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