CGDebugInfo.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. //===--- CGDebugInfo.h - DebugInfo for LLVM CodeGen -------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This is the source-level debug info generator for llvm translation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
  13. #define LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
  14. #include "CGBuilder.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/ExternalASTSource.h"
  18. #include "clang/AST/PrettyPrinter.h"
  19. #include "clang/AST/Type.h"
  20. #include "clang/AST/TypeOrdering.h"
  21. #include "clang/Basic/CodeGenOptions.h"
  22. #include "clang/Basic/Module.h"
  23. #include "clang/Basic/SourceLocation.h"
  24. #include "llvm/ADT/DenseMap.h"
  25. #include "llvm/ADT/DenseSet.h"
  26. #include "llvm/IR/DIBuilder.h"
  27. #include "llvm/IR/DebugInfo.h"
  28. #include "llvm/IR/ValueHandle.h"
  29. #include "llvm/Support/Allocator.h"
  30. #include <optional>
  31. namespace llvm {
  32. class MDNode;
  33. }
  34. namespace clang {
  35. class ClassTemplateSpecializationDecl;
  36. class GlobalDecl;
  37. class ModuleMap;
  38. class ObjCInterfaceDecl;
  39. class UsingDecl;
  40. class VarDecl;
  41. enum class DynamicInitKind : unsigned;
  42. namespace CodeGen {
  43. class CodeGenModule;
  44. class CodeGenFunction;
  45. class CGBlockInfo;
  46. /// This class gathers all debug information during compilation and is
  47. /// responsible for emitting to llvm globals or pass directly to the
  48. /// backend.
  49. class CGDebugInfo {
  50. friend class ApplyDebugLocation;
  51. friend class SaveAndRestoreLocation;
  52. CodeGenModule &CGM;
  53. const codegenoptions::DebugInfoKind DebugKind;
  54. bool DebugTypeExtRefs;
  55. llvm::DIBuilder DBuilder;
  56. llvm::DICompileUnit *TheCU = nullptr;
  57. ModuleMap *ClangModuleMap = nullptr;
  58. ASTSourceDescriptor PCHDescriptor;
  59. SourceLocation CurLoc;
  60. llvm::MDNode *CurInlinedAt = nullptr;
  61. llvm::DIType *VTablePtrType = nullptr;
  62. llvm::DIType *ClassTy = nullptr;
  63. llvm::DICompositeType *ObjTy = nullptr;
  64. llvm::DIType *SelTy = nullptr;
  65. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  66. llvm::DIType *SingletonId = nullptr;
  67. #include "clang/Basic/OpenCLImageTypes.def"
  68. llvm::DIType *OCLSamplerDITy = nullptr;
  69. llvm::DIType *OCLEventDITy = nullptr;
  70. llvm::DIType *OCLClkEventDITy = nullptr;
  71. llvm::DIType *OCLQueueDITy = nullptr;
  72. llvm::DIType *OCLNDRangeDITy = nullptr;
  73. llvm::DIType *OCLReserveIDDITy = nullptr;
  74. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  75. llvm::DIType *Id##Ty = nullptr;
  76. #include "clang/Basic/OpenCLExtensionTypes.def"
  77. /// Cache of previously constructed Types.
  78. llvm::DenseMap<const void *, llvm::TrackingMDRef> TypeCache;
  79. std::map<llvm::StringRef, llvm::StringRef, std::greater<llvm::StringRef>>
  80. DebugPrefixMap;
  81. /// Cache that maps VLA types to size expressions for that type,
  82. /// represented by instantiated Metadata nodes.
  83. llvm::SmallDenseMap<QualType, llvm::Metadata *> SizeExprCache;
  84. /// Callbacks to use when printing names and types.
  85. class PrintingCallbacks final : public clang::PrintingCallbacks {
  86. const CGDebugInfo &Self;
  87. public:
  88. PrintingCallbacks(const CGDebugInfo &Self) : Self(Self) {}
  89. std::string remapPath(StringRef Path) const override {
  90. return Self.remapDIPath(Path);
  91. }
  92. };
  93. PrintingCallbacks PrintCB = {*this};
  94. struct ObjCInterfaceCacheEntry {
  95. const ObjCInterfaceType *Type;
  96. llvm::DIType *Decl;
  97. llvm::DIFile *Unit;
  98. ObjCInterfaceCacheEntry(const ObjCInterfaceType *Type, llvm::DIType *Decl,
  99. llvm::DIFile *Unit)
  100. : Type(Type), Decl(Decl), Unit(Unit) {}
  101. };
  102. /// Cache of previously constructed interfaces which may change.
  103. llvm::SmallVector<ObjCInterfaceCacheEntry, 32> ObjCInterfaceCache;
  104. /// Cache of forward declarations for methods belonging to the interface.
  105. /// The extra bit on the DISubprogram specifies whether a method is
  106. /// "objc_direct".
  107. llvm::DenseMap<const ObjCInterfaceDecl *,
  108. std::vector<llvm::PointerIntPair<llvm::DISubprogram *, 1>>>
  109. ObjCMethodCache;
  110. /// Cache of references to clang modules and precompiled headers.
  111. llvm::DenseMap<const Module *, llvm::TrackingMDRef> ModuleCache;
  112. /// List of interfaces we want to keep even if orphaned.
  113. std::vector<void *> RetainedTypes;
  114. /// Cache of forward declared types to RAUW at the end of compilation.
  115. std::vector<std::pair<const TagType *, llvm::TrackingMDRef>> ReplaceMap;
  116. /// Cache of replaceable forward declarations (functions and
  117. /// variables) to RAUW at the end of compilation.
  118. std::vector<std::pair<const DeclaratorDecl *, llvm::TrackingMDRef>>
  119. FwdDeclReplaceMap;
  120. /// Keep track of our current nested lexical block.
  121. std::vector<llvm::TypedTrackingMDRef<llvm::DIScope>> LexicalBlockStack;
  122. llvm::DenseMap<const Decl *, llvm::TrackingMDRef> RegionMap;
  123. /// Keep track of LexicalBlockStack counter at the beginning of a
  124. /// function. This is used to pop unbalanced regions at the end of a
  125. /// function.
  126. std::vector<unsigned> FnBeginRegionCount;
  127. /// This is a storage for names that are constructed on demand. For
  128. /// example, C++ destructors, C++ operators etc..
  129. llvm::BumpPtrAllocator DebugInfoNames;
  130. StringRef CWDName;
  131. llvm::DenseMap<const char *, llvm::TrackingMDRef> DIFileCache;
  132. llvm::DenseMap<const FunctionDecl *, llvm::TrackingMDRef> SPCache;
  133. /// Cache declarations relevant to DW_TAG_imported_declarations (C++
  134. /// using declarations and global alias variables) that aren't covered
  135. /// by other more specific caches.
  136. llvm::DenseMap<const Decl *, llvm::TrackingMDRef> DeclCache;
  137. llvm::DenseMap<const Decl *, llvm::TrackingMDRef> ImportedDeclCache;
  138. llvm::DenseMap<const NamespaceDecl *, llvm::TrackingMDRef> NamespaceCache;
  139. llvm::DenseMap<const NamespaceAliasDecl *, llvm::TrackingMDRef>
  140. NamespaceAliasCache;
  141. llvm::DenseMap<const Decl *, llvm::TypedTrackingMDRef<llvm::DIDerivedType>>
  142. StaticDataMemberCache;
  143. using ParamDecl2StmtTy = llvm::DenseMap<const ParmVarDecl *, const Stmt *>;
  144. using Param2DILocTy =
  145. llvm::DenseMap<const ParmVarDecl *, llvm::DILocalVariable *>;
  146. /// The key is coroutine real parameters, value is coroutine move parameters.
  147. ParamDecl2StmtTy CoroutineParameterMappings;
  148. /// The key is coroutine real parameters, value is DIVariable in LLVM IR.
  149. Param2DILocTy ParamDbgMappings;
  150. /// Helper functions for getOrCreateType.
  151. /// @{
  152. /// Currently the checksum of an interface includes the number of
  153. /// ivars and property accessors.
  154. llvm::DIType *CreateType(const BuiltinType *Ty);
  155. llvm::DIType *CreateType(const ComplexType *Ty);
  156. llvm::DIType *CreateType(const BitIntType *Ty);
  157. llvm::DIType *CreateQualifiedType(QualType Ty, llvm::DIFile *Fg);
  158. llvm::DIType *CreateQualifiedType(const FunctionProtoType *Ty,
  159. llvm::DIFile *Fg);
  160. llvm::DIType *CreateType(const TypedefType *Ty, llvm::DIFile *Fg);
  161. llvm::DIType *CreateType(const TemplateSpecializationType *Ty,
  162. llvm::DIFile *Fg);
  163. llvm::DIType *CreateType(const ObjCObjectPointerType *Ty, llvm::DIFile *F);
  164. llvm::DIType *CreateType(const PointerType *Ty, llvm::DIFile *F);
  165. llvm::DIType *CreateType(const BlockPointerType *Ty, llvm::DIFile *F);
  166. llvm::DIType *CreateType(const FunctionType *Ty, llvm::DIFile *F);
  167. /// Get structure or union type.
  168. llvm::DIType *CreateType(const RecordType *Tyg);
  169. llvm::DIType *CreateTypeDefinition(const RecordType *Ty);
  170. llvm::DICompositeType *CreateLimitedType(const RecordType *Ty);
  171. void CollectContainingType(const CXXRecordDecl *RD,
  172. llvm::DICompositeType *CT);
  173. /// Get Objective-C interface type.
  174. llvm::DIType *CreateType(const ObjCInterfaceType *Ty, llvm::DIFile *F);
  175. llvm::DIType *CreateTypeDefinition(const ObjCInterfaceType *Ty,
  176. llvm::DIFile *F);
  177. /// Get Objective-C object type.
  178. llvm::DIType *CreateType(const ObjCObjectType *Ty, llvm::DIFile *F);
  179. llvm::DIType *CreateType(const ObjCTypeParamType *Ty, llvm::DIFile *Unit);
  180. llvm::DIType *CreateType(const VectorType *Ty, llvm::DIFile *F);
  181. llvm::DIType *CreateType(const ConstantMatrixType *Ty, llvm::DIFile *F);
  182. llvm::DIType *CreateType(const ArrayType *Ty, llvm::DIFile *F);
  183. llvm::DIType *CreateType(const LValueReferenceType *Ty, llvm::DIFile *F);
  184. llvm::DIType *CreateType(const RValueReferenceType *Ty, llvm::DIFile *Unit);
  185. llvm::DIType *CreateType(const MemberPointerType *Ty, llvm::DIFile *F);
  186. llvm::DIType *CreateType(const AtomicType *Ty, llvm::DIFile *F);
  187. llvm::DIType *CreateType(const PipeType *Ty, llvm::DIFile *F);
  188. /// Get enumeration type.
  189. llvm::DIType *CreateEnumType(const EnumType *Ty);
  190. llvm::DIType *CreateTypeDefinition(const EnumType *Ty);
  191. /// Look up the completed type for a self pointer in the TypeCache and
  192. /// create a copy of it with the ObjectPointer and Artificial flags
  193. /// set. If the type is not cached, a new one is created. This should
  194. /// never happen though, since creating a type for the implicit self
  195. /// argument implies that we already parsed the interface definition
  196. /// and the ivar declarations in the implementation.
  197. llvm::DIType *CreateSelfType(const QualType &QualTy, llvm::DIType *Ty);
  198. /// @}
  199. /// Get the type from the cache or return null type if it doesn't
  200. /// exist.
  201. llvm::DIType *getTypeOrNull(const QualType);
  202. /// Return the debug type for a C++ method.
  203. /// \arg CXXMethodDecl is of FunctionType. This function type is
  204. /// not updated to include implicit \c this pointer. Use this routine
  205. /// to get a method type which includes \c this pointer.
  206. llvm::DISubroutineType *getOrCreateMethodType(const CXXMethodDecl *Method,
  207. llvm::DIFile *F);
  208. llvm::DISubroutineType *
  209. getOrCreateInstanceMethodType(QualType ThisPtr, const FunctionProtoType *Func,
  210. llvm::DIFile *Unit);
  211. llvm::DISubroutineType *
  212. getOrCreateFunctionType(const Decl *D, QualType FnType, llvm::DIFile *F);
  213. /// \return debug info descriptor for vtable.
  214. llvm::DIType *getOrCreateVTablePtrType(llvm::DIFile *F);
  215. /// \return namespace descriptor for the given namespace decl.
  216. llvm::DINamespace *getOrCreateNamespace(const NamespaceDecl *N);
  217. llvm::DIType *CreatePointerLikeType(llvm::dwarf::Tag Tag, const Type *Ty,
  218. QualType PointeeTy, llvm::DIFile *F);
  219. llvm::DIType *getOrCreateStructPtrType(StringRef Name, llvm::DIType *&Cache);
  220. /// A helper function to create a subprogram for a single member
  221. /// function GlobalDecl.
  222. llvm::DISubprogram *CreateCXXMemberFunction(const CXXMethodDecl *Method,
  223. llvm::DIFile *F,
  224. llvm::DIType *RecordTy);
  225. /// A helper function to collect debug info for C++ member
  226. /// functions. This is used while creating debug info entry for a
  227. /// Record.
  228. void CollectCXXMemberFunctions(const CXXRecordDecl *Decl, llvm::DIFile *F,
  229. SmallVectorImpl<llvm::Metadata *> &E,
  230. llvm::DIType *T);
  231. /// A helper function to collect debug info for C++ base
  232. /// classes. This is used while creating debug info entry for a
  233. /// Record.
  234. void CollectCXXBases(const CXXRecordDecl *Decl, llvm::DIFile *F,
  235. SmallVectorImpl<llvm::Metadata *> &EltTys,
  236. llvm::DIType *RecordTy);
  237. /// Helper function for CollectCXXBases.
  238. /// Adds debug info entries for types in Bases that are not in SeenTypes.
  239. void CollectCXXBasesAux(
  240. const CXXRecordDecl *RD, llvm::DIFile *Unit,
  241. SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
  242. const CXXRecordDecl::base_class_const_range &Bases,
  243. llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
  244. llvm::DINode::DIFlags StartingFlags);
  245. struct TemplateArgs {
  246. const TemplateParameterList *TList;
  247. llvm::ArrayRef<TemplateArgument> Args;
  248. };
  249. /// A helper function to collect template parameters.
  250. llvm::DINodeArray CollectTemplateParams(std::optional<TemplateArgs> Args,
  251. llvm::DIFile *Unit);
  252. /// A helper function to collect debug info for function template
  253. /// parameters.
  254. llvm::DINodeArray CollectFunctionTemplateParams(const FunctionDecl *FD,
  255. llvm::DIFile *Unit);
  256. /// A helper function to collect debug info for function template
  257. /// parameters.
  258. llvm::DINodeArray CollectVarTemplateParams(const VarDecl *VD,
  259. llvm::DIFile *Unit);
  260. std::optional<TemplateArgs> GetTemplateArgs(const VarDecl *) const;
  261. std::optional<TemplateArgs> GetTemplateArgs(const RecordDecl *) const;
  262. std::optional<TemplateArgs> GetTemplateArgs(const FunctionDecl *) const;
  263. /// A helper function to collect debug info for template
  264. /// parameters.
  265. llvm::DINodeArray CollectCXXTemplateParams(const RecordDecl *TS,
  266. llvm::DIFile *F);
  267. /// A helper function to collect debug info for btf_decl_tag annotations.
  268. llvm::DINodeArray CollectBTFDeclTagAnnotations(const Decl *D);
  269. llvm::DIType *createFieldType(StringRef name, QualType type,
  270. SourceLocation loc, AccessSpecifier AS,
  271. uint64_t offsetInBits, uint32_t AlignInBits,
  272. llvm::DIFile *tunit, llvm::DIScope *scope,
  273. const RecordDecl *RD = nullptr,
  274. llvm::DINodeArray Annotations = nullptr);
  275. llvm::DIType *createFieldType(StringRef name, QualType type,
  276. SourceLocation loc, AccessSpecifier AS,
  277. uint64_t offsetInBits, llvm::DIFile *tunit,
  278. llvm::DIScope *scope,
  279. const RecordDecl *RD = nullptr) {
  280. return createFieldType(name, type, loc, AS, offsetInBits, 0, tunit, scope,
  281. RD);
  282. }
  283. /// Create new bit field member.
  284. llvm::DIType *createBitFieldType(const FieldDecl *BitFieldDecl,
  285. llvm::DIScope *RecordTy,
  286. const RecordDecl *RD);
  287. /// Helpers for collecting fields of a record.
  288. /// @{
  289. void CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
  290. SmallVectorImpl<llvm::Metadata *> &E,
  291. llvm::DIType *RecordTy);
  292. llvm::DIDerivedType *CreateRecordStaticField(const VarDecl *Var,
  293. llvm::DIType *RecordTy,
  294. const RecordDecl *RD);
  295. void CollectRecordNormalField(const FieldDecl *Field, uint64_t OffsetInBits,
  296. llvm::DIFile *F,
  297. SmallVectorImpl<llvm::Metadata *> &E,
  298. llvm::DIType *RecordTy, const RecordDecl *RD);
  299. void CollectRecordNestedType(const TypeDecl *RD,
  300. SmallVectorImpl<llvm::Metadata *> &E);
  301. void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile *F,
  302. SmallVectorImpl<llvm::Metadata *> &E,
  303. llvm::DICompositeType *RecordTy);
  304. /// If the C++ class has vtable info then insert appropriate debug
  305. /// info entry in EltTys vector.
  306. void CollectVTableInfo(const CXXRecordDecl *Decl, llvm::DIFile *F,
  307. SmallVectorImpl<llvm::Metadata *> &EltTys);
  308. /// @}
  309. /// Create a new lexical block node and push it on the stack.
  310. void CreateLexicalBlock(SourceLocation Loc);
  311. /// If target-specific LLVM \p AddressSpace directly maps to target-specific
  312. /// DWARF address space, appends extended dereferencing mechanism to complex
  313. /// expression \p Expr. Otherwise, does nothing.
  314. ///
  315. /// Extended dereferencing mechanism is has the following format:
  316. /// DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
  317. void AppendAddressSpaceXDeref(unsigned AddressSpace,
  318. SmallVectorImpl<uint64_t> &Expr) const;
  319. /// A helper function to collect debug info for the default elements of a
  320. /// block.
  321. ///
  322. /// \returns The next available field offset after the default elements.
  323. uint64_t collectDefaultElementTypesForBlockPointer(
  324. const BlockPointerType *Ty, llvm::DIFile *Unit,
  325. llvm::DIDerivedType *DescTy, unsigned LineNo,
  326. SmallVectorImpl<llvm::Metadata *> &EltTys);
  327. /// A helper function to collect debug info for the default fields of a
  328. /// block.
  329. void collectDefaultFieldsForBlockLiteralDeclare(
  330. const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
  331. const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
  332. SmallVectorImpl<llvm::Metadata *> &Fields);
  333. public:
  334. CGDebugInfo(CodeGenModule &CGM);
  335. ~CGDebugInfo();
  336. void finalize();
  337. /// Remap a given path with the current debug prefix map
  338. std::string remapDIPath(StringRef) const;
  339. /// Register VLA size expression debug node with the qualified type.
  340. void registerVLASizeExpression(QualType Ty, llvm::Metadata *SizeExpr) {
  341. SizeExprCache[Ty] = SizeExpr;
  342. }
  343. /// Module debugging: Support for building PCMs.
  344. /// @{
  345. /// Set the main CU's DwoId field to \p Signature.
  346. void setDwoId(uint64_t Signature);
  347. /// When generating debug information for a clang module or
  348. /// precompiled header, this module map will be used to determine
  349. /// the module of origin of each Decl.
  350. void setModuleMap(ModuleMap &MMap) { ClangModuleMap = &MMap; }
  351. /// When generating debug information for a clang module or
  352. /// precompiled header, this module map will be used to determine
  353. /// the module of origin of each Decl.
  354. void setPCHDescriptor(ASTSourceDescriptor PCH) { PCHDescriptor = PCH; }
  355. /// @}
  356. /// Update the current source location. If \arg loc is invalid it is
  357. /// ignored.
  358. void setLocation(SourceLocation Loc);
  359. /// Return the current source location. This does not necessarily correspond
  360. /// to the IRBuilder's current DebugLoc.
  361. SourceLocation getLocation() const { return CurLoc; }
  362. /// Update the current inline scope. All subsequent calls to \p EmitLocation
  363. /// will create a location with this inlinedAt field.
  364. void setInlinedAt(llvm::MDNode *InlinedAt) { CurInlinedAt = InlinedAt; }
  365. /// \return the current inline scope.
  366. llvm::MDNode *getInlinedAt() const { return CurInlinedAt; }
  367. // Converts a SourceLocation to a DebugLoc
  368. llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Loc);
  369. /// Emit metadata to indicate a change in line/column information in
  370. /// the source file. If the location is invalid, the previous
  371. /// location will be reused.
  372. void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc);
  373. QualType getFunctionType(const FunctionDecl *FD, QualType RetTy,
  374. const SmallVectorImpl<const VarDecl *> &Args);
  375. /// Emit a call to llvm.dbg.function.start to indicate
  376. /// start of a new function.
  377. /// \param Loc The location of the function header.
  378. /// \param ScopeLoc The location of the function body.
  379. void emitFunctionStart(GlobalDecl GD, SourceLocation Loc,
  380. SourceLocation ScopeLoc, QualType FnType,
  381. llvm::Function *Fn, bool CurFnIsThunk);
  382. /// Start a new scope for an inlined function.
  383. void EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD);
  384. /// End an inlined function scope.
  385. void EmitInlineFunctionEnd(CGBuilderTy &Builder);
  386. /// Emit debug info for a function declaration.
  387. /// \p Fn is set only when a declaration for a debug call site gets created.
  388. void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
  389. QualType FnType, llvm::Function *Fn = nullptr);
  390. /// Emit debug info for an extern function being called.
  391. /// This is needed for call site debug info.
  392. void EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
  393. QualType CalleeType,
  394. const FunctionDecl *CalleeDecl);
  395. /// Constructs the debug code for exiting a function.
  396. void EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn);
  397. /// Emit metadata to indicate the beginning of a new lexical block
  398. /// and push the block onto the stack.
  399. void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc);
  400. /// Emit metadata to indicate the end of a new lexical block and pop
  401. /// the current block.
  402. void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc);
  403. /// Emit call to \c llvm.dbg.declare for an automatic variable
  404. /// declaration.
  405. /// Returns a pointer to the DILocalVariable associated with the
  406. /// llvm.dbg.declare, or nullptr otherwise.
  407. llvm::DILocalVariable *
  408. EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI,
  409. CGBuilderTy &Builder,
  410. const bool UsePointerValue = false);
  411. /// Emit call to \c llvm.dbg.label for an label.
  412. void EmitLabel(const LabelDecl *D, CGBuilderTy &Builder);
  413. /// Emit call to \c llvm.dbg.declare for an imported variable
  414. /// declaration in a block.
  415. void EmitDeclareOfBlockDeclRefVariable(
  416. const VarDecl *variable, llvm::Value *storage, CGBuilderTy &Builder,
  417. const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint = nullptr);
  418. /// Emit call to \c llvm.dbg.declare for an argument variable
  419. /// declaration.
  420. llvm::DILocalVariable *EmitDeclareOfArgVariable(const VarDecl *Decl,
  421. llvm::Value *AI,
  422. unsigned ArgNo,
  423. CGBuilderTy &Builder);
  424. /// Emit call to \c llvm.dbg.declare for the block-literal argument
  425. /// to a block invocation function.
  426. void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
  427. StringRef Name, unsigned ArgNo,
  428. llvm::AllocaInst *LocalAddr,
  429. CGBuilderTy &Builder);
  430. /// Emit information about a global variable.
  431. void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
  432. /// Emit a constant global variable's debug info.
  433. void EmitGlobalVariable(const ValueDecl *VD, const APValue &Init);
  434. /// Emit information about an external variable.
  435. void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
  436. /// Emit information about global variable alias.
  437. void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl);
  438. /// Emit C++ using directive.
  439. void EmitUsingDirective(const UsingDirectiveDecl &UD);
  440. /// Emit the type explicitly casted to.
  441. void EmitExplicitCastType(QualType Ty);
  442. /// Emit the type even if it might not be used.
  443. void EmitAndRetainType(QualType Ty);
  444. /// Emit a shadow decl brought in by a using or using-enum
  445. void EmitUsingShadowDecl(const UsingShadowDecl &USD);
  446. /// Emit C++ using declaration.
  447. void EmitUsingDecl(const UsingDecl &UD);
  448. /// Emit C++ using-enum declaration.
  449. void EmitUsingEnumDecl(const UsingEnumDecl &UD);
  450. /// Emit an @import declaration.
  451. void EmitImportDecl(const ImportDecl &ID);
  452. /// DebugInfo isn't attached to string literals by default. While certain
  453. /// aspects of debuginfo aren't useful for string literals (like a name), it's
  454. /// nice to be able to symbolize the line and column information. This is
  455. /// especially useful for sanitizers, as it allows symbolization of
  456. /// heap-buffer-overflows on constant strings.
  457. void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,
  458. const StringLiteral *S);
  459. /// Emit C++ namespace alias.
  460. llvm::DIImportedEntity *EmitNamespaceAlias(const NamespaceAliasDecl &NA);
  461. /// Emit record type's standalone debug info.
  462. llvm::DIType *getOrCreateRecordType(QualType Ty, SourceLocation L);
  463. /// Emit an Objective-C interface type standalone debug info.
  464. llvm::DIType *getOrCreateInterfaceType(QualType Ty, SourceLocation Loc);
  465. /// Emit standalone debug info for a type.
  466. llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
  467. /// Add heapallocsite metadata for MSAllocator calls.
  468. void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy,
  469. SourceLocation Loc);
  470. void completeType(const EnumDecl *ED);
  471. void completeType(const RecordDecl *RD);
  472. void completeRequiredType(const RecordDecl *RD);
  473. void completeClassData(const RecordDecl *RD);
  474. void completeClass(const RecordDecl *RD);
  475. void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD);
  476. void completeUnusedClass(const CXXRecordDecl &D);
  477. /// Create debug info for a macro defined by a #define directive or a macro
  478. /// undefined by a #undef directive.
  479. llvm::DIMacro *CreateMacro(llvm::DIMacroFile *Parent, unsigned MType,
  480. SourceLocation LineLoc, StringRef Name,
  481. StringRef Value);
  482. /// Create debug info for a file referenced by an #include directive.
  483. llvm::DIMacroFile *CreateTempMacroFile(llvm::DIMacroFile *Parent,
  484. SourceLocation LineLoc,
  485. SourceLocation FileLoc);
  486. Param2DILocTy &getParamDbgMappings() { return ParamDbgMappings; }
  487. ParamDecl2StmtTy &getCoroutineParameterMappings() {
  488. return CoroutineParameterMappings;
  489. }
  490. private:
  491. /// Emit call to llvm.dbg.declare for a variable declaration.
  492. /// Returns a pointer to the DILocalVariable associated with the
  493. /// llvm.dbg.declare, or nullptr otherwise.
  494. llvm::DILocalVariable *EmitDeclare(const VarDecl *decl, llvm::Value *AI,
  495. std::optional<unsigned> ArgNo,
  496. CGBuilderTy &Builder,
  497. const bool UsePointerValue = false);
  498. /// Emit call to llvm.dbg.declare for a binding declaration.
  499. /// Returns a pointer to the DILocalVariable associated with the
  500. /// llvm.dbg.declare, or nullptr otherwise.
  501. llvm::DILocalVariable *EmitDeclare(const BindingDecl *decl, llvm::Value *AI,
  502. std::optional<unsigned> ArgNo,
  503. CGBuilderTy &Builder,
  504. const bool UsePointerValue = false);
  505. struct BlockByRefType {
  506. /// The wrapper struct used inside the __block_literal struct.
  507. llvm::DIType *BlockByRefWrapper;
  508. /// The type as it appears in the source code.
  509. llvm::DIType *WrappedType;
  510. };
  511. std::string GetName(const Decl*, bool Qualified = false) const;
  512. /// Build up structure info for the byref. See \a BuildByRefType.
  513. BlockByRefType EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
  514. uint64_t *OffSet);
  515. /// Get context info for the DeclContext of \p Decl.
  516. llvm::DIScope *getDeclContextDescriptor(const Decl *D);
  517. /// Get context info for a given DeclContext \p Decl.
  518. llvm::DIScope *getContextDescriptor(const Decl *Context,
  519. llvm::DIScope *Default);
  520. llvm::DIScope *getCurrentContextDescriptor(const Decl *Decl);
  521. /// Create a forward decl for a RecordType in a given context.
  522. llvm::DICompositeType *getOrCreateRecordFwdDecl(const RecordType *,
  523. llvm::DIScope *);
  524. /// Return current directory name.
  525. StringRef getCurrentDirname();
  526. /// Create new compile unit.
  527. void CreateCompileUnit();
  528. /// Compute the file checksum debug info for input file ID.
  529. std::optional<llvm::DIFile::ChecksumKind>
  530. computeChecksum(FileID FID, SmallString<64> &Checksum) const;
  531. /// Get the source of the given file ID.
  532. std::optional<StringRef> getSource(const SourceManager &SM, FileID FID);
  533. /// Convenience function to get the file debug info descriptor for the input
  534. /// location.
  535. llvm::DIFile *getOrCreateFile(SourceLocation Loc);
  536. /// Create a file debug info descriptor for a source file.
  537. llvm::DIFile *
  538. createFile(StringRef FileName,
  539. std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
  540. std::optional<StringRef> Source);
  541. /// Get the type from the cache or create a new type if necessary.
  542. llvm::DIType *getOrCreateType(QualType Ty, llvm::DIFile *Fg);
  543. /// Get a reference to a clang module. If \p CreateSkeletonCU is true,
  544. /// this also creates a split dwarf skeleton compile unit.
  545. llvm::DIModule *getOrCreateModuleRef(ASTSourceDescriptor Mod,
  546. bool CreateSkeletonCU);
  547. /// DebugTypeExtRefs: If \p D originated in a clang module, return it.
  548. llvm::DIModule *getParentModuleOrNull(const Decl *D);
  549. /// Get the type from the cache or create a new partial type if
  550. /// necessary.
  551. llvm::DICompositeType *getOrCreateLimitedType(const RecordType *Ty);
  552. /// Create type metadata for a source language type.
  553. llvm::DIType *CreateTypeNode(QualType Ty, llvm::DIFile *Fg);
  554. /// Create new member and increase Offset by FType's size.
  555. llvm::DIType *CreateMemberType(llvm::DIFile *Unit, QualType FType,
  556. StringRef Name, uint64_t *Offset);
  557. /// Retrieve the DIDescriptor, if any, for the canonical form of this
  558. /// declaration.
  559. llvm::DINode *getDeclarationOrDefinition(const Decl *D);
  560. /// \return debug info descriptor to describe method
  561. /// declaration for the given method definition.
  562. llvm::DISubprogram *getFunctionDeclaration(const Decl *D);
  563. /// \return debug info descriptor to the describe method declaration
  564. /// for the given method definition.
  565. /// \param FnType For Objective-C methods, their type.
  566. /// \param LineNo The declaration's line number.
  567. /// \param Flags The DIFlags for the method declaration.
  568. /// \param SPFlags The subprogram-spcific flags for the method declaration.
  569. llvm::DISubprogram *
  570. getObjCMethodDeclaration(const Decl *D, llvm::DISubroutineType *FnType,
  571. unsigned LineNo, llvm::DINode::DIFlags Flags,
  572. llvm::DISubprogram::DISPFlags SPFlags);
  573. /// \return debug info descriptor to describe in-class static data
  574. /// member declaration for the given out-of-class definition. If D
  575. /// is an out-of-class definition of a static data member of a
  576. /// class, find its corresponding in-class declaration.
  577. llvm::DIDerivedType *
  578. getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D);
  579. /// Helper that either creates a forward declaration or a stub.
  580. llvm::DISubprogram *getFunctionFwdDeclOrStub(GlobalDecl GD, bool Stub);
  581. /// Create a subprogram describing the forward declaration
  582. /// represented in the given FunctionDecl wrapped in a GlobalDecl.
  583. llvm::DISubprogram *getFunctionForwardDeclaration(GlobalDecl GD);
  584. /// Create a DISubprogram describing the function
  585. /// represented in the given FunctionDecl wrapped in a GlobalDecl.
  586. llvm::DISubprogram *getFunctionStub(GlobalDecl GD);
  587. /// Create a global variable describing the forward declaration
  588. /// represented in the given VarDecl.
  589. llvm::DIGlobalVariable *
  590. getGlobalVariableForwardDeclaration(const VarDecl *VD);
  591. /// Return a global variable that represents one of the collection of global
  592. /// variables created for an anonmyous union.
  593. ///
  594. /// Recursively collect all of the member fields of a global
  595. /// anonymous decl and create static variables for them. The first
  596. /// time this is called it needs to be on a union and then from
  597. /// there we can have additional unnamed fields.
  598. llvm::DIGlobalVariableExpression *
  599. CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile *Unit,
  600. unsigned LineNo, StringRef LinkageName,
  601. llvm::GlobalVariable *Var, llvm::DIScope *DContext);
  602. /// Return flags which enable debug info emission for call sites, provided
  603. /// that it is supported and enabled.
  604. llvm::DINode::DIFlags getCallSiteRelatedAttrs() const;
  605. /// Get the printing policy for producing names for debug info.
  606. PrintingPolicy getPrintingPolicy() const;
  607. /// Get function name for the given FunctionDecl. If the name is
  608. /// constructed on demand (e.g., C++ destructor) then the name is
  609. /// stored on the side.
  610. StringRef getFunctionName(const FunctionDecl *FD);
  611. /// Returns the unmangled name of an Objective-C method.
  612. /// This is the display name for the debugging info.
  613. StringRef getObjCMethodName(const ObjCMethodDecl *FD);
  614. /// Return selector name. This is used for debugging
  615. /// info.
  616. StringRef getSelectorName(Selector S);
  617. /// Get class name including template argument list.
  618. StringRef getClassName(const RecordDecl *RD);
  619. /// Get the vtable name for the given class.
  620. StringRef getVTableName(const CXXRecordDecl *Decl);
  621. /// Get the name to use in the debug info for a dynamic initializer or atexit
  622. /// stub function.
  623. StringRef getDynamicInitializerName(const VarDecl *VD,
  624. DynamicInitKind StubKind,
  625. llvm::Function *InitFn);
  626. /// Get line number for the location. If location is invalid
  627. /// then use current location.
  628. unsigned getLineNumber(SourceLocation Loc);
  629. /// Get column number for the location. If location is
  630. /// invalid then use current location.
  631. /// \param Force Assume DebugColumnInfo option is true.
  632. unsigned getColumnNumber(SourceLocation Loc, bool Force = false);
  633. /// Collect various properties of a FunctionDecl.
  634. /// \param GD A GlobalDecl whose getDecl() must return a FunctionDecl.
  635. void collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
  636. StringRef &Name, StringRef &LinkageName,
  637. llvm::DIScope *&FDContext,
  638. llvm::DINodeArray &TParamsArray,
  639. llvm::DINode::DIFlags &Flags);
  640. /// Collect various properties of a VarDecl.
  641. void collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
  642. unsigned &LineNo, QualType &T, StringRef &Name,
  643. StringRef &LinkageName,
  644. llvm::MDTuple *&TemplateParameters,
  645. llvm::DIScope *&VDContext);
  646. /// Allocate a copy of \p A using the DebugInfoNames allocator
  647. /// and return a reference to it. If multiple arguments are given the strings
  648. /// are concatenated.
  649. StringRef internString(StringRef A, StringRef B = StringRef()) {
  650. char *Data = DebugInfoNames.Allocate<char>(A.size() + B.size());
  651. if (!A.empty())
  652. std::memcpy(Data, A.data(), A.size());
  653. if (!B.empty())
  654. std::memcpy(Data + A.size(), B.data(), B.size());
  655. return StringRef(Data, A.size() + B.size());
  656. }
  657. };
  658. /// A scoped helper to set the current debug location to the specified
  659. /// location or preferred location of the specified Expr.
  660. class ApplyDebugLocation {
  661. private:
  662. void init(SourceLocation TemporaryLocation, bool DefaultToEmpty = false);
  663. ApplyDebugLocation(CodeGenFunction &CGF, bool DefaultToEmpty,
  664. SourceLocation TemporaryLocation);
  665. llvm::DebugLoc OriginalLocation;
  666. CodeGenFunction *CGF;
  667. public:
  668. /// Set the location to the (valid) TemporaryLocation.
  669. ApplyDebugLocation(CodeGenFunction &CGF, SourceLocation TemporaryLocation);
  670. ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E);
  671. ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc);
  672. ApplyDebugLocation(ApplyDebugLocation &&Other) : CGF(Other.CGF) {
  673. Other.CGF = nullptr;
  674. }
  675. ApplyDebugLocation &operator=(ApplyDebugLocation &&) = default;
  676. ~ApplyDebugLocation();
  677. /// Apply TemporaryLocation if it is valid. Otherwise switch
  678. /// to an artificial debug location that has a valid scope, but no
  679. /// line information.
  680. ///
  681. /// Artificial locations are useful when emitting compiler-generated
  682. /// helper functions that have no source location associated with
  683. /// them. The DWARF specification allows the compiler to use the
  684. /// special line number 0 to indicate code that can not be
  685. /// attributed to any source location. Note that passing an empty
  686. /// SourceLocation to CGDebugInfo::setLocation() will result in the
  687. /// last valid location being reused.
  688. static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF) {
  689. return ApplyDebugLocation(CGF, false, SourceLocation());
  690. }
  691. /// Apply TemporaryLocation if it is valid. Otherwise switch
  692. /// to an artificial debug location that has a valid scope, but no
  693. /// line information.
  694. static ApplyDebugLocation
  695. CreateDefaultArtificial(CodeGenFunction &CGF,
  696. SourceLocation TemporaryLocation) {
  697. return ApplyDebugLocation(CGF, false, TemporaryLocation);
  698. }
  699. /// Set the IRBuilder to not attach debug locations. Note that
  700. /// passing an empty SourceLocation to \a CGDebugInfo::setLocation()
  701. /// will result in the last valid location being reused. Note that
  702. /// all instructions that do not have a location at the beginning of
  703. /// a function are counted towards to function prologue.
  704. static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF) {
  705. return ApplyDebugLocation(CGF, true, SourceLocation());
  706. }
  707. };
  708. /// A scoped helper to set the current debug location to an inlined location.
  709. class ApplyInlineDebugLocation {
  710. SourceLocation SavedLocation;
  711. CodeGenFunction *CGF;
  712. public:
  713. /// Set up the CodeGenFunction's DebugInfo to produce inline locations for the
  714. /// function \p InlinedFn. The current debug location becomes the inlined call
  715. /// site of the inlined function.
  716. ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn);
  717. /// Restore everything back to the original state.
  718. ~ApplyInlineDebugLocation();
  719. };
  720. } // namespace CodeGen
  721. } // namespace clang
  722. #endif // LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H