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