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