Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGDebugInfo.h
35234 views
//===--- CGDebugInfo.h - DebugInfo for LLVM CodeGen -------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This is the source-level debug info generator for llvm translation.9//10//===----------------------------------------------------------------------===//1112#ifndef LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H13#define LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H1415#include "CGBuilder.h"16#include "clang/AST/DeclCXX.h"17#include "clang/AST/Expr.h"18#include "clang/AST/ExternalASTSource.h"19#include "clang/AST/PrettyPrinter.h"20#include "clang/AST/Type.h"21#include "clang/AST/TypeOrdering.h"22#include "clang/Basic/ASTSourceDescriptor.h"23#include "clang/Basic/CodeGenOptions.h"24#include "clang/Basic/SourceLocation.h"25#include "llvm/ADT/DenseMap.h"26#include "llvm/ADT/DenseSet.h"27#include "llvm/IR/DIBuilder.h"28#include "llvm/IR/DebugInfo.h"29#include "llvm/IR/ValueHandle.h"30#include "llvm/Support/Allocator.h"31#include <map>32#include <optional>33#include <string>3435namespace llvm {36class MDNode;37}3839namespace clang {40class ClassTemplateSpecializationDecl;41class GlobalDecl;42class Module;43class ModuleMap;44class ObjCInterfaceDecl;45class UsingDecl;46class VarDecl;47enum class DynamicInitKind : unsigned;4849namespace CodeGen {50class CodeGenModule;51class CodeGenFunction;52class CGBlockInfo;5354/// This class gathers all debug information during compilation and is55/// responsible for emitting to llvm globals or pass directly to the56/// backend.57class CGDebugInfo {58friend class ApplyDebugLocation;59friend class SaveAndRestoreLocation;60CodeGenModule &CGM;61const llvm::codegenoptions::DebugInfoKind DebugKind;62bool DebugTypeExtRefs;63llvm::DIBuilder DBuilder;64llvm::DICompileUnit *TheCU = nullptr;65ModuleMap *ClangModuleMap = nullptr;66ASTSourceDescriptor PCHDescriptor;67SourceLocation CurLoc;68llvm::MDNode *CurInlinedAt = nullptr;69llvm::DIType *VTablePtrType = nullptr;70llvm::DIType *ClassTy = nullptr;71llvm::DICompositeType *ObjTy = nullptr;72llvm::DIType *SelTy = nullptr;73#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \74llvm::DIType *SingletonId = nullptr;75#include "clang/Basic/OpenCLImageTypes.def"76llvm::DIType *OCLSamplerDITy = nullptr;77llvm::DIType *OCLEventDITy = nullptr;78llvm::DIType *OCLClkEventDITy = nullptr;79llvm::DIType *OCLQueueDITy = nullptr;80llvm::DIType *OCLNDRangeDITy = nullptr;81llvm::DIType *OCLReserveIDDITy = nullptr;82#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \83llvm::DIType *Id##Ty = nullptr;84#include "clang/Basic/OpenCLExtensionTypes.def"85#define WASM_TYPE(Name, Id, SingletonId) llvm::DIType *SingletonId = nullptr;86#include "clang/Basic/WebAssemblyReferenceTypes.def"87#define AMDGPU_TYPE(Name, Id, SingletonId) llvm::DIType *SingletonId = nullptr;88#include "clang/Basic/AMDGPUTypes.def"8990/// Cache of previously constructed Types.91llvm::DenseMap<const void *, llvm::TrackingMDRef> TypeCache;9293/// Cache that maps VLA types to size expressions for that type,94/// represented by instantiated Metadata nodes.95llvm::SmallDenseMap<QualType, llvm::Metadata *> SizeExprCache;9697/// Callbacks to use when printing names and types.98class PrintingCallbacks final : public clang::PrintingCallbacks {99const CGDebugInfo &Self;100101public:102PrintingCallbacks(const CGDebugInfo &Self) : Self(Self) {}103std::string remapPath(StringRef Path) const override {104return Self.remapDIPath(Path);105}106};107PrintingCallbacks PrintCB = {*this};108109struct ObjCInterfaceCacheEntry {110const ObjCInterfaceType *Type;111llvm::DIType *Decl;112llvm::DIFile *Unit;113ObjCInterfaceCacheEntry(const ObjCInterfaceType *Type, llvm::DIType *Decl,114llvm::DIFile *Unit)115: Type(Type), Decl(Decl), Unit(Unit) {}116};117118/// Cache of previously constructed interfaces which may change.119llvm::SmallVector<ObjCInterfaceCacheEntry, 32> ObjCInterfaceCache;120121/// Cache of forward declarations for methods belonging to the interface.122/// The extra bit on the DISubprogram specifies whether a method is123/// "objc_direct".124llvm::DenseMap<const ObjCInterfaceDecl *,125std::vector<llvm::PointerIntPair<llvm::DISubprogram *, 1>>>126ObjCMethodCache;127128/// Cache of references to clang modules and precompiled headers.129llvm::DenseMap<const Module *, llvm::TrackingMDRef> ModuleCache;130131/// List of interfaces we want to keep even if orphaned.132std::vector<void *> RetainedTypes;133134/// Cache of forward declared types to RAUW at the end of compilation.135std::vector<std::pair<const TagType *, llvm::TrackingMDRef>> ReplaceMap;136137/// Cache of replaceable forward declarations (functions and138/// variables) to RAUW at the end of compilation.139std::vector<std::pair<const DeclaratorDecl *, llvm::TrackingMDRef>>140FwdDeclReplaceMap;141142/// Keep track of our current nested lexical block.143std::vector<llvm::TypedTrackingMDRef<llvm::DIScope>> LexicalBlockStack;144llvm::DenseMap<const Decl *, llvm::TrackingMDRef> RegionMap;145/// Keep track of LexicalBlockStack counter at the beginning of a146/// function. This is used to pop unbalanced regions at the end of a147/// function.148std::vector<unsigned> FnBeginRegionCount;149150/// This is a storage for names that are constructed on demand. For151/// example, C++ destructors, C++ operators etc..152llvm::BumpPtrAllocator DebugInfoNames;153StringRef CWDName;154155llvm::DenseMap<const char *, llvm::TrackingMDRef> DIFileCache;156llvm::DenseMap<const FunctionDecl *, llvm::TrackingMDRef> SPCache;157/// Cache declarations relevant to DW_TAG_imported_declarations (C++158/// using declarations and global alias variables) that aren't covered159/// by other more specific caches.160llvm::DenseMap<const Decl *, llvm::TrackingMDRef> DeclCache;161llvm::DenseMap<const Decl *, llvm::TrackingMDRef> ImportedDeclCache;162llvm::DenseMap<const NamespaceDecl *, llvm::TrackingMDRef> NamespaceCache;163llvm::DenseMap<const NamespaceAliasDecl *, llvm::TrackingMDRef>164NamespaceAliasCache;165llvm::DenseMap<const Decl *, llvm::TypedTrackingMDRef<llvm::DIDerivedType>>166StaticDataMemberCache;167168using ParamDecl2StmtTy = llvm::DenseMap<const ParmVarDecl *, const Stmt *>;169using Param2DILocTy =170llvm::DenseMap<const ParmVarDecl *, llvm::DILocalVariable *>;171172/// The key is coroutine real parameters, value is coroutine move parameters.173ParamDecl2StmtTy CoroutineParameterMappings;174/// The key is coroutine real parameters, value is DIVariable in LLVM IR.175Param2DILocTy ParamDbgMappings;176177/// Helper functions for getOrCreateType.178/// @{179/// Currently the checksum of an interface includes the number of180/// ivars and property accessors.181llvm::DIType *CreateType(const BuiltinType *Ty);182llvm::DIType *CreateType(const ComplexType *Ty);183llvm::DIType *CreateType(const BitIntType *Ty);184llvm::DIType *CreateQualifiedType(QualType Ty, llvm::DIFile *Fg);185llvm::DIType *CreateQualifiedType(const FunctionProtoType *Ty,186llvm::DIFile *Fg);187llvm::DIType *CreateType(const TypedefType *Ty, llvm::DIFile *Fg);188llvm::DIType *CreateType(const TemplateSpecializationType *Ty,189llvm::DIFile *Fg);190llvm::DIType *CreateType(const ObjCObjectPointerType *Ty, llvm::DIFile *F);191llvm::DIType *CreateType(const PointerType *Ty, llvm::DIFile *F);192llvm::DIType *CreateType(const BlockPointerType *Ty, llvm::DIFile *F);193llvm::DIType *CreateType(const FunctionType *Ty, llvm::DIFile *F);194/// Get structure or union type.195llvm::DIType *CreateType(const RecordType *Tyg);196197/// Create definition for the specified 'Ty'.198///199/// \returns A pair of 'llvm::DIType's. The first is the definition200/// of the 'Ty'. The second is the type specified by the preferred_name201/// attribute on 'Ty', which can be a nullptr if no such attribute202/// exists.203std::pair<llvm::DIType *, llvm::DIType *>204CreateTypeDefinition(const RecordType *Ty);205llvm::DICompositeType *CreateLimitedType(const RecordType *Ty);206void CollectContainingType(const CXXRecordDecl *RD,207llvm::DICompositeType *CT);208/// Get Objective-C interface type.209llvm::DIType *CreateType(const ObjCInterfaceType *Ty, llvm::DIFile *F);210llvm::DIType *CreateTypeDefinition(const ObjCInterfaceType *Ty,211llvm::DIFile *F);212/// Get Objective-C object type.213llvm::DIType *CreateType(const ObjCObjectType *Ty, llvm::DIFile *F);214llvm::DIType *CreateType(const ObjCTypeParamType *Ty, llvm::DIFile *Unit);215216llvm::DIType *CreateType(const VectorType *Ty, llvm::DIFile *F);217llvm::DIType *CreateType(const ConstantMatrixType *Ty, llvm::DIFile *F);218llvm::DIType *CreateType(const ArrayType *Ty, llvm::DIFile *F);219llvm::DIType *CreateType(const LValueReferenceType *Ty, llvm::DIFile *F);220llvm::DIType *CreateType(const RValueReferenceType *Ty, llvm::DIFile *Unit);221llvm::DIType *CreateType(const MemberPointerType *Ty, llvm::DIFile *F);222llvm::DIType *CreateType(const AtomicType *Ty, llvm::DIFile *F);223llvm::DIType *CreateType(const PipeType *Ty, llvm::DIFile *F);224/// Get enumeration type.225llvm::DIType *CreateEnumType(const EnumType *Ty);226llvm::DIType *CreateTypeDefinition(const EnumType *Ty);227/// Look up the completed type for a self pointer in the TypeCache and228/// create a copy of it with the ObjectPointer and Artificial flags229/// set. If the type is not cached, a new one is created. This should230/// never happen though, since creating a type for the implicit self231/// argument implies that we already parsed the interface definition232/// and the ivar declarations in the implementation.233llvm::DIType *CreateSelfType(const QualType &QualTy, llvm::DIType *Ty);234/// @}235236/// Get the type from the cache or return null type if it doesn't237/// exist.238llvm::DIType *getTypeOrNull(const QualType);239/// Return the debug type for a C++ method.240/// \arg CXXMethodDecl is of FunctionType. This function type is241/// not updated to include implicit \c this pointer. Use this routine242/// to get a method type which includes \c this pointer.243llvm::DISubroutineType *getOrCreateMethodType(const CXXMethodDecl *Method,244llvm::DIFile *F);245llvm::DISubroutineType *246getOrCreateInstanceMethodType(QualType ThisPtr, const FunctionProtoType *Func,247llvm::DIFile *Unit);248llvm::DISubroutineType *249getOrCreateFunctionType(const Decl *D, QualType FnType, llvm::DIFile *F);250/// \return debug info descriptor for vtable.251llvm::DIType *getOrCreateVTablePtrType(llvm::DIFile *F);252253/// \return namespace descriptor for the given namespace decl.254llvm::DINamespace *getOrCreateNamespace(const NamespaceDecl *N);255llvm::DIType *CreatePointerLikeType(llvm::dwarf::Tag Tag, const Type *Ty,256QualType PointeeTy, llvm::DIFile *F);257llvm::DIType *getOrCreateStructPtrType(StringRef Name, llvm::DIType *&Cache);258259/// A helper function to create a subprogram for a single member260/// function GlobalDecl.261llvm::DISubprogram *CreateCXXMemberFunction(const CXXMethodDecl *Method,262llvm::DIFile *F,263llvm::DIType *RecordTy);264265/// A helper function to collect debug info for C++ member266/// functions. This is used while creating debug info entry for a267/// Record.268void CollectCXXMemberFunctions(const CXXRecordDecl *Decl, llvm::DIFile *F,269SmallVectorImpl<llvm::Metadata *> &E,270llvm::DIType *T);271272/// A helper function to collect debug info for C++ base273/// classes. This is used while creating debug info entry for a274/// Record.275void CollectCXXBases(const CXXRecordDecl *Decl, llvm::DIFile *F,276SmallVectorImpl<llvm::Metadata *> &EltTys,277llvm::DIType *RecordTy);278279/// Helper function for CollectCXXBases.280/// Adds debug info entries for types in Bases that are not in SeenTypes.281void CollectCXXBasesAux(282const CXXRecordDecl *RD, llvm::DIFile *Unit,283SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,284const CXXRecordDecl::base_class_const_range &Bases,285llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,286llvm::DINode::DIFlags StartingFlags);287288/// Helper function that returns the llvm::DIType that the289/// PreferredNameAttr attribute on \ref RD refers to. If no such290/// attribute exists, returns nullptr.291llvm::DIType *GetPreferredNameType(const CXXRecordDecl *RD,292llvm::DIFile *Unit);293294struct TemplateArgs {295const TemplateParameterList *TList;296llvm::ArrayRef<TemplateArgument> Args;297};298/// A helper function to collect template parameters.299llvm::DINodeArray CollectTemplateParams(std::optional<TemplateArgs> Args,300llvm::DIFile *Unit);301/// A helper function to collect debug info for function template302/// parameters.303llvm::DINodeArray CollectFunctionTemplateParams(const FunctionDecl *FD,304llvm::DIFile *Unit);305306/// A helper function to collect debug info for function template307/// parameters.308llvm::DINodeArray CollectVarTemplateParams(const VarDecl *VD,309llvm::DIFile *Unit);310311std::optional<TemplateArgs> GetTemplateArgs(const VarDecl *) const;312std::optional<TemplateArgs> GetTemplateArgs(const RecordDecl *) const;313std::optional<TemplateArgs> GetTemplateArgs(const FunctionDecl *) const;314315/// A helper function to collect debug info for template316/// parameters.317llvm::DINodeArray CollectCXXTemplateParams(const RecordDecl *TS,318llvm::DIFile *F);319320/// A helper function to collect debug info for btf_decl_tag annotations.321llvm::DINodeArray CollectBTFDeclTagAnnotations(const Decl *D);322323llvm::DIType *createFieldType(StringRef name, QualType type,324SourceLocation loc, AccessSpecifier AS,325uint64_t offsetInBits, uint32_t AlignInBits,326llvm::DIFile *tunit, llvm::DIScope *scope,327const RecordDecl *RD = nullptr,328llvm::DINodeArray Annotations = nullptr);329330llvm::DIType *createFieldType(StringRef name, QualType type,331SourceLocation loc, AccessSpecifier AS,332uint64_t offsetInBits, llvm::DIFile *tunit,333llvm::DIScope *scope,334const RecordDecl *RD = nullptr) {335return createFieldType(name, type, loc, AS, offsetInBits, 0, tunit, scope,336RD);337}338339/// Create new bit field member.340llvm::DIDerivedType *createBitFieldType(const FieldDecl *BitFieldDecl,341llvm::DIScope *RecordTy,342const RecordDecl *RD);343344/// Create an anonnymous zero-size separator for bit-field-decl if needed on345/// the target.346llvm::DIDerivedType *createBitFieldSeparatorIfNeeded(347const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI,348llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD);349350/// A cache that maps names of artificial inlined functions to subprograms.351llvm::StringMap<llvm::DISubprogram *> InlinedTrapFuncMap;352353/// A function that returns the subprogram corresponding to the artificial354/// inlined function for traps.355llvm::DISubprogram *createInlinedTrapSubprogram(StringRef FuncName,356llvm::DIFile *FileScope);357358/// Helpers for collecting fields of a record.359/// @{360void CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,361SmallVectorImpl<llvm::Metadata *> &E,362llvm::DIType *RecordTy);363llvm::DIDerivedType *CreateRecordStaticField(const VarDecl *Var,364llvm::DIType *RecordTy,365const RecordDecl *RD);366void CollectRecordNormalField(const FieldDecl *Field, uint64_t OffsetInBits,367llvm::DIFile *F,368SmallVectorImpl<llvm::Metadata *> &E,369llvm::DIType *RecordTy, const RecordDecl *RD);370void CollectRecordNestedType(const TypeDecl *RD,371SmallVectorImpl<llvm::Metadata *> &E);372void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile *F,373SmallVectorImpl<llvm::Metadata *> &E,374llvm::DICompositeType *RecordTy);375376/// If the C++ class has vtable info then insert appropriate debug377/// info entry in EltTys vector.378void CollectVTableInfo(const CXXRecordDecl *Decl, llvm::DIFile *F,379SmallVectorImpl<llvm::Metadata *> &EltTys);380/// @}381382/// Create a new lexical block node and push it on the stack.383void CreateLexicalBlock(SourceLocation Loc);384385/// If target-specific LLVM \p AddressSpace directly maps to target-specific386/// DWARF address space, appends extended dereferencing mechanism to complex387/// expression \p Expr. Otherwise, does nothing.388///389/// Extended dereferencing mechanism is has the following format:390/// DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef391void AppendAddressSpaceXDeref(unsigned AddressSpace,392SmallVectorImpl<uint64_t> &Expr) const;393394/// A helper function to collect debug info for the default elements of a395/// block.396///397/// \returns The next available field offset after the default elements.398uint64_t collectDefaultElementTypesForBlockPointer(399const BlockPointerType *Ty, llvm::DIFile *Unit,400llvm::DIDerivedType *DescTy, unsigned LineNo,401SmallVectorImpl<llvm::Metadata *> &EltTys);402403/// A helper function to collect debug info for the default fields of a404/// block.405void collectDefaultFieldsForBlockLiteralDeclare(406const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,407const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,408SmallVectorImpl<llvm::Metadata *> &Fields);409410public:411CGDebugInfo(CodeGenModule &CGM);412~CGDebugInfo();413414void finalize();415416/// Remap a given path with the current debug prefix map417std::string remapDIPath(StringRef) const;418419/// Register VLA size expression debug node with the qualified type.420void registerVLASizeExpression(QualType Ty, llvm::Metadata *SizeExpr) {421SizeExprCache[Ty] = SizeExpr;422}423424/// Module debugging: Support for building PCMs.425/// @{426/// Set the main CU's DwoId field to \p Signature.427void setDwoId(uint64_t Signature);428429/// When generating debug information for a clang module or430/// precompiled header, this module map will be used to determine431/// the module of origin of each Decl.432void setModuleMap(ModuleMap &MMap) { ClangModuleMap = &MMap; }433434/// When generating debug information for a clang module or435/// precompiled header, this module map will be used to determine436/// the module of origin of each Decl.437void setPCHDescriptor(ASTSourceDescriptor PCH) { PCHDescriptor = PCH; }438/// @}439440/// Update the current source location. If \arg loc is invalid it is441/// ignored.442void setLocation(SourceLocation Loc);443444/// Return the current source location. This does not necessarily correspond445/// to the IRBuilder's current DebugLoc.446SourceLocation getLocation() const { return CurLoc; }447448/// Update the current inline scope. All subsequent calls to \p EmitLocation449/// will create a location with this inlinedAt field.450void setInlinedAt(llvm::MDNode *InlinedAt) { CurInlinedAt = InlinedAt; }451452/// \return the current inline scope.453llvm::MDNode *getInlinedAt() const { return CurInlinedAt; }454455// Converts a SourceLocation to a DebugLoc456llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Loc);457458/// Emit metadata to indicate a change in line/column information in459/// the source file. If the location is invalid, the previous460/// location will be reused.461void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc);462463QualType getFunctionType(const FunctionDecl *FD, QualType RetTy,464const SmallVectorImpl<const VarDecl *> &Args);465466/// Emit a call to llvm.dbg.function.start to indicate467/// start of a new function.468/// \param Loc The location of the function header.469/// \param ScopeLoc The location of the function body.470void emitFunctionStart(GlobalDecl GD, SourceLocation Loc,471SourceLocation ScopeLoc, QualType FnType,472llvm::Function *Fn, bool CurFnIsThunk);473474/// Start a new scope for an inlined function.475void EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD);476/// End an inlined function scope.477void EmitInlineFunctionEnd(CGBuilderTy &Builder);478479/// Emit debug info for a function declaration.480/// \p Fn is set only when a declaration for a debug call site gets created.481void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,482QualType FnType, llvm::Function *Fn = nullptr);483484/// Emit debug info for an extern function being called.485/// This is needed for call site debug info.486void EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,487QualType CalleeType,488const FunctionDecl *CalleeDecl);489490/// Constructs the debug code for exiting a function.491void EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn);492493/// Emit metadata to indicate the beginning of a new lexical block494/// and push the block onto the stack.495void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc);496497/// Emit metadata to indicate the end of a new lexical block and pop498/// the current block.499void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc);500501/// Emit call to \c llvm.dbg.declare for an automatic variable502/// declaration.503/// Returns a pointer to the DILocalVariable associated with the504/// llvm.dbg.declare, or nullptr otherwise.505llvm::DILocalVariable *506EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI,507CGBuilderTy &Builder,508const bool UsePointerValue = false);509510/// Emit call to \c llvm.dbg.label for an label.511void EmitLabel(const LabelDecl *D, CGBuilderTy &Builder);512513/// Emit call to \c llvm.dbg.declare for an imported variable514/// declaration in a block.515void EmitDeclareOfBlockDeclRefVariable(516const VarDecl *variable, llvm::Value *storage, CGBuilderTy &Builder,517const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint = nullptr);518519/// Emit call to \c llvm.dbg.declare for an argument variable520/// declaration.521llvm::DILocalVariable *522EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, unsigned ArgNo,523CGBuilderTy &Builder, bool UsePointerValue = false);524525/// Emit call to \c llvm.dbg.declare for the block-literal argument526/// to a block invocation function.527void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,528StringRef Name, unsigned ArgNo,529llvm::AllocaInst *LocalAddr,530CGBuilderTy &Builder);531532/// Emit information about a global variable.533void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);534535/// Emit a constant global variable's debug info.536void EmitGlobalVariable(const ValueDecl *VD, const APValue &Init);537538/// Emit information about an external variable.539void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);540541/// Emit a pseudo variable and debug info for an intermediate value if it does542/// not correspond to a variable in the source code, so that a profiler can543/// track more accurate usage of certain instructions of interest.544void EmitPseudoVariable(CGBuilderTy &Builder, llvm::Instruction *Value,545QualType Ty);546547/// Emit information about global variable alias.548void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl);549550/// Emit C++ using directive.551void EmitUsingDirective(const UsingDirectiveDecl &UD);552553/// Emit the type explicitly casted to.554void EmitExplicitCastType(QualType Ty);555556/// Emit the type even if it might not be used.557void EmitAndRetainType(QualType Ty);558559/// Emit a shadow decl brought in by a using or using-enum560void EmitUsingShadowDecl(const UsingShadowDecl &USD);561562/// Emit C++ using declaration.563void EmitUsingDecl(const UsingDecl &UD);564565/// Emit C++ using-enum declaration.566void EmitUsingEnumDecl(const UsingEnumDecl &UD);567568/// Emit an @import declaration.569void EmitImportDecl(const ImportDecl &ID);570571/// DebugInfo isn't attached to string literals by default. While certain572/// aspects of debuginfo aren't useful for string literals (like a name), it's573/// nice to be able to symbolize the line and column information. This is574/// especially useful for sanitizers, as it allows symbolization of575/// heap-buffer-overflows on constant strings.576void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,577const StringLiteral *S);578579/// Emit C++ namespace alias.580llvm::DIImportedEntity *EmitNamespaceAlias(const NamespaceAliasDecl &NA);581582/// Emit record type's standalone debug info.583llvm::DIType *getOrCreateRecordType(QualType Ty, SourceLocation L);584585/// Emit an Objective-C interface type standalone debug info.586llvm::DIType *getOrCreateInterfaceType(QualType Ty, SourceLocation Loc);587588/// Emit standalone debug info for a type.589llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);590591/// Add heapallocsite metadata for MSAllocator calls.592void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy,593SourceLocation Loc);594595void completeType(const EnumDecl *ED);596void completeType(const RecordDecl *RD);597void completeRequiredType(const RecordDecl *RD);598void completeClassData(const RecordDecl *RD);599void completeClass(const RecordDecl *RD);600601void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD);602void completeUnusedClass(const CXXRecordDecl &D);603604/// Create debug info for a macro defined by a #define directive or a macro605/// undefined by a #undef directive.606llvm::DIMacro *CreateMacro(llvm::DIMacroFile *Parent, unsigned MType,607SourceLocation LineLoc, StringRef Name,608StringRef Value);609610/// Create debug info for a file referenced by an #include directive.611llvm::DIMacroFile *CreateTempMacroFile(llvm::DIMacroFile *Parent,612SourceLocation LineLoc,613SourceLocation FileLoc);614615Param2DILocTy &getParamDbgMappings() { return ParamDbgMappings; }616ParamDecl2StmtTy &getCoroutineParameterMappings() {617return CoroutineParameterMappings;618}619620/// Create a debug location from `TrapLocation` that adds an artificial inline621/// frame where the frame name is622///623/// * `<Prefix>:<Category>:<FailureMsg>`624///625/// `<Prefix>` is "__clang_trap_msg".626///627/// This is used to store failure reasons for traps.628llvm::DILocation *CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation,629StringRef Category,630StringRef FailureMsg);631632private:633/// Emit call to llvm.dbg.declare for a variable declaration.634/// Returns a pointer to the DILocalVariable associated with the635/// llvm.dbg.declare, or nullptr otherwise.636llvm::DILocalVariable *EmitDeclare(const VarDecl *decl, llvm::Value *AI,637std::optional<unsigned> ArgNo,638CGBuilderTy &Builder,639const bool UsePointerValue = false);640641/// Emit call to llvm.dbg.declare for a binding declaration.642/// Returns a pointer to the DILocalVariable associated with the643/// llvm.dbg.declare, or nullptr otherwise.644llvm::DILocalVariable *EmitDeclare(const BindingDecl *decl, llvm::Value *AI,645std::optional<unsigned> ArgNo,646CGBuilderTy &Builder,647const bool UsePointerValue = false);648649struct BlockByRefType {650/// The wrapper struct used inside the __block_literal struct.651llvm::DIType *BlockByRefWrapper;652/// The type as it appears in the source code.653llvm::DIType *WrappedType;654};655656bool HasReconstitutableArgs(ArrayRef<TemplateArgument> Args) const;657std::string GetName(const Decl *, bool Qualified = false) const;658659/// Build up structure info for the byref. See \a BuildByRefType.660BlockByRefType EmitTypeForVarWithBlocksAttr(const VarDecl *VD,661uint64_t *OffSet);662663/// Get context info for the DeclContext of \p Decl.664llvm::DIScope *getDeclContextDescriptor(const Decl *D);665/// Get context info for a given DeclContext \p Decl.666llvm::DIScope *getContextDescriptor(const Decl *Context,667llvm::DIScope *Default);668669llvm::DIScope *getCurrentContextDescriptor(const Decl *Decl);670671/// Create a forward decl for a RecordType in a given context.672llvm::DICompositeType *getOrCreateRecordFwdDecl(const RecordType *,673llvm::DIScope *);674675/// Return current directory name.676StringRef getCurrentDirname();677678/// Create new compile unit.679void CreateCompileUnit();680681/// Compute the file checksum debug info for input file ID.682std::optional<llvm::DIFile::ChecksumKind>683computeChecksum(FileID FID, SmallString<64> &Checksum) const;684685/// Get the source of the given file ID.686std::optional<StringRef> getSource(const SourceManager &SM, FileID FID);687688/// Convenience function to get the file debug info descriptor for the input689/// location.690llvm::DIFile *getOrCreateFile(SourceLocation Loc);691692/// Create a file debug info descriptor for a source file.693llvm::DIFile *694createFile(StringRef FileName,695std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,696std::optional<StringRef> Source);697698/// Get the type from the cache or create a new type if necessary.699llvm::DIType *getOrCreateType(QualType Ty, llvm::DIFile *Fg);700701/// Get a reference to a clang module. If \p CreateSkeletonCU is true,702/// this also creates a split dwarf skeleton compile unit.703llvm::DIModule *getOrCreateModuleRef(ASTSourceDescriptor Mod,704bool CreateSkeletonCU);705706/// DebugTypeExtRefs: If \p D originated in a clang module, return it.707llvm::DIModule *getParentModuleOrNull(const Decl *D);708709/// Get the type from the cache or create a new partial type if710/// necessary.711llvm::DICompositeType *getOrCreateLimitedType(const RecordType *Ty);712713/// Create type metadata for a source language type.714llvm::DIType *CreateTypeNode(QualType Ty, llvm::DIFile *Fg);715716/// Create new member and increase Offset by FType's size.717llvm::DIType *CreateMemberType(llvm::DIFile *Unit, QualType FType,718StringRef Name, uint64_t *Offset);719720/// Retrieve the DIDescriptor, if any, for the canonical form of this721/// declaration.722llvm::DINode *getDeclarationOrDefinition(const Decl *D);723724/// \return debug info descriptor to describe method725/// declaration for the given method definition.726llvm::DISubprogram *getFunctionDeclaration(const Decl *D);727728/// \return debug info descriptor to the describe method declaration729/// for the given method definition.730/// \param FnType For Objective-C methods, their type.731/// \param LineNo The declaration's line number.732/// \param Flags The DIFlags for the method declaration.733/// \param SPFlags The subprogram-spcific flags for the method declaration.734llvm::DISubprogram *735getObjCMethodDeclaration(const Decl *D, llvm::DISubroutineType *FnType,736unsigned LineNo, llvm::DINode::DIFlags Flags,737llvm::DISubprogram::DISPFlags SPFlags);738739/// \return debug info descriptor to describe in-class static data740/// member declaration for the given out-of-class definition. If D741/// is an out-of-class definition of a static data member of a742/// class, find its corresponding in-class declaration.743llvm::DIDerivedType *744getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D);745746/// Helper that either creates a forward declaration or a stub.747llvm::DISubprogram *getFunctionFwdDeclOrStub(GlobalDecl GD, bool Stub);748749/// Create a subprogram describing the forward declaration750/// represented in the given FunctionDecl wrapped in a GlobalDecl.751llvm::DISubprogram *getFunctionForwardDeclaration(GlobalDecl GD);752753/// Create a DISubprogram describing the function754/// represented in the given FunctionDecl wrapped in a GlobalDecl.755llvm::DISubprogram *getFunctionStub(GlobalDecl GD);756757/// Create a global variable describing the forward declaration758/// represented in the given VarDecl.759llvm::DIGlobalVariable *760getGlobalVariableForwardDeclaration(const VarDecl *VD);761762/// Return a global variable that represents one of the collection of global763/// variables created for an anonmyous union.764///765/// Recursively collect all of the member fields of a global766/// anonymous decl and create static variables for them. The first767/// time this is called it needs to be on a union and then from768/// there we can have additional unnamed fields.769llvm::DIGlobalVariableExpression *770CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile *Unit,771unsigned LineNo, StringRef LinkageName,772llvm::GlobalVariable *Var, llvm::DIScope *DContext);773774775/// Return flags which enable debug info emission for call sites, provided776/// that it is supported and enabled.777llvm::DINode::DIFlags getCallSiteRelatedAttrs() const;778779/// Get the printing policy for producing names for debug info.780PrintingPolicy getPrintingPolicy() const;781782/// Get function name for the given FunctionDecl. If the name is783/// constructed on demand (e.g., C++ destructor) then the name is784/// stored on the side.785StringRef getFunctionName(const FunctionDecl *FD);786787/// Returns the unmangled name of an Objective-C method.788/// This is the display name for the debugging info.789StringRef getObjCMethodName(const ObjCMethodDecl *FD);790791/// Return selector name. This is used for debugging792/// info.793StringRef getSelectorName(Selector S);794795/// Get class name including template argument list.796StringRef getClassName(const RecordDecl *RD);797798/// Get the vtable name for the given class.799StringRef getVTableName(const CXXRecordDecl *Decl);800801/// Get the name to use in the debug info for a dynamic initializer or atexit802/// stub function.803StringRef getDynamicInitializerName(const VarDecl *VD,804DynamicInitKind StubKind,805llvm::Function *InitFn);806807/// Get line number for the location. If location is invalid808/// then use current location.809unsigned getLineNumber(SourceLocation Loc);810811/// Get column number for the location. If location is812/// invalid then use current location.813/// \param Force Assume DebugColumnInfo option is true.814unsigned getColumnNumber(SourceLocation Loc, bool Force = false);815816/// Collect various properties of a FunctionDecl.817/// \param GD A GlobalDecl whose getDecl() must return a FunctionDecl.818void collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,819StringRef &Name, StringRef &LinkageName,820llvm::DIScope *&FDContext,821llvm::DINodeArray &TParamsArray,822llvm::DINode::DIFlags &Flags);823824/// Collect various properties of a VarDecl.825void collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,826unsigned &LineNo, QualType &T, StringRef &Name,827StringRef &LinkageName,828llvm::MDTuple *&TemplateParameters,829llvm::DIScope *&VDContext);830831/// Create a DIExpression representing the constant corresponding832/// to the specified 'Val'. Returns nullptr on failure.833llvm::DIExpression *createConstantValueExpression(const clang::ValueDecl *VD,834const APValue &Val);835836/// Allocate a copy of \p A using the DebugInfoNames allocator837/// and return a reference to it. If multiple arguments are given the strings838/// are concatenated.839StringRef internString(StringRef A, StringRef B = StringRef()) {840char *Data = DebugInfoNames.Allocate<char>(A.size() + B.size());841if (!A.empty())842std::memcpy(Data, A.data(), A.size());843if (!B.empty())844std::memcpy(Data + A.size(), B.data(), B.size());845return StringRef(Data, A.size() + B.size());846}847};848849/// A scoped helper to set the current debug location to the specified850/// location or preferred location of the specified Expr.851class ApplyDebugLocation {852private:853void init(SourceLocation TemporaryLocation, bool DefaultToEmpty = false);854ApplyDebugLocation(CodeGenFunction &CGF, bool DefaultToEmpty,855SourceLocation TemporaryLocation);856857llvm::DebugLoc OriginalLocation;858CodeGenFunction *CGF;859860public:861/// Set the location to the (valid) TemporaryLocation.862ApplyDebugLocation(CodeGenFunction &CGF, SourceLocation TemporaryLocation);863ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E);864ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc);865ApplyDebugLocation(ApplyDebugLocation &&Other) : CGF(Other.CGF) {866Other.CGF = nullptr;867}868869// Define copy assignment operator.870ApplyDebugLocation &operator=(ApplyDebugLocation &&Other) {871if (this != &Other) {872CGF = Other.CGF;873Other.CGF = nullptr;874}875return *this;876}877878~ApplyDebugLocation();879880/// Apply TemporaryLocation if it is valid. Otherwise switch881/// to an artificial debug location that has a valid scope, but no882/// line information.883///884/// Artificial locations are useful when emitting compiler-generated885/// helper functions that have no source location associated with886/// them. The DWARF specification allows the compiler to use the887/// special line number 0 to indicate code that can not be888/// attributed to any source location. Note that passing an empty889/// SourceLocation to CGDebugInfo::setLocation() will result in the890/// last valid location being reused.891static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF) {892return ApplyDebugLocation(CGF, false, SourceLocation());893}894/// Apply TemporaryLocation if it is valid. Otherwise switch895/// to an artificial debug location that has a valid scope, but no896/// line information.897static ApplyDebugLocation898CreateDefaultArtificial(CodeGenFunction &CGF,899SourceLocation TemporaryLocation) {900return ApplyDebugLocation(CGF, false, TemporaryLocation);901}902903/// Set the IRBuilder to not attach debug locations. Note that904/// passing an empty SourceLocation to \a CGDebugInfo::setLocation()905/// will result in the last valid location being reused. Note that906/// all instructions that do not have a location at the beginning of907/// a function are counted towards to function prologue.908static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF) {909return ApplyDebugLocation(CGF, true, SourceLocation());910}911};912913/// A scoped helper to set the current debug location to an inlined location.914class ApplyInlineDebugLocation {915SourceLocation SavedLocation;916CodeGenFunction *CGF;917918public:919/// Set up the CodeGenFunction's DebugInfo to produce inline locations for the920/// function \p InlinedFn. The current debug location becomes the inlined call921/// site of the inlined function.922ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn);923/// Restore everything back to the original state.924~ApplyInlineDebugLocation();925};926927} // namespace CodeGen928} // namespace clang929930#endif // LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H931932933