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