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