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 template
252   /// parameters.
253   llvm::DINodeArray
254   CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TS,
255                            llvm::DIFile *F);
256 
257   llvm::DIType *createFieldType(StringRef name, QualType type,
258                                 SourceLocation loc, AccessSpecifier AS,
259                                 uint64_t offsetInBits, uint32_t AlignInBits,
260                                 llvm::DIFile *tunit, llvm::DIScope *scope,
261                                 const RecordDecl *RD = nullptr);
262 
263   llvm::DIType *createFieldType(StringRef name, QualType type,
264                                 SourceLocation loc, AccessSpecifier AS,
265                                 uint64_t offsetInBits, llvm::DIFile *tunit,
266                                 llvm::DIScope *scope,
267                                 const RecordDecl *RD = nullptr) {
268     return createFieldType(name, type, loc, AS, offsetInBits, 0, tunit, scope,
269                            RD);
270   }
271 
272   /// Create new bit field member.
273   llvm::DIType *createBitFieldType(const FieldDecl *BitFieldDecl,
274                                    llvm::DIScope *RecordTy,
275                                    const RecordDecl *RD);
276 
277   /// Helpers for collecting fields of a record.
278   /// @{
279   void CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
280                                  SmallVectorImpl<llvm::Metadata *> &E,
281                                  llvm::DIType *RecordTy);
282   llvm::DIDerivedType *CreateRecordStaticField(const VarDecl *Var,
283                                                llvm::DIType *RecordTy,
284                                                const RecordDecl *RD);
285   void CollectRecordNormalField(const FieldDecl *Field, uint64_t OffsetInBits,
286                                 llvm::DIFile *F,
287                                 SmallVectorImpl<llvm::Metadata *> &E,
288                                 llvm::DIType *RecordTy, const RecordDecl *RD);
289   void CollectRecordNestedType(const TypeDecl *RD,
290                                SmallVectorImpl<llvm::Metadata *> &E);
291   void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile *F,
292                            SmallVectorImpl<llvm::Metadata *> &E,
293                            llvm::DICompositeType *RecordTy);
294 
295   /// If the C++ class has vtable info then insert appropriate debug
296   /// info entry in EltTys vector.
297   void CollectVTableInfo(const CXXRecordDecl *Decl, llvm::DIFile *F,
298                          SmallVectorImpl<llvm::Metadata *> &EltTys,
299                          llvm::DICompositeType *RecordTy);
300   /// @}
301 
302   /// Create a new lexical block node and push it on the stack.
303   void CreateLexicalBlock(SourceLocation Loc);
304 
305   /// If target-specific LLVM \p AddressSpace directly maps to target-specific
306   /// DWARF address space, appends extended dereferencing mechanism to complex
307   /// expression \p Expr. Otherwise, does nothing.
308   ///
309   /// Extended dereferencing mechanism is has the following format:
310   ///     DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
311   void AppendAddressSpaceXDeref(unsigned AddressSpace,
312                                 SmallVectorImpl<int64_t> &Expr) const;
313 
314   /// A helper function to collect debug info for the default elements of a
315   /// block.
316   ///
317   /// \returns The next available field offset after the default elements.
318   uint64_t collectDefaultElementTypesForBlockPointer(
319       const BlockPointerType *Ty, llvm::DIFile *Unit,
320       llvm::DIDerivedType *DescTy, unsigned LineNo,
321       SmallVectorImpl<llvm::Metadata *> &EltTys);
322 
323   /// A helper function to collect debug info for the default fields of a
324   /// block.
325   void collectDefaultFieldsForBlockLiteralDeclare(
326       const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
327       const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
328       SmallVectorImpl<llvm::Metadata *> &Fields);
329 
330 public:
331   CGDebugInfo(CodeGenModule &CGM);
332   ~CGDebugInfo();
333 
334   void finalize();
335 
336   /// Register VLA size expression debug node with the qualified type.
337   void registerVLASizeExpression(QualType Ty, llvm::Metadata *SizeExpr) {
338     SizeExprCache[Ty] = SizeExpr;
339   }
340 
341   /// Module debugging: Support for building PCMs.
342   /// @{
343   /// Set the main CU's DwoId field to \p Signature.
344   void setDwoId(uint64_t Signature);
345 
346   /// When generating debug information for a clang module or
347   /// precompiled header, this module map will be used to determine
348   /// the module of origin of each Decl.
349   void setModuleMap(ModuleMap &MMap) { ClangModuleMap = &MMap; }
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 setPCHDescriptor(ExternalASTSource::ASTSourceDescriptor PCH) {
355     PCHDescriptor = PCH;
356   }
357   /// @}
358 
359   /// Update the current source location. If \arg loc is invalid it is
360   /// ignored.
361   void setLocation(SourceLocation Loc);
362 
363   /// Return the current source location. This does not necessarily correspond
364   /// to the IRBuilder's current DebugLoc.
365   SourceLocation getLocation() const { return CurLoc; }
366 
367   /// Update the current inline scope. All subsequent calls to \p EmitLocation
368   /// will create a location with this inlinedAt field.
369   void setInlinedAt(llvm::MDNode *InlinedAt) { CurInlinedAt = InlinedAt; }
370 
371   /// \return the current inline scope.
372   llvm::MDNode *getInlinedAt() const { return CurInlinedAt; }
373 
374   // Converts a SourceLocation to a DebugLoc
375   llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Loc);
376 
377   /// Emit metadata to indicate a change in line/column information in
378   /// the source file. If the location is invalid, the previous
379   /// location will be reused.
380   void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc);
381 
382   /// Emit a call to llvm.dbg.function.start to indicate
383   /// start of a new function.
384   /// \param Loc       The location of the function header.
385   /// \param ScopeLoc  The location of the function body.
386   void EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
387                          SourceLocation ScopeLoc, QualType FnType,
388                          llvm::Function *Fn, bool CurFnIsThunk,
389                          CGBuilderTy &Builder);
390 
391   /// Start a new scope for an inlined function.
392   void EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD);
393   /// End an inlined function scope.
394   void EmitInlineFunctionEnd(CGBuilderTy &Builder);
395 
396   /// Emit debug info for a function declaration.
397   void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType);
398 
399   /// Constructs the debug code for exiting a function.
400   void EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn);
401 
402   /// Emit metadata to indicate the beginning of a new lexical block
403   /// and push the block onto the stack.
404   void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc);
405 
406   /// Emit metadata to indicate the end of a new lexical block and pop
407   /// the current block.
408   void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc);
409 
410   /// Emit call to \c llvm.dbg.declare for an automatic variable
411   /// declaration.
412   /// Returns a pointer to the DILocalVariable associated with the
413   /// llvm.dbg.declare, or nullptr otherwise.
414   llvm::DILocalVariable *EmitDeclareOfAutoVariable(const VarDecl *Decl,
415                                                    llvm::Value *AI,
416                                                    CGBuilderTy &Builder);
417 
418   /// Emit call to \c llvm.dbg.declare for an imported variable
419   /// declaration in a block.
420   void EmitDeclareOfBlockDeclRefVariable(
421       const VarDecl *variable, llvm::Value *storage, CGBuilderTy &Builder,
422       const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint = nullptr);
423 
424   /// Emit call to \c llvm.dbg.declare for an argument variable
425   /// declaration.
426   void EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
427                                 unsigned ArgNo, CGBuilderTy &Builder);
428 
429   /// Emit call to \c llvm.dbg.declare for the block-literal argument
430   /// to a block invocation function.
431   void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
432                                             StringRef Name, unsigned ArgNo,
433                                             llvm::AllocaInst *LocalAddr,
434                                             CGBuilderTy &Builder);
435 
436   /// Emit information about a global variable.
437   void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
438 
439   /// Emit a constant global variable's debug info.
440   void EmitGlobalVariable(const ValueDecl *VD, const APValue &Init);
441 
442   /// Emit C++ using directive.
443   void EmitUsingDirective(const UsingDirectiveDecl &UD);
444 
445   /// Emit the type explicitly casted to.
446   void EmitExplicitCastType(QualType Ty);
447 
448   /// Emit C++ using declaration.
449   void EmitUsingDecl(const UsingDecl &UD);
450 
451   /// Emit an @import declaration.
452   void EmitImportDecl(const ImportDecl &ID);
453 
454   /// Emit C++ namespace alias.
455   llvm::DIImportedEntity *EmitNamespaceAlias(const NamespaceAliasDecl &NA);
456 
457   /// Emit record type's standalone debug info.
458   llvm::DIType *getOrCreateRecordType(QualType Ty, SourceLocation L);
459 
460   /// Emit an Objective-C interface type standalone debug info.
461   llvm::DIType *getOrCreateInterfaceType(QualType Ty, SourceLocation Loc);
462 
463   /// Emit standalone debug info for a type.
464   llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
465 
466   void completeType(const EnumDecl *ED);
467   void completeType(const RecordDecl *RD);
468   void completeRequiredType(const RecordDecl *RD);
469   void completeClassData(const RecordDecl *RD);
470   void completeClass(const RecordDecl *RD);
471 
472   void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD);
473   void completeUnusedClass(const CXXRecordDecl &D);
474 
475   /// Create debug info for a macro defined by a #define directive or a macro
476   /// undefined by a #undef directive.
477   llvm::DIMacro *CreateMacro(llvm::DIMacroFile *Parent, unsigned MType,
478                              SourceLocation LineLoc, StringRef Name,
479                              StringRef Value);
480 
481   /// Create debug info for a file referenced by an #include directive.
482   llvm::DIMacroFile *CreateTempMacroFile(llvm::DIMacroFile *Parent,
483                                          SourceLocation LineLoc,
484                                          SourceLocation FileLoc);
485 
486 private:
487   /// Emit call to llvm.dbg.declare for a variable declaration.
488   /// Returns a pointer to the DILocalVariable associated with the
489   /// llvm.dbg.declare, or nullptr otherwise.
490   llvm::DILocalVariable *EmitDeclare(const VarDecl *decl, llvm::Value *AI,
491                                      llvm::Optional<unsigned> ArgNo,
492                                      CGBuilderTy &Builder);
493 
494   /// Build up structure info for the byref.  See \a BuildByRefType.
495   llvm::DIType *EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
496                                              uint64_t *OffSet);
497 
498   /// Get context info for the DeclContext of \p Decl.
499   llvm::DIScope *getDeclContextDescriptor(const Decl *D);
500   /// Get context info for a given DeclContext \p Decl.
501   llvm::DIScope *getContextDescriptor(const Decl *Context,
502                                       llvm::DIScope *Default);
503 
504   llvm::DIScope *getCurrentContextDescriptor(const Decl *Decl);
505 
506   /// Create a forward decl for a RecordType in a given context.
507   llvm::DICompositeType *getOrCreateRecordFwdDecl(const RecordType *,
508                                                   llvm::DIScope *);
509 
510   /// Return current directory name.
511   StringRef getCurrentDirname();
512 
513   /// Create new compile unit.
514   void CreateCompileUnit();
515 
516   /// Remap a given path with the current debug prefix map
517   std::string remapDIPath(StringRef) const;
518 
519   /// Compute the file checksum debug info for input file ID.
520   Optional<llvm::DIFile::ChecksumKind>
521   computeChecksum(FileID FID, SmallString<32> &Checksum) const;
522 
523   /// Get the source of the given file ID.
524   Optional<StringRef> getSource(const SourceManager &SM, FileID FID);
525 
526   /// Get the file debug info descriptor for the input location.
527   llvm::DIFile *getOrCreateFile(SourceLocation Loc);
528 
529   /// Get the file info for main compile unit.
530   llvm::DIFile *getOrCreateMainFile();
531 
532   /// Get the type from the cache or create a new type if necessary.
533   llvm::DIType *getOrCreateType(QualType Ty, llvm::DIFile *Fg);
534 
535   /// Get a reference to a clang module.  If \p CreateSkeletonCU is true,
536   /// this also creates a split dwarf skeleton compile unit.
537   llvm::DIModule *
538   getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
539                        bool CreateSkeletonCU);
540 
541   /// DebugTypeExtRefs: If \p D originated in a clang module, return it.
542   llvm::DIModule *getParentModuleOrNull(const Decl *D);
543 
544   /// Get the type from the cache or create a new partial type if
545   /// necessary.
546   llvm::DICompositeType *getOrCreateLimitedType(const RecordType *Ty,
547                                                 llvm::DIFile *F);
548 
549   /// Create type metadata for a source language type.
550   llvm::DIType *CreateTypeNode(QualType Ty, llvm::DIFile *Fg);
551 
552   /// Create new member and increase Offset by FType's size.
553   llvm::DIType *CreateMemberType(llvm::DIFile *Unit, QualType FType,
554                                  StringRef Name, uint64_t *Offset);
555 
556   /// Retrieve the DIDescriptor, if any, for the canonical form of this
557   /// declaration.
558   llvm::DINode *getDeclarationOrDefinition(const Decl *D);
559 
560   /// \return debug info descriptor to describe method
561   /// declaration for the given method definition.
562   llvm::DISubprogram *getFunctionDeclaration(const Decl *D);
563 
564   /// \return debug info descriptor to describe in-class static data
565   /// member declaration for the given out-of-class definition.  If D
566   /// is an out-of-class definition of a static data member of a
567   /// class, find its corresponding in-class declaration.
568   llvm::DIDerivedType *
569   getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D);
570 
571   /// Helper that either creates a forward declaration or a stub.
572   llvm::DISubprogram *getFunctionFwdDeclOrStub(GlobalDecl GD, bool Stub);
573 
574   /// Create a subprogram describing the forward declaration
575   /// represented in the given FunctionDecl wrapped in a GlobalDecl.
576   llvm::DISubprogram *getFunctionForwardDeclaration(GlobalDecl GD);
577 
578   /// Create a DISubprogram describing the function
579   /// represented in the given FunctionDecl wrapped in a GlobalDecl.
580   llvm::DISubprogram *getFunctionStub(GlobalDecl GD);
581 
582   /// Create a global variable describing the forward declaration
583   /// represented in the given VarDecl.
584   llvm::DIGlobalVariable *
585   getGlobalVariableForwardDeclaration(const VarDecl *VD);
586 
587   /// Return a global variable that represents one of the collection of global
588   /// variables created for an anonmyous union.
589   ///
590   /// Recursively collect all of the member fields of a global
591   /// anonymous decl and create static variables for them. The first
592   /// time this is called it needs to be on a union and then from
593   /// there we can have additional unnamed fields.
594   llvm::DIGlobalVariableExpression *
595   CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile *Unit,
596                          unsigned LineNo, StringRef LinkageName,
597                          llvm::GlobalVariable *Var, llvm::DIScope *DContext);
598 
599   /// Get the printing policy for producing names for debug info.
600   PrintingPolicy getPrintingPolicy() const;
601 
602   /// Get function name for the given FunctionDecl. If the name is
603   /// constructed on demand (e.g., C++ destructor) then the name is
604   /// stored on the side.
605   StringRef getFunctionName(const FunctionDecl *FD);
606 
607   /// Returns the unmangled name of an Objective-C method.
608   /// This is the display name for the debugging info.
609   StringRef getObjCMethodName(const ObjCMethodDecl *FD);
610 
611   /// Return selector name. This is used for debugging
612   /// info.
613   StringRef getSelectorName(Selector S);
614 
615   /// Get class name including template argument list.
616   StringRef getClassName(const RecordDecl *RD);
617 
618   /// Get the vtable name for the given class.
619   StringRef getVTableName(const CXXRecordDecl *Decl);
620 
621   /// Get line number for the location. If location is invalid
622   /// then use current location.
623   unsigned getLineNumber(SourceLocation Loc);
624 
625   /// Get column number for the location. If location is
626   /// invalid then use current location.
627   /// \param Force  Assume DebugColumnInfo option is true.
628   unsigned getColumnNumber(SourceLocation Loc, bool Force = false);
629 
630   /// Collect various properties of a FunctionDecl.
631   /// \param GD  A GlobalDecl whose getDecl() must return a FunctionDecl.
632   void collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
633                                 StringRef &Name, StringRef &LinkageName,
634                                 llvm::DIScope *&FDContext,
635                                 llvm::DINodeArray &TParamsArray,
636                                 llvm::DINode::DIFlags &Flags);
637 
638   /// Collect various properties of a VarDecl.
639   void collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
640                            unsigned &LineNo, QualType &T, StringRef &Name,
641                            StringRef &LinkageName, llvm::DIScope *&VDContext);
642 
643   /// Allocate a copy of \p A using the DebugInfoNames allocator
644   /// and return a reference to it. If multiple arguments are given the strings
645   /// are concatenated.
646   StringRef internString(StringRef A, StringRef B = StringRef()) {
647     char *Data = DebugInfoNames.Allocate<char>(A.size() + B.size());
648     if (!A.empty())
649       std::memcpy(Data, A.data(), A.size());
650     if (!B.empty())
651       std::memcpy(Data + A.size(), B.data(), B.size());
652     return StringRef(Data, A.size() + B.size());
653   }
654 };
655 
656 /// A scoped helper to set the current debug location to the specified
657 /// location or preferred location of the specified Expr.
658 class ApplyDebugLocation {
659 private:
660   void init(SourceLocation TemporaryLocation, bool DefaultToEmpty = false);
661   ApplyDebugLocation(CodeGenFunction &CGF, bool DefaultToEmpty,
662                      SourceLocation TemporaryLocation);
663 
664   llvm::DebugLoc OriginalLocation;
665   CodeGenFunction *CGF;
666 
667 public:
668   /// Set the location to the (valid) TemporaryLocation.
669   ApplyDebugLocation(CodeGenFunction &CGF, SourceLocation TemporaryLocation);
670   ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E);
671   ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc);
672   ApplyDebugLocation(ApplyDebugLocation &&Other) : CGF(Other.CGF) {
673     Other.CGF = nullptr;
674   }
675 
676   ~ApplyDebugLocation();
677 
678   /// Apply TemporaryLocation if it is valid. Otherwise switch
679   /// to an artificial debug location that has a valid scope, but no
680   /// line information.
681   ///
682   /// Artificial locations are useful when emitting compiler-generated
683   /// helper functions that have no source location associated with
684   /// them. The DWARF specification allows the compiler to use the
685   /// special line number 0 to indicate code that can not be
686   /// attributed to any source location. Note that passing an empty
687   /// SourceLocation to CGDebugInfo::setLocation() will result in the
688   /// last valid location being reused.
689   static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF) {
690     return ApplyDebugLocation(CGF, false, SourceLocation());
691   }
692   /// Apply TemporaryLocation if it is valid. Otherwise switch
693   /// to an artificial debug location that has a valid scope, but no
694   /// line information.
695   static ApplyDebugLocation
696   CreateDefaultArtificial(CodeGenFunction &CGF,
697                           SourceLocation TemporaryLocation) {
698     return ApplyDebugLocation(CGF, false, TemporaryLocation);
699   }
700 
701   /// Set the IRBuilder to not attach debug locations.  Note that
702   /// passing an empty SourceLocation to \a CGDebugInfo::setLocation()
703   /// will result in the last valid location being reused.  Note that
704   /// all instructions that do not have a location at the beginning of
705   /// a function are counted towards to function prologue.
706   static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF) {
707     return ApplyDebugLocation(CGF, true, SourceLocation());
708   }
709 };
710 
711 /// A scoped helper to set the current debug location to an inlined location.
712 class ApplyInlineDebugLocation {
713   SourceLocation SavedLocation;
714   CodeGenFunction *CGF;
715 
716 public:
717   /// Set up the CodeGenFunction's DebugInfo to produce inline locations for the
718   /// function \p InlinedFn. The current debug location becomes the inlined call
719   /// site of the inlined function.
720   ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn);
721   /// Restore everything back to the orginial state.
722   ~ApplyInlineDebugLocation();
723 };
724 
725 } // namespace CodeGen
726 } // namespace clang
727 
728 #endif // LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
729