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 *OCLSamplerDITy = nullptr;
71   llvm::DIType *OCLEventDITy = nullptr;
72   llvm::DIType *OCLClkEventDITy = nullptr;
73   llvm::DIType *OCLQueueDITy = nullptr;
74   llvm::DIType *OCLNDRangeDITy = nullptr;
75   llvm::DIType *OCLReserveIDDITy = nullptr;
76 
77   /// Cache of previously constructed Types.
78   llvm::DenseMap<const void *, llvm::TrackingMDRef> TypeCache;
79 
80   llvm::SmallDenseMap<llvm::StringRef, llvm::StringRef> DebugPrefixMap;
81 
82   struct ObjCInterfaceCacheEntry {
83     const ObjCInterfaceType *Type;
84     llvm::DIType *Decl;
85     llvm::DIFile *Unit;
86     ObjCInterfaceCacheEntry(const ObjCInterfaceType *Type, llvm::DIType *Decl,
87                             llvm::DIFile *Unit)
88         : Type(Type), Decl(Decl), Unit(Unit) {}
89   };
90 
91   /// Cache of previously constructed interfaces which may change.
92   llvm::SmallVector<ObjCInterfaceCacheEntry, 32> ObjCInterfaceCache;
93 
94   /// Cache of references to clang modules and precompiled headers.
95   llvm::DenseMap<const Module *, llvm::TrackingMDRef> ModuleCache;
96 
97   /// List of interfaces we want to keep even if orphaned.
98   std::vector<void *> RetainedTypes;
99 
100   /// Cache of forward declared types to RAUW at the end of
101   /// 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   /// A helper function to collect template parameters.
223   llvm::DINodeArray CollectTemplateParams(const TemplateParameterList *TPList,
224                                           ArrayRef<TemplateArgument> TAList,
225                                           llvm::DIFile *Unit);
226   /// A helper function to collect debug info for function template
227   /// parameters.
228   llvm::DINodeArray CollectFunctionTemplateParams(const FunctionDecl *FD,
229                                                   llvm::DIFile *Unit);
230 
231   /// A helper function to collect debug info for template
232   /// parameters.
233   llvm::DINodeArray
234   CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TS,
235                            llvm::DIFile *F);
236 
237   llvm::DIType *createFieldType(StringRef name, QualType type,
238                                 SourceLocation loc, AccessSpecifier AS,
239                                 uint64_t offsetInBits, llvm::DIFile *tunit,
240                                 llvm::DIScope *scope,
241                                 const RecordDecl *RD = nullptr);
242 
243   /// Create new bit field member.
244   llvm::DIType *createBitFieldType(const FieldDecl *BitFieldDecl,
245                                    llvm::DIScope *RecordTy,
246                                    const RecordDecl *RD);
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 CollectRecordNestedRecord(const RecordDecl *RD,
261                                  SmallVectorImpl<llvm::Metadata *> &E);
262   void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile *F,
263                            SmallVectorImpl<llvm::Metadata *> &E,
264                            llvm::DICompositeType *RecordTy);
265 
266   /// If the C++ class has vtable info then insert appropriate debug
267   /// info entry in EltTys vector.
268   void CollectVTableInfo(const CXXRecordDecl *Decl, llvm::DIFile *F,
269                          SmallVectorImpl<llvm::Metadata *> &EltTys,
270                          llvm::DICompositeType *RecordTy);
271   /// @}
272 
273   /// Create a new lexical block node and push it on the stack.
274   void CreateLexicalBlock(SourceLocation Loc);
275 
276 public:
277   CGDebugInfo(CodeGenModule &CGM);
278   ~CGDebugInfo();
279 
280   void finalize();
281 
282   /// Module debugging: Support for building PCMs.
283   /// @{
284   /// Set the main CU's DwoId field to \p Signature.
285   void setDwoId(uint64_t Signature);
286 
287   /// When generating debug information for a clang module or
288   /// precompiled header, this module map will be used to determine
289   /// the module of origin of each Decl.
290   void setModuleMap(ModuleMap &MMap) { ClangModuleMap = &MMap; }
291 
292   /// When generating debug information for a clang module or
293   /// precompiled header, this module map will be used to determine
294   /// the module of origin of each Decl.
295   void setPCHDescriptor(ExternalASTSource::ASTSourceDescriptor PCH) {
296     PCHDescriptor = PCH;
297   }
298   /// @}
299 
300   /// Update the current source location. If \arg loc is invalid it is
301   /// ignored.
302   void setLocation(SourceLocation Loc);
303 
304   /// Emit metadata to indicate a change in line/column information in
305   /// the source file. If the location is invalid, the previous
306   /// location will be reused.
307   void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc);
308 
309   /// Emit a call to llvm.dbg.function.start to indicate
310   /// start of a new function.
311   /// \param Loc       The location of the function header.
312   /// \param ScopeLoc  The location of the function body.
313   void EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
314                          SourceLocation ScopeLoc, QualType FnType,
315                          llvm::Function *Fn, CGBuilderTy &Builder);
316 
317   /// Emit debug info for a function declaration.
318   void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType);
319 
320   /// Constructs the debug code for exiting a function.
321   void EmitFunctionEnd(CGBuilderTy &Builder);
322 
323   /// Emit metadata to indicate the beginning of a new lexical block
324   /// and push the block onto the stack.
325   void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc);
326 
327   /// Emit metadata to indicate the end of a new lexical block and pop
328   /// the current block.
329   void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc);
330 
331   /// Emit call to \c llvm.dbg.declare for an automatic variable
332   /// declaration.
333   void EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI,
334                                  CGBuilderTy &Builder);
335 
336   /// Emit call to \c llvm.dbg.declare for an imported variable
337   /// declaration in a block.
338   void EmitDeclareOfBlockDeclRefVariable(const VarDecl *variable,
339                                          llvm::Value *storage,
340                                          CGBuilderTy &Builder,
341                                          const CGBlockInfo &blockInfo,
342                                          llvm::Instruction *InsertPoint = nullptr);
343 
344   /// Emit call to \c llvm.dbg.declare for an argument variable
345   /// declaration.
346   void EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
347                                 unsigned ArgNo, CGBuilderTy &Builder);
348 
349   /// Emit call to \c llvm.dbg.declare for the block-literal argument
350   /// to a block invocation function.
351   void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
352                                             llvm::Value *Arg, unsigned ArgNo,
353                                             llvm::Value *LocalAddr,
354                                             CGBuilderTy &Builder);
355 
356   /// Emit information about a global variable.
357   void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
358 
359   /// Emit a constant global variable's debug info.
360   void EmitGlobalVariable(const ValueDecl *VD, const APValue &Init);
361 
362   /// Emit C++ using directive.
363   void EmitUsingDirective(const UsingDirectiveDecl &UD);
364 
365   /// Emit the type explicitly casted to.
366   void EmitExplicitCastType(QualType Ty);
367 
368   /// Emit C++ using declaration.
369   void EmitUsingDecl(const UsingDecl &UD);
370 
371   /// Emit an @import declaration.
372   void EmitImportDecl(const ImportDecl &ID);
373 
374   /// Emit C++ namespace alias.
375   llvm::DIImportedEntity *EmitNamespaceAlias(const NamespaceAliasDecl &NA);
376 
377   /// Emit record type's standalone debug info.
378   llvm::DIType *getOrCreateRecordType(QualType Ty, SourceLocation L);
379 
380   /// Emit an Objective-C interface type standalone debug info.
381   llvm::DIType *getOrCreateInterfaceType(QualType Ty, SourceLocation Loc);
382 
383   /// Emit standalone debug info for a type.
384   llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
385 
386   void completeType(const EnumDecl *ED);
387   void completeType(const RecordDecl *RD);
388   void completeRequiredType(const RecordDecl *RD);
389   void completeClassData(const RecordDecl *RD);
390 
391   void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD);
392 
393 private:
394   /// Emit call to llvm.dbg.declare for a variable declaration.
395   void EmitDeclare(const VarDecl *decl, llvm::Value *AI,
396                    llvm::Optional<unsigned> ArgNo, CGBuilderTy &Builder);
397 
398   /// Build up structure info for the byref.  See \a BuildByRefType.
399   llvm::DIType *EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
400                                              uint64_t *OffSet);
401 
402   /// Get context info for the DeclContext of \p Decl.
403   llvm::DIScope *getDeclContextDescriptor(const Decl *D);
404   /// Get context info for a given DeclContext \p Decl.
405   llvm::DIScope *getContextDescriptor(const Decl *Context,
406                                       llvm::DIScope *Default);
407 
408   llvm::DIScope *getCurrentContextDescriptor(const Decl *Decl);
409 
410   /// Create a forward decl for a RecordType in a given context.
411   llvm::DICompositeType *getOrCreateRecordFwdDecl(const RecordType *,
412                                                   llvm::DIScope *);
413 
414   /// Return current directory name.
415   StringRef getCurrentDirname();
416 
417   /// Create new compile unit.
418   void CreateCompileUnit();
419 
420   /// Remap a given path with the current debug prefix map
421   std::string remapDIPath(StringRef) const;
422 
423   /// Get the file debug info descriptor for the input location.
424   llvm::DIFile *getOrCreateFile(SourceLocation Loc);
425 
426   /// Get the file info for main compile unit.
427   llvm::DIFile *getOrCreateMainFile();
428 
429   /// Get the type from the cache or create a new type if necessary.
430   llvm::DIType *getOrCreateType(QualType Ty, llvm::DIFile *Fg);
431 
432   /// Get a reference to a clang module.  If \p CreateSkeletonCU is true,
433   /// this also creates a split dwarf skeleton compile unit.
434   llvm::DIModule *
435   getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
436                        bool CreateSkeletonCU);
437 
438   /// DebugTypeExtRefs: If \p D originated in a clang module, return it.
439   llvm::DIModule *getParentModuleOrNull(const Decl *D);
440 
441   /// Get the type from the cache or create a new partial type if
442   /// necessary.
443   llvm::DICompositeType *getOrCreateLimitedType(const RecordType *Ty,
444                                                 llvm::DIFile *F);
445 
446   /// Create type metadata for a source language type.
447   llvm::DIType *CreateTypeNode(QualType Ty, llvm::DIFile *Fg);
448 
449   /// Create new member and increase Offset by FType's size.
450   llvm::DIType *CreateMemberType(llvm::DIFile *Unit, QualType FType,
451                                  StringRef Name, uint64_t *Offset);
452 
453   /// Retrieve the DIDescriptor, if any, for the canonical form of this
454   /// declaration.
455   llvm::DINode *getDeclarationOrDefinition(const Decl *D);
456 
457   /// \return debug info descriptor to describe method
458   /// declaration for the given method definition.
459   llvm::DISubprogram *getFunctionDeclaration(const Decl *D);
460 
461   /// \return debug info descriptor to describe in-class static data
462   /// member declaration for the given out-of-class definition.  If D
463   /// is an out-of-class definition of a static data member of a
464   /// class, find its corresponding in-class declaration.
465   llvm::DIDerivedType *
466   getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D);
467 
468   /// Create a subprogram describing the forward declaration
469   /// represented in the given FunctionDecl.
470   llvm::DISubprogram *getFunctionForwardDeclaration(const FunctionDecl *FD);
471 
472   /// Create a global variable describing the forward decalration
473   /// represented in the given VarDecl.
474   llvm::DIGlobalVariable *
475   getGlobalVariableForwardDeclaration(const VarDecl *VD);
476 
477   /// \brief Return a global variable that represents one of the
478   /// collection of global variables created for an anonmyous union.
479   ///
480   /// Recursively collect all of the member fields of a global
481   /// anonymous decl and create static variables for them. The first
482   /// time this is called it needs to be on a union and then from
483   /// there we can have additional unnamed fields.
484   llvm::DIGlobalVariable *
485   CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile *Unit,
486                          unsigned LineNo, StringRef LinkageName,
487                          llvm::GlobalVariable *Var, llvm::DIScope *DContext);
488 
489   /// Get function name for the given FunctionDecl. If the name is
490   /// constructed on demand (e.g., C++ destructor) then the name is
491   /// stored on the side.
492   StringRef getFunctionName(const FunctionDecl *FD);
493 
494   /// Returns the unmangled name of an Objective-C method.
495   /// This is the display name for the debugging info.
496   StringRef getObjCMethodName(const ObjCMethodDecl *FD);
497 
498   /// Return selector name. This is used for debugging
499   /// info.
500   StringRef getSelectorName(Selector S);
501 
502   /// Get class name including template argument list.
503   StringRef getClassName(const RecordDecl *RD);
504 
505   /// Get the vtable name for the given class.
506   StringRef getVTableName(const CXXRecordDecl *Decl);
507 
508   /// Get line number for the location. If location is invalid
509   /// then use current location.
510   unsigned getLineNumber(SourceLocation Loc);
511 
512   /// Get column number for the location. If location is
513   /// invalid then use current location.
514   /// \param Force  Assume DebugColumnInfo option is true.
515   unsigned getColumnNumber(SourceLocation Loc, bool Force = false);
516 
517   /// Collect various properties of a FunctionDecl.
518   /// \param GD  A GlobalDecl whose getDecl() must return a FunctionDecl.
519   void collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
520                                 StringRef &Name, StringRef &LinkageName,
521                                 llvm::DIScope *&FDContext,
522                                 llvm::DINodeArray &TParamsArray,
523                                 llvm::DINode::DIFlags &Flags);
524 
525   /// Collect various properties of a VarDecl.
526   void collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
527                            unsigned &LineNo, QualType &T, StringRef &Name,
528                            StringRef &LinkageName, llvm::DIScope *&VDContext);
529 
530   /// Allocate a copy of \p A using the DebugInfoNames allocator
531   /// and return a reference to it. If multiple arguments are given the strings
532   /// are concatenated.
533   StringRef internString(StringRef A, StringRef B = StringRef()) {
534     char *Data = DebugInfoNames.Allocate<char>(A.size() + B.size());
535     if (!A.empty())
536       std::memcpy(Data, A.data(), A.size());
537     if (!B.empty())
538       std::memcpy(Data + A.size(), B.data(), B.size());
539     return StringRef(Data, A.size() + B.size());
540   }
541 };
542 
543 /// A scoped helper to set the current debug location to the specified
544 /// location or preferred location of the specified Expr.
545 class ApplyDebugLocation {
546 private:
547   void init(SourceLocation TemporaryLocation, bool DefaultToEmpty = false);
548   ApplyDebugLocation(CodeGenFunction &CGF, bool DefaultToEmpty,
549                      SourceLocation TemporaryLocation);
550 
551   llvm::DebugLoc OriginalLocation;
552   CodeGenFunction *CGF;
553 
554 public:
555   /// Set the location to the (valid) TemporaryLocation.
556   ApplyDebugLocation(CodeGenFunction &CGF, SourceLocation TemporaryLocation);
557   ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E);
558   ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc);
559   ApplyDebugLocation(ApplyDebugLocation &&Other) : CGF(Other.CGF) {
560     Other.CGF = nullptr;
561   }
562 
563   ~ApplyDebugLocation();
564 
565   /// \brief Apply TemporaryLocation if it is valid. Otherwise switch
566   /// to an artificial debug location that has a valid scope, but no
567   /// line information.
568   ///
569   /// Artificial locations are useful when emitting compiler-generated
570   /// helper functions that have no source location associated with
571   /// them. The DWARF specification allows the compiler to use the
572   /// special line number 0 to indicate code that can not be
573   /// attributed to any source location. Note that passing an empty
574   /// SourceLocation to CGDebugInfo::setLocation() will result in the
575   /// last valid location being reused.
576   static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF) {
577     return ApplyDebugLocation(CGF, false, SourceLocation());
578   }
579   /// \brief Apply TemporaryLocation if it is valid. Otherwise switch
580   /// to an artificial debug location that has a valid scope, but no
581   /// line information.
582   static ApplyDebugLocation
583   CreateDefaultArtificial(CodeGenFunction &CGF,
584                           SourceLocation TemporaryLocation) {
585     return ApplyDebugLocation(CGF, false, TemporaryLocation);
586   }
587 
588   /// Set the IRBuilder to not attach debug locations.  Note that
589   /// passing an empty SourceLocation to \a CGDebugInfo::setLocation()
590   /// will result in the last valid location being reused.  Note that
591   /// all instructions that do not have a location at the beginning of
592   /// a function are counted towards to function prologue.
593   static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF) {
594     return ApplyDebugLocation(CGF, true, SourceLocation());
595   }
596 
597 };
598 
599 } // namespace CodeGen
600 } // namespace clang
601 
602 #endif // LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
603