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