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