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