1125a94c4fc39c7d023d24ceafe340cad3a8bb12
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfDebug.h
1 //===-- llvm/CodeGen/DwarfDebug.h - Dwarf Debug Framework ------*- 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 file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef CODEGEN_ASMPRINTER_DWARFDEBUG_H__
15 #define CODEGEN_ASMPRINTER_DWARFDEBUG_H__
16
17 #include "DIE.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/LexicalScopes.h"
25 #include "llvm/DebugInfo.h"
26 #include "llvm/MC/MachineLocation.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/DebugLoc.h"
29
30 namespace llvm {
31
32 class CompileUnit;
33 class ConstantInt;
34 class ConstantFP;
35 class DbgVariable;
36 class MachineFrameInfo;
37 class MachineModuleInfo;
38 class MachineOperand;
39 class MCAsmInfo;
40 class DIEAbbrev;
41 class DIE;
42 class DIEBlock;
43 class DIEEntry;
44
45 //===----------------------------------------------------------------------===//
46 /// \brief This class is used to record source line correspondence.
47 class SrcLineInfo {
48   unsigned Line;                     // Source line number.
49   unsigned Column;                   // Source column.
50   unsigned SourceID;                 // Source ID number.
51   MCSymbol *Label;                   // Label in code ID number.
52 public:
53   SrcLineInfo(unsigned L, unsigned C, unsigned S, MCSymbol *label)
54     : Line(L), Column(C), SourceID(S), Label(label) {}
55
56   // Accessors
57   unsigned getLine() const { return Line; }
58   unsigned getColumn() const { return Column; }
59   unsigned getSourceID() const { return SourceID; }
60   MCSymbol *getLabel() const { return Label; }
61 };
62
63 /// \brief This struct describes location entries emitted in the .debug_loc
64 /// section.
65 typedef struct DotDebugLocEntry {
66   const MCSymbol *Begin;
67   const MCSymbol *End;
68   MachineLocation Loc;
69   const MDNode *Variable;
70   bool Merged;
71   bool Constant;
72   enum EntryType {
73     E_Location,
74     E_Integer,
75     E_ConstantFP,
76     E_ConstantInt
77   };
78   enum EntryType EntryKind;
79
80   union {
81     int64_t Int;
82     const ConstantFP *CFP;
83     const ConstantInt *CIP;
84   } Constants;
85   DotDebugLocEntry()
86     : Begin(0), End(0), Variable(0), Merged(false),
87       Constant(false) { Constants.Int = 0;}
88   DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E, MachineLocation &L,
89                    const MDNode *V)
90     : Begin(B), End(E), Loc(L), Variable(V), Merged(false),
91       Constant(false) { Constants.Int = 0; EntryKind = E_Location; }
92   DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E, int64_t i)
93     : Begin(B), End(E), Variable(0), Merged(false),
94       Constant(true) { Constants.Int = i; EntryKind = E_Integer; }
95   DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E, const ConstantFP *FPtr)
96     : Begin(B), End(E), Variable(0), Merged(false),
97       Constant(true) { Constants.CFP = FPtr; EntryKind = E_ConstantFP; }
98   DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E,
99                    const ConstantInt *IPtr)
100     : Begin(B), End(E), Variable(0), Merged(false),
101       Constant(true) { Constants.CIP = IPtr; EntryKind = E_ConstantInt; }
102
103   /// \brief Empty entries are also used as a trigger to emit temp label. Such
104   /// labels are referenced is used to find debug_loc offset for a given DIE.
105   bool isEmpty() { return Begin == 0 && End == 0; }
106   bool isMerged() { return Merged; }
107   void Merge(DotDebugLocEntry *Next) {
108     if (!(Begin && Loc == Next->Loc && End == Next->Begin))
109       return;
110     Next->Begin = Begin;
111     Merged = true;
112   }
113   bool isLocation() const    { return EntryKind == E_Location; }
114   bool isInt() const         { return EntryKind == E_Integer; }
115   bool isConstantFP() const  { return EntryKind == E_ConstantFP; }
116   bool isConstantInt() const { return EntryKind == E_ConstantInt; }
117   int64_t getInt()                    { return Constants.Int; }
118   const ConstantFP *getConstantFP()   { return Constants.CFP; }
119   const ConstantInt *getConstantInt() { return Constants.CIP; }
120 } DotDebugLocEntry;
121
122 //===----------------------------------------------------------------------===//
123 /// \brief This class is used to track local variable information.
124 class DbgVariable {
125   DIVariable Var;                    // Variable Descriptor.
126   DIE *TheDIE;                       // Variable DIE.
127   unsigned DotDebugLocOffset;        // Offset in DotDebugLocEntries.
128   DbgVariable *AbsVar;               // Corresponding Abstract variable, if any.
129   const MachineInstr *MInsn;         // DBG_VALUE instruction of the variable.
130   int FrameIndex;
131 public:
132   // AbsVar may be NULL.
133   DbgVariable(DIVariable V, DbgVariable *AV)
134     : Var(V), TheDIE(0), DotDebugLocOffset(~0U), AbsVar(AV), MInsn(0),
135       FrameIndex(~0) {}
136
137   // Accessors.
138   DIVariable getVariable()           const { return Var; }
139   void setDIE(DIE *D)                      { TheDIE = D; }
140   DIE *getDIE()                      const { return TheDIE; }
141   void setDotDebugLocOffset(unsigned O)    { DotDebugLocOffset = O; }
142   unsigned getDotDebugLocOffset()    const { return DotDebugLocOffset; }
143   StringRef getName()                const { return Var.getName(); }
144   DbgVariable *getAbstractVariable() const { return AbsVar; }
145   const MachineInstr *getMInsn()     const { return MInsn; }
146   void setMInsn(const MachineInstr *M)     { MInsn = M; }
147   int getFrameIndex()                const { return FrameIndex; }
148   void setFrameIndex(int FI)               { FrameIndex = FI; }
149   // Translate tag to proper Dwarf tag.
150   unsigned getTag()                  const {
151     if (Var.getTag() == dwarf::DW_TAG_arg_variable)
152       return dwarf::DW_TAG_formal_parameter;
153
154     return dwarf::DW_TAG_variable;
155   }
156   /// \brief Return true if DbgVariable is artificial.
157   bool isArtificial()                const {
158     if (Var.isArtificial())
159       return true;
160     if (getType().isArtificial())
161       return true;
162     return false;
163   }
164
165   bool isObjectPointer()             const {
166     if (Var.isObjectPointer())
167       return true;
168     if (getType().isObjectPointer())
169       return true;
170     return false;
171   }
172
173   bool variableHasComplexAddress()   const {
174     assert(Var.Verify() && "Invalid complex DbgVariable!");
175     return Var.hasComplexAddress();
176   }
177   bool isBlockByrefVariable()        const {
178     assert(Var.Verify() && "Invalid complex DbgVariable!");
179     return Var.isBlockByrefVariable();
180   }
181   unsigned getNumAddrElements()      const {
182     assert(Var.Verify() && "Invalid complex DbgVariable!");
183     return Var.getNumAddrElements();
184   }
185   uint64_t getAddrElement(unsigned i) const {
186     return Var.getAddrElement(i);
187   }
188   DIType getType() const;
189 };
190
191 /// \brief Collects and handles dwarf debug information.
192 class DwarfDebug {
193   // Target of Dwarf emission.
194   AsmPrinter *Asm;
195
196   // Collected machine module information.
197   MachineModuleInfo *MMI;
198
199   // All DIEValues are allocated through this allocator.
200   BumpPtrAllocator DIEValueAllocator;
201
202   //===--------------------------------------------------------------------===//
203   // Attributes used to construct specific Dwarf sections.
204   //
205
206   CompileUnit *FirstCU;
207
208   // Maps MDNode with its corresponding CompileUnit.
209   DenseMap <const MDNode *, CompileUnit *> CUMap;
210
211   // Maps subprogram MDNode with its corresponding CompileUnit.
212   DenseMap <const MDNode *, CompileUnit *> SPMap;
213
214   // Used to uniquely define abbreviations.
215   FoldingSet<DIEAbbrev> AbbreviationsSet;
216
217   // A list of all the unique abbreviations in use.
218   std::vector<DIEAbbrev *> Abbreviations;
219
220   // Source id map, i.e. pair of source filename and directory,
221   // separated by a zero byte, mapped to a unique id.
222   StringMap<unsigned, BumpPtrAllocator&> SourceIdMap;
223
224   // A String->Symbol mapping of strings used by indirect
225   // references.
226   StringMap<std::pair<MCSymbol*, unsigned>, BumpPtrAllocator&> StringPool;
227   unsigned NextStringPoolNumber;
228
229   // Provides a unique id per text section.
230   SetVector<const MCSection*> SectionMap;
231
232   // List of Arguments (DbgValues) for current function.
233   SmallVector<DbgVariable *, 8> CurrentFnArguments;
234
235   LexicalScopes LScopes;
236
237   // Collection of abstract subprogram DIEs.
238   DenseMap<const MDNode *, DIE *> AbstractSPDies;
239
240   // Collection of dbg variables of a scope.
241   DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> > ScopeVariables;
242
243   // Collection of abstract variables.
244   DenseMap<const MDNode *, DbgVariable *> AbstractVariables;
245
246   // Collection of DotDebugLocEntry.
247   SmallVector<DotDebugLocEntry, 4> DotDebugLocEntries;
248
249   // Collection of subprogram DIEs that are marked (at the end of the module)
250   // as DW_AT_inline.
251   SmallPtrSet<DIE *, 4> InlinedSubprogramDIEs;
252
253   // Keep track of inlined functions and their location.  This
254   // information is used to populate the debug_inlined section.
255   typedef std::pair<const MCSymbol *, DIE *> InlineInfoLabels;
256   DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> > InlineInfo;
257   SmallVector<const MDNode *, 4> InlinedSPNodes;
258
259   // This is a collection of subprogram MDNodes that are processed to create DIEs.
260   SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
261
262   // Maps instruction with label emitted before instruction.
263   DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
264
265   // Maps instruction with label emitted after instruction.
266   DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
267
268   // Every user variable mentioned by a DBG_VALUE instruction in order of
269   // appearance.
270   SmallVector<const MDNode*, 8> UserVariables;
271
272   // For each user variable, keep a list of DBG_VALUE instructions in order.
273   // The list can also contain normal instructions that clobber the previous
274   // DBG_VALUE.
275   typedef DenseMap<const MDNode*, SmallVector<const MachineInstr*, 4> >
276     DbgValueHistoryMap;
277   DbgValueHistoryMap DbgValues;
278
279   SmallVector<const MCSymbol *, 8> DebugRangeSymbols;
280
281   // Previous instruction's location information. This is used to determine
282   // label location to indicate scope boundries in dwarf debug info.
283   DebugLoc PrevInstLoc;
284   MCSymbol *PrevLabel;
285
286   // This location indicates end of function prologue and beginning of function
287   // body.
288   DebugLoc PrologEndLoc;
289
290   struct FunctionDebugFrameInfo {
291     unsigned Number;
292     std::vector<MachineMove> Moves;
293
294     FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M)
295       : Number(Num), Moves(M) {}
296   };
297
298   std::vector<FunctionDebugFrameInfo> DebugFrames;
299
300   // Section Symbols: these are assembler temporary labels that are emitted at
301   // the beginning of each supported dwarf section.  These are used to form
302   // section offsets and are created by EmitSectionLabels.
303   MCSymbol *DwarfInfoSectionSym, *DwarfAbbrevSectionSym;
304   MCSymbol *DwarfStrSectionSym, *TextSectionSym, *DwarfDebugRangeSectionSym;
305   MCSymbol *DwarfDebugLocSectionSym;
306   MCSymbol *FunctionBeginSym, *FunctionEndSym;
307
308   // As an optimization, there is no need to emit an entry in the directory
309   // table for the same directory as DW_at_comp_dir.
310   StringRef CompilationDir;
311
312   // Holders for the various debug information flags that we might need to
313   // have exposed. See accessor functions below for description.
314   bool IsDarwinGDBCompat;
315
316   // Counter for assigning globally unique IDs for CUs.
317   unsigned GlobalCUIndexCount;
318
319   // DWARF5 Experimental Options
320   bool HasDwarfAccelTables;
321   bool HasSplitDwarf;
322
323   // Fission Variables
324   // In general these will all be for bits that are left in the
325   // original object file, rather than things that are meant
326   // to be in the .dwo sections.
327
328   // The CU left in the original object file for Fission debug info.
329   CompileUnit *SkeletonCU;
330
331 private:
332
333   /// \brief Define a unique number for the abbreviation.
334   void assignAbbrevNumber(DIEAbbrev &Abbrev);
335
336   void addScopeVariable(LexicalScope *LS, DbgVariable *Var);
337
338   /// \brief Find abstract variable associated with Var.
339   DbgVariable *findAbstractVariable(DIVariable &Var, DebugLoc Loc);
340
341   /// \brief Find DIE for the given subprogram and attach appropriate
342   /// DW_AT_low_pc and DW_AT_high_pc attributes. If there are global
343   /// variables in this scope then create and insert DIEs for these
344   /// variables.
345   DIE *updateSubprogramScopeDIE(CompileUnit *SPCU, const MDNode *SPNode);
346
347   /// \brief Construct new DW_TAG_lexical_block for this scope and
348   /// attach DW_AT_low_pc/DW_AT_high_pc labels.
349   DIE *constructLexicalScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
350
351   /// \brief This scope represents inlined body of a function. Construct
352   /// DIE to represent this concrete inlined copy of the function.
353   DIE *constructInlinedScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
354
355   /// \brief Construct a DIE for this scope.
356   DIE *constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
357
358   /// \brief Emit initial Dwarf sections with a label at the start of each one.
359   void emitSectionLabels();
360
361   /// \brief Recursively Emits a debug information entry.
362   void emitDIE(DIE *Die);
363
364   /// \brief Compute the size and offset of a DIE given an incoming Offset.
365   unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
366
367   /// \brief Compute the size and offset of all the DIEs.
368   void computeSizeAndOffsets();
369
370   /// \brief Attach DW_AT_inline attribute with inlined subprogram DIEs.
371   void computeInlinedDIEs();
372
373   /// \brief Collect info for variables that were optimized out.
374   void collectDeadVariables();
375
376   /// \brief Finish off debug information after all functions have been
377   /// processed.
378   void finalizeModuleInfo();
379
380   /// \brief Emit labels to close any remaining sections that have been left
381   /// open.
382   void endSections();
383
384   /// \brief Emit all of the compile units to the target section.
385   void emitCompileUnits(const MCSection *);
386
387   /// \brief Emit the debug info section.
388   void emitDebugInfo();
389
390   /// \brief Emit the abbreviation section.
391   void emitAbbreviations();
392
393   /// \brief Emit the last address of the section and the end of
394   /// the line matrix.
395   void emitEndOfLineMatrix(unsigned SectionEnd);
396
397   /// \brief Emit visible names into a hashed accelerator table section.
398   void emitAccelNames();
399
400   /// \brief Emit objective C classes and categories into a hashed
401   /// accelerator table section.
402   void emitAccelObjC();
403
404   /// \brief Emit namespace dies into a hashed accelerator table.
405   void emitAccelNamespaces();
406
407   /// \brief Emit type dies into a hashed accelerator table.
408   void emitAccelTypes();
409
410   /// \brief Emit visible types into a debug pubtypes section.
411   void emitDebugPubTypes();
412
413   /// \brief Emit visible names into a debug str section.
414   void emitDebugStr();
415
416   /// \brief Emit visible names into a debug loc section.
417   void emitDebugLoc();
418
419   /// \brief Emit visible names into a debug aranges section.
420   void emitDebugARanges();
421
422   /// \brief Emit visible names into a debug ranges section.
423   void emitDebugRanges();
424
425   /// \brief Emit visible names into a debug macinfo section.
426   void emitDebugMacInfo();
427
428   /// \brief Emit inline info using custom format.
429   void emitDebugInlineInfo();
430
431   /// DWARF 5 Experimental Split Dwarf Emitters
432
433   /// \brief Construct the split debug info compile unit for the debug info
434   /// section.
435   CompileUnit *constructSkeletonCU(const MDNode *);
436
437   /// \brief Emit the local split debug info section.
438   void emitSkeletonCU(const MCSection *);
439
440   /// \brief Emit the debug info dwo section.
441   void emitDebugInfoDWO();
442
443   /// \brief Create new CompileUnit for the given metadata node with tag
444   /// DW_TAG_compile_unit.
445   CompileUnit *constructCompileUnit(const MDNode *N);
446
447   /// \brief Construct subprogram DIE.
448   void constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N);
449
450   /// \brief Register a source line with debug info. Returns the unique
451   /// label that was emitted and which provides correspondence to the
452   /// source line list.
453   void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
454                         unsigned Flags);
455
456   /// \brief Indentify instructions that are marking the beginning of or
457   /// ending of a scope.
458   void identifyScopeMarkers();
459
460   /// \brief If Var is an current function argument that add it in
461   /// CurrentFnArguments list.
462   bool addCurrentFnArgument(const MachineFunction *MF,
463                             DbgVariable *Var, LexicalScope *Scope);
464
465   /// \brief Populate LexicalScope entries with variables' info.
466   void collectVariableInfo(const MachineFunction *,
467                            SmallPtrSet<const MDNode *, 16> &ProcessedVars);
468
469   /// \brief Collect variable information from the side table maintained
470   /// by MMI.
471   void collectVariableInfoFromMMITable(const MachineFunction * MF,
472                                        SmallPtrSet<const MDNode *, 16> &P);
473
474   /// \brief Ensure that a label will be emitted before MI.
475   void requestLabelBeforeInsn(const MachineInstr *MI) {
476     LabelsBeforeInsn.insert(std::make_pair(MI, (MCSymbol*)0));
477   }
478
479   /// \brief Return Label preceding the instruction.
480   const MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
481
482   /// \brief Ensure that a label will be emitted after MI.
483   void requestLabelAfterInsn(const MachineInstr *MI) {
484     LabelsAfterInsn.insert(std::make_pair(MI, (MCSymbol*)0));
485   }
486
487   /// \brief Return Label immediately following the instruction.
488   const MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
489
490 public:
491   //===--------------------------------------------------------------------===//
492   // Main entry points.
493   //
494   DwarfDebug(AsmPrinter *A, Module *M);
495   ~DwarfDebug();
496
497   /// \brief Collect debug info from named mdnodes such as llvm.dbg.enum
498   /// and llvm.dbg.ty
499   void collectInfoFromNamedMDNodes(const Module *M);
500
501   /// \brief Collect debug info using DebugInfoFinder.
502   /// FIXME - Remove this when DragonEgg switches to DIBuilder.
503   bool collectLegacyDebugInfo(const Module *M);
504
505   /// \brief Emit all Dwarf sections that should come prior to the
506   /// content.
507   void beginModule();
508
509   /// \brief Emit all Dwarf sections that should come after the content.
510   void endModule();
511
512   /// \brief Gather pre-function debug information.
513   void beginFunction(const MachineFunction *MF);
514
515   /// \brief Gather and emit post-function debug information.
516   void endFunction(const MachineFunction *MF);
517
518   /// \brief Process beginning of an instruction.
519   void beginInstruction(const MachineInstr *MI);
520
521   /// \brief Process end of an instruction.
522   void endInstruction(const MachineInstr *MI);
523
524   /// \brief Look up the source id with the given directory and source file
525   /// names. If none currently exists, create a new id and insert it in the
526   /// SourceIds map.
527   unsigned getOrCreateSourceID(StringRef DirName, StringRef FullName);
528
529   /// \brief Returns the entry into the start of the pool.
530   MCSymbol *getStringPool();
531
532   /// \brief Returns an entry into the string pool with the given
533   /// string text.
534   MCSymbol *getStringPoolEntry(StringRef Str);
535
536   /// \brief Returns whether or not to limit some of our debug
537   /// output to the limitations of darwin gdb.
538   bool useDarwinGDBCompat() { return IsDarwinGDBCompat; }
539
540   // Experimental DWARF5 features.
541
542   /// \brief Returns whether or not to emit tables that dwarf consumers can
543   /// use to accelerate lookup.
544   bool useDwarfAccelTables() { return HasDwarfAccelTables; }
545
546   /// \brief Returns whether or not to change the current debug info for the
547   /// split dwarf proposal support.
548   bool useSplitDwarf() { return HasSplitDwarf; }
549 };
550 } // End of namespace llvm
551
552 #endif