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