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/IR/DIBuilder.h"
24 #include "llvm/IR/DebugInfo.h"
25 #include "llvm/IR/ValueHandle.h"
26 #include "llvm/Support/Allocator.h"
27 
28 namespace llvm {
29   class MDNode;
30 }
31 
32 namespace clang {
33   class CXXMethodDecl;
34   class VarDecl;
35   class ObjCInterfaceDecl;
36   class ObjCIvarDecl;
37   class ClassTemplateSpecializationDecl;
38   class GlobalDecl;
39   class UsingDecl;
40 
41 namespace CodeGen {
42   class CodeGenModule;
43   class CodeGenFunction;
44   class CGBlockInfo;
45 
46 /// CGDebugInfo - This class gathers all debug information during compilation
47 /// and is responsible for emitting to llvm globals or pass directly to
48 /// the backend.
49 class CGDebugInfo {
50   friend class ArtificialLocation;
51   friend class SaveAndRestoreLocation;
52   CodeGenModule &CGM;
53   const CodeGenOptions::DebugInfoKind DebugKind;
54   llvm::DIBuilder DBuilder;
55   llvm::DICompileUnit TheCU;
56   SourceLocation CurLoc, PrevLoc;
57   llvm::DIType VTablePtrType;
58   llvm::DIType ClassTy;
59   llvm::DICompositeType ObjTy;
60   llvm::DIType SelTy;
61   llvm::DIType OCLImage1dDITy, OCLImage1dArrayDITy, OCLImage1dBufferDITy;
62   llvm::DIType OCLImage2dDITy, OCLImage2dArrayDITy;
63   llvm::DIType OCLImage3dDITy;
64   llvm::DIType OCLEventDITy;
65   llvm::DIType BlockLiteralGeneric;
66 
67   /// TypeCache - Cache of previously constructed Types.
68   llvm::DenseMap<const void *, llvm::WeakVH> TypeCache;
69 
70   struct ObjCInterfaceCacheEntry {
71     const ObjCInterfaceType *Type;
72     llvm::DIType Decl;
73     llvm::DIFile Unit;
74     ObjCInterfaceCacheEntry(const ObjCInterfaceType *Type, llvm::DIType Decl,
75                             llvm::DIFile Unit)
76         : Type(Type), Decl(Decl), Unit(Unit) {}
77   };
78 
79   /// ObjCInterfaceCache - Cache of previously constructed interfaces
80   /// which may change.
81   llvm::SmallVector<ObjCInterfaceCacheEntry, 32> ObjCInterfaceCache;
82 
83   /// RetainedTypes - list of interfaces we want to keep even if orphaned.
84   std::vector<void *> RetainedTypes;
85 
86   /// ReplaceMap - Cache of forward declared types to RAUW at the end of
87   /// compilation.
88   std::vector<std::pair<const TagType *, llvm::WeakVH>> ReplaceMap;
89 
90   /// \brief Cache of replaceable forward declarartions (functions and
91   /// variables) to RAUW at the end of compilation.
92   std::vector<std::pair<const DeclaratorDecl *, llvm::WeakVH>> FwdDeclReplaceMap;
93 
94   // LexicalBlockStack - Keep track of our current nested lexical block.
95   std::vector<llvm::TrackingVH<llvm::MDNode> > LexicalBlockStack;
96   llvm::DenseMap<const Decl *, llvm::WeakVH> RegionMap;
97   // FnBeginRegionCount - Keep track of LexicalBlockStack counter at the
98   // beginning of a function. This is used to pop unbalanced regions at
99   // the end of a function.
100   std::vector<unsigned> FnBeginRegionCount;
101 
102   /// DebugInfoNames - This is a storage for names that are
103   /// constructed on demand. For example, C++ destructors, C++ operators etc..
104   llvm::BumpPtrAllocator DebugInfoNames;
105   StringRef CWDName;
106 
107   llvm::DenseMap<const char *, llvm::WeakVH> DIFileCache;
108   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH> SPCache;
109   /// \brief Cache declarations relevant to DW_TAG_imported_declarations (C++
110   /// using declarations) that aren't covered by other more specific caches.
111   llvm::DenseMap<const Decl *, llvm::WeakVH> DeclCache;
112   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH> NameSpaceCache;
113   llvm::DenseMap<const NamespaceAliasDecl *, llvm::WeakVH> NamespaceAliasCache;
114   llvm::DenseMap<const Decl *, llvm::WeakVH> StaticDataMemberCache;
115 
116   /// Helper functions for getOrCreateType.
117   unsigned Checksum(const ObjCInterfaceDecl *InterfaceDecl);
118   llvm::DIType CreateType(const BuiltinType *Ty);
119   llvm::DIType CreateType(const ComplexType *Ty);
120   llvm::DIType CreateQualifiedType(QualType Ty, llvm::DIFile Fg);
121   llvm::DIType CreateType(const TypedefType *Ty, llvm::DIFile Fg);
122   llvm::DIType CreateType(const TemplateSpecializationType *Ty, llvm::DIFile Fg);
123   llvm::DIType CreateType(const ObjCObjectPointerType *Ty,
124                           llvm::DIFile F);
125   llvm::DIType CreateType(const PointerType *Ty, llvm::DIFile F);
126   llvm::DIType CreateType(const BlockPointerType *Ty, llvm::DIFile F);
127   llvm::DIType CreateType(const FunctionType *Ty, llvm::DIFile F);
128   llvm::DIType CreateType(const RecordType *Tyg);
129   llvm::DIType CreateTypeDefinition(const RecordType *Ty);
130   llvm::DICompositeType CreateLimitedType(const RecordType *Ty);
131   void CollectContainingType(const CXXRecordDecl *RD, llvm::DICompositeType CT);
132   llvm::DIType CreateType(const ObjCInterfaceType *Ty, llvm::DIFile F);
133   llvm::DIType CreateTypeDefinition(const ObjCInterfaceType *Ty, llvm::DIFile F);
134   llvm::DIType CreateType(const ObjCObjectType *Ty, llvm::DIFile F);
135   llvm::DIType CreateType(const VectorType *Ty, llvm::DIFile F);
136   llvm::DIType CreateType(const ArrayType *Ty, llvm::DIFile F);
137   llvm::DIType CreateType(const LValueReferenceType *Ty, llvm::DIFile F);
138   llvm::DIType CreateType(const RValueReferenceType *Ty, llvm::DIFile Unit);
139   llvm::DIType CreateType(const MemberPointerType *Ty, llvm::DIFile F);
140   llvm::DIType CreateType(const AtomicType *Ty, llvm::DIFile F);
141   llvm::DIType CreateEnumType(const EnumType *Ty);
142   llvm::DIType CreateTypeDefinition(const EnumType *Ty);
143   llvm::DIType CreateSelfType(const QualType &QualTy, llvm::DIType Ty);
144   llvm::DIType getTypeOrNull(const QualType);
145   llvm::DICompositeType getOrCreateMethodType(const CXXMethodDecl *Method,
146                                               llvm::DIFile F);
147   llvm::DICompositeType getOrCreateInstanceMethodType(
148       QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit);
149   llvm::DICompositeType getOrCreateFunctionType(const Decl *D, QualType FnType,
150                                                 llvm::DIFile F);
151   llvm::DIType getOrCreateVTablePtrType(llvm::DIFile F);
152   llvm::DINameSpace getOrCreateNameSpace(const NamespaceDecl *N);
153   llvm::DIType getOrCreateTypeDeclaration(QualType PointeeTy, llvm::DIFile F);
154   llvm::DIType CreatePointerLikeType(llvm::dwarf::Tag Tag,
155                                      const Type *Ty, QualType PointeeTy,
156                                      llvm::DIFile F);
157 
158   llvm::Value *getCachedInterfaceTypeOrNull(const QualType Ty);
159   llvm::DIType getOrCreateStructPtrType(StringRef Name, llvm::DIType &Cache);
160 
161   llvm::DISubprogram CreateCXXMemberFunction(const CXXMethodDecl *Method,
162                                              llvm::DIFile F,
163                                              llvm::DIType RecordTy);
164 
165   void CollectCXXMemberFunctions(const CXXRecordDecl *Decl,
166                                  llvm::DIFile F,
167                                  SmallVectorImpl<llvm::Value *> &E,
168                                  llvm::DIType T);
169 
170   void CollectCXXBases(const CXXRecordDecl *Decl,
171                        llvm::DIFile F,
172                        SmallVectorImpl<llvm::Value *> &EltTys,
173                        llvm::DIType RecordTy);
174 
175   llvm::DIArray
176   CollectTemplateParams(const TemplateParameterList *TPList,
177                         ArrayRef<TemplateArgument> TAList,
178                         llvm::DIFile Unit);
179   llvm::DIArray
180   CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit);
181   llvm::DIArray
182   CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TS,
183                            llvm::DIFile F);
184 
185   llvm::DIType createFieldType(StringRef name, QualType type,
186                                uint64_t sizeInBitsOverride, SourceLocation loc,
187                                AccessSpecifier AS,
188                                uint64_t offsetInBits,
189                                llvm::DIFile tunit,
190                                llvm::DIScope scope,
191                                const RecordDecl* RD = nullptr);
192 
193   // Helpers for collecting fields of a record.
194   void CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
195                                  SmallVectorImpl<llvm::Value *> &E,
196                                  llvm::DIType RecordTy);
197   llvm::DIDerivedType CreateRecordStaticField(const VarDecl *Var,
198                                               llvm::DIType RecordTy,
199                                               const RecordDecl* RD);
200   void CollectRecordNormalField(const FieldDecl *Field, uint64_t OffsetInBits,
201                                 llvm::DIFile F,
202                                 SmallVectorImpl<llvm::Value *> &E,
203                                 llvm::DIType RecordTy,
204                                 const RecordDecl* RD);
205   void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile F,
206                            SmallVectorImpl<llvm::Value *> &E,
207                            llvm::DICompositeType RecordTy);
208 
209   void CollectVTableInfo(const CXXRecordDecl *Decl,
210                          llvm::DIFile F,
211                          SmallVectorImpl<llvm::Value *> &EltTys);
212 
213   // CreateLexicalBlock - Create a new lexical block node and push it on
214   // the stack.
215   void CreateLexicalBlock(SourceLocation Loc);
216 
217 public:
218   CGDebugInfo(CodeGenModule &CGM);
219   ~CGDebugInfo();
220 
221   void finalize();
222 
223   /// setLocation - Update the current source location. If \arg loc is
224   /// invalid it is ignored.
225   void setLocation(SourceLocation Loc);
226 
227   /// getLocation - Return the current source location.
228   SourceLocation getLocation() const { return CurLoc; }
229 
230   /// EmitLocation - Emit metadata to indicate a change in line/column
231   /// information in the source file.
232   /// \param ForceColumnInfo  Assume DebugColumnInfo option is true.
233   void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
234                     bool ForceColumnInfo = false);
235 
236   /// EmitFunctionStart - Emit a call to llvm.dbg.function.start to indicate
237   /// start of a new function.
238   /// \param Loc       The location of the function header.
239   /// \param ScopeLoc  The location of the function body.
240   void EmitFunctionStart(GlobalDecl GD,
241                          SourceLocation Loc, SourceLocation ScopeLoc,
242                          QualType FnType, llvm::Function *Fn,
243                          CGBuilderTy &Builder);
244 
245   /// EmitFunctionEnd - Constructs the debug code for exiting a function.
246   void EmitFunctionEnd(CGBuilderTy &Builder);
247 
248   /// EmitLexicalBlockStart - Emit metadata to indicate the beginning of a
249   /// new lexical block and push the block onto the stack.
250   void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc);
251 
252   /// EmitLexicalBlockEnd - Emit metadata to indicate the end of a new lexical
253   /// block and pop the current block.
254   void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc);
255 
256   /// EmitDeclareOfAutoVariable - Emit call to llvm.dbg.declare for an automatic
257   /// variable declaration.
258   void EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI,
259                                  CGBuilderTy &Builder);
260 
261   /// EmitDeclareOfBlockDeclRefVariable - Emit call to llvm.dbg.declare for an
262   /// imported variable declaration in a block.
263   void EmitDeclareOfBlockDeclRefVariable(const VarDecl *variable,
264                                          llvm::Value *storage,
265                                          CGBuilderTy &Builder,
266                                          const CGBlockInfo &blockInfo);
267 
268   /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
269   /// variable declaration.
270   void EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
271                                 unsigned ArgNo, CGBuilderTy &Builder);
272 
273   /// EmitDeclareOfBlockLiteralArgVariable - Emit call to
274   /// llvm.dbg.declare for the block-literal argument to a block
275   /// invocation function.
276   void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
277                                             llvm::Value *Arg, unsigned ArgNo,
278                                             llvm::Value *LocalAddr,
279                                             CGBuilderTy &Builder);
280 
281   /// EmitGlobalVariable - Emit information about a global variable.
282   void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
283 
284   /// EmitGlobalVariable - Emit global variable's debug info.
285   void EmitGlobalVariable(const ValueDecl *VD, llvm::Constant *Init);
286 
287   /// \brief - Emit C++ using directive.
288   void EmitUsingDirective(const UsingDirectiveDecl &UD);
289 
290   /// EmitExplicitCastType - Emit the type explicitly casted to.
291   void EmitExplicitCastType(QualType Ty);
292 
293   /// \brief - Emit C++ using declaration.
294   void EmitUsingDecl(const UsingDecl &UD);
295 
296   /// \brief - Emit C++ namespace alias.
297   llvm::DIImportedEntity EmitNamespaceAlias(const NamespaceAliasDecl &NA);
298 
299   /// getOrCreateRecordType - Emit record type's standalone debug info.
300   llvm::DIType getOrCreateRecordType(QualType Ty, SourceLocation L);
301 
302   /// getOrCreateInterfaceType - Emit an objective c interface type standalone
303   /// debug info.
304   llvm::DIType getOrCreateInterfaceType(QualType Ty,
305                                         SourceLocation Loc);
306 
307   void completeType(const EnumDecl *ED);
308   void completeType(const RecordDecl *RD);
309   void completeRequiredType(const RecordDecl *RD);
310   void completeClassData(const RecordDecl *RD);
311 
312   void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD);
313 
314 private:
315   /// EmitDeclare - Emit call to llvm.dbg.declare for a variable declaration.
316   /// Tag accepts custom types DW_TAG_arg_variable and DW_TAG_auto_variable,
317   /// otherwise would be of type llvm::dwarf::Tag.
318   void EmitDeclare(const VarDecl *decl, llvm::dwarf::LLVMConstants Tag,
319                    llvm::Value *AI, unsigned ArgNo, CGBuilderTy &Builder);
320 
321   // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
322   // See BuildByRefType.
323   llvm::DIType EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
324                                             uint64_t *OffSet);
325 
326   /// getContextDescriptor - Get context info for the decl.
327   llvm::DIScope getContextDescriptor(const Decl *Decl);
328 
329   llvm::DIScope getCurrentContextDescriptor(const Decl *Decl);
330 
331   /// \brief Create a forward decl for a RecordType in a given context.
332   llvm::DICompositeType getOrCreateRecordFwdDecl(const RecordType *,
333                                                  llvm::DIDescriptor);
334 
335   /// createContextChain - Create a set of decls for the context chain.
336   llvm::DIDescriptor createContextChain(const Decl *Decl);
337 
338   /// getCurrentDirname - Return current directory name.
339   StringRef getCurrentDirname();
340 
341   /// CreateCompileUnit - Create new compile unit.
342   void CreateCompileUnit();
343 
344   /// getOrCreateFile - Get the file debug info descriptor for the input
345   /// location.
346   llvm::DIFile getOrCreateFile(SourceLocation Loc);
347 
348   /// getOrCreateMainFile - Get the file info for main compile unit.
349   llvm::DIFile getOrCreateMainFile();
350 
351   /// getOrCreateType - Get the type from the cache or create a new type if
352   /// necessary.
353   llvm::DIType getOrCreateType(QualType Ty, llvm::DIFile Fg);
354 
355   /// getOrCreateLimitedType - Get the type from the cache or create a new
356   /// partial type if necessary.
357   llvm::DIType getOrCreateLimitedType(const RecordType *Ty, llvm::DIFile F);
358 
359   /// CreateTypeNode - Create type metadata for a source language type.
360   llvm::DIType CreateTypeNode(QualType Ty, llvm::DIFile Fg);
361 
362   /// getObjCInterfaceDecl - return the underlying ObjCInterfaceDecl
363   /// if Ty is an ObjCInterface or a pointer to one.
364   ObjCInterfaceDecl* getObjCInterfaceDecl(QualType Ty);
365 
366   /// CreateMemberType - Create new member and increase Offset by FType's size.
367   llvm::DIType CreateMemberType(llvm::DIFile Unit, QualType FType,
368                                 StringRef Name, uint64_t *Offset);
369 
370   /// \brief Retrieve the DIDescriptor, if any, for the canonical form of this
371   /// declaration.
372   llvm::DIDescriptor getDeclarationOrDefinition(const Decl *D);
373 
374   /// getFunctionDeclaration - Return debug info descriptor to describe method
375   /// declaration for the given method definition.
376   llvm::DISubprogram getFunctionDeclaration(const Decl *D);
377 
378   /// Return debug info descriptor to describe in-class static data member
379   /// declaration for the given out-of-class definition.
380   llvm::DIDerivedType
381   getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D);
382 
383   /// \brief Create a DISubprogram describing the forward
384   /// decalration represented in the given FunctionDecl.
385   llvm::DISubprogram getFunctionForwardDeclaration(const FunctionDecl *FD);
386 
387   /// \brief Create a DIGlobalVariable describing the forward
388   /// decalration represented in the given VarDecl.
389   llvm::DIGlobalVariable getGlobalVariableForwardDeclaration(const VarDecl *VD);
390 
391   /// Return a global variable that represents one of the collection of
392   /// global variables created for an anonmyous union.
393   llvm::DIGlobalVariable
394   CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile Unit, unsigned LineNo,
395                          StringRef LinkageName, llvm::GlobalVariable *Var,
396                          llvm::DIDescriptor DContext);
397 
398   /// getFunctionName - Get function name for the given FunctionDecl. If the
399   /// name is constructed on demand (e.g. C++ destructor) then the name
400   /// is stored on the side.
401   StringRef getFunctionName(const FunctionDecl *FD);
402 
403   /// getObjCMethodName - Returns the unmangled name of an Objective-C method.
404   /// This is the display name for the debugging info.
405   StringRef getObjCMethodName(const ObjCMethodDecl *FD);
406 
407   /// getSelectorName - Return selector name. This is used for debugging
408   /// info.
409   StringRef getSelectorName(Selector S);
410 
411   /// getClassName - Get class name including template argument list.
412   StringRef getClassName(const RecordDecl *RD);
413 
414   /// getVTableName - Get vtable name for the given Class.
415   StringRef getVTableName(const CXXRecordDecl *Decl);
416 
417   /// getLineNumber - Get line number for the location. If location is invalid
418   /// then use current location.
419   unsigned getLineNumber(SourceLocation Loc);
420 
421   /// getColumnNumber - Get column number for the location. If location is
422   /// invalid then use current location.
423   /// \param Force  Assume DebugColumnInfo option is true.
424   unsigned getColumnNumber(SourceLocation Loc, bool Force=false);
425 
426   /// \brief Collect various properties of a FunctionDecl.
427   /// \param GD  A GlobalDecl whose getDecl() must return a FunctionDecl.
428   void collectFunctionDeclProps(GlobalDecl GD,
429                                 llvm::DIFile Unit,
430                                 StringRef &Name, StringRef &LinkageName,
431                                 llvm::DIDescriptor &FDContext,
432                                 llvm::DIArray &TParamsArray,
433                                 unsigned &Flags);
434 
435   /// \brief Collect various properties of a VarDecl.
436   void collectVarDeclProps(const VarDecl *VD, llvm::DIFile &Unit,
437                            unsigned &LineNo, QualType &T,
438                            StringRef &Name, StringRef &LinkageName,
439                            llvm::DIDescriptor &VDContext);
440 
441   /// internString - Allocate a copy of \p A using the DebugInfoNames allocator
442   /// and return a reference to it. If multiple arguments are given the strings
443   /// are concatenated.
444   StringRef internString(StringRef A, StringRef B = StringRef()) {
445     char *Data = DebugInfoNames.Allocate<char>(A.size() + B.size());
446     std::memcpy(Data, A.data(), A.size());
447     std::memcpy(Data + A.size(), B.data(), B.size());
448     return StringRef(Data, A.size() + B.size());
449   }
450 };
451 
452 /// SaveAndRestoreLocation - An RAII object saves the current location
453 /// and automatically restores it to the original value.
454 class SaveAndRestoreLocation {
455 protected:
456   SourceLocation SavedLoc;
457   CGDebugInfo *DI;
458   CGBuilderTy &Builder;
459 public:
460   SaveAndRestoreLocation(CodeGenFunction &CGF, CGBuilderTy &B);
461   /// Autorestore everything back to normal.
462   ~SaveAndRestoreLocation();
463 };
464 
465 /// NoLocation - An RAII object that temporarily disables debug
466 /// locations. This is useful for emitting instructions that should be
467 /// counted towards the function prologue.
468 class NoLocation : public SaveAndRestoreLocation {
469 public:
470   NoLocation(CodeGenFunction &CGF, CGBuilderTy &B);
471   /// Autorestore everything back to normal.
472   ~NoLocation();
473 };
474 
475 /// ArtificialLocation - An RAII object that temporarily switches to
476 /// an artificial debug location that has a valid scope, but no line
477 /// information. This is useful when emitting compiler-generated
478 /// helper functions that have no source location associated with
479 /// them. The DWARF specification allows the compiler to use the
480 /// special line number 0 to indicate code that can not be attributed
481 /// to any source location.
482 ///
483 /// This is necessary because passing an empty SourceLocation to
484 /// CGDebugInfo::setLocation() will result in the last valid location
485 /// being reused.
486 class ArtificialLocation : public SaveAndRestoreLocation {
487 public:
488   ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B);
489 
490   /// Set the current location to line 0, but within the current scope
491   /// (= the top of the LexicalBlockStack).
492   void Emit();
493 
494   /// Autorestore everything back to normal.
495   ~ArtificialLocation();
496 };
497 
498 
499 } // namespace CodeGen
500 } // namespace clang
501 
502 
503 #endif
504