DwarfDebug: Allocate DIEValues with a BumpPtrAllocator. Most of them are
[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 "DwarfPrinter.h"
19 #include "llvm/CodeGen/AsmPrinter.h"
20 #include "llvm/CodeGen/MachineLocation.h"
21 #include "llvm/Analysis/DebugInfo.h"
22 #include "llvm/Support/Allocator.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/FoldingSet.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/UniqueVector.h"
29 #include <string>
30
31 namespace llvm {
32
33 class CompileUnit;
34 class DbgConcreteScope;
35 class DbgScope;
36 class DbgVariable;
37 class MachineFrameInfo;
38 class MachineModuleInfo;
39 class MCAsmInfo;
40 class Timer;
41
42 //===----------------------------------------------------------------------===//
43 /// SrcLineInfo - This class is used to record source line correspondence.
44 ///
45 class SrcLineInfo {
46   unsigned Line;                     // Source line number.
47   unsigned Column;                   // Source column.
48   unsigned SourceID;                 // Source ID number.
49   MCSymbol *Label;                   // Label in code ID number.
50 public:
51   SrcLineInfo(unsigned L, unsigned C, unsigned S, MCSymbol *label)
52     : Line(L), Column(C), SourceID(S), Label(label) {}
53
54   // Accessors
55   unsigned getLine() const { return Line; }
56   unsigned getColumn() const { return Column; }
57   unsigned getSourceID() const { return SourceID; }
58   MCSymbol *getLabel() const { return Label; }
59 };
60
61 class DwarfDebug : public DwarfPrinter {
62   //===--------------------------------------------------------------------===//
63   // Attributes used to construct specific Dwarf sections.
64   //
65
66   /// ModuleCU - All DIEs are inserted in ModuleCU.
67   CompileUnit *ModuleCU;
68
69   /// AbbreviationsSet - Used to uniquely define abbreviations.
70   ///
71   FoldingSet<DIEAbbrev> AbbreviationsSet;
72
73   /// Abbreviations - A list of all the unique abbreviations in use.
74   ///
75   std::vector<DIEAbbrev *> Abbreviations;
76
77   /// DirectoryIdMap - Directory name to directory id map.
78   ///
79   StringMap<unsigned> DirectoryIdMap;
80
81   /// DirectoryNames - A list of directory names.
82   SmallVector<std::string, 8> DirectoryNames;
83
84   /// SourceFileIdMap - Source file name to source file id map.
85   ///
86   StringMap<unsigned> SourceFileIdMap;
87
88   /// SourceFileNames - A list of source file names.
89   SmallVector<std::string, 8> SourceFileNames;
90
91   /// SourceIdMap - Source id map, i.e. pair of directory id and source file
92   /// id mapped to a unique id.
93   DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
94
95   /// SourceIds - Reverse map from source id to directory id + file id pair.
96   ///
97   SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
98
99   /// Lines - List of source line correspondence.
100   std::vector<SrcLineInfo> Lines;
101
102   /// DIEBlocks - A list of all the DIEBlocks in use.
103   std::vector<DIEBlock *> DIEBlocks;
104
105   // DIEValueAllocator - All DIEValues are allocated through this allocator.
106   BumpPtrAllocator DIEValueAllocator;
107
108   /// StringPool - A String->Symbol mapping of strings used by indirect
109   /// references.
110   StringMap<std::pair<MCSymbol*, unsigned> > StringPool;
111   unsigned NextStringPoolNumber;
112   
113   MCSymbol *getStringPoolEntry(StringRef Str);
114
115   /// SectionMap - Provides a unique id per text section.
116   ///
117   UniqueVector<const MCSection*> SectionMap;
118
119   /// SectionSourceLines - Tracks line numbers per text section.
120   ///
121   std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
122
123   /// didInitial - Flag to indicate if initial emission has been done.
124   ///
125   bool didInitial;
126
127   /// shouldEmit - Flag to indicate if debug information should be emitted.
128   ///
129   bool shouldEmit;
130
131   // CurrentFnDbgScope - Top level scope for the current function.
132   //
133   DbgScope *CurrentFnDbgScope;
134   
135   /// DbgScopeMap - Tracks the scopes in the current function.  Owns the
136   /// contained DbgScope*s.
137   ///
138   DenseMap<MDNode *, DbgScope *> DbgScopeMap;
139
140   /// ConcreteScopes - Tracks the concrete scopees in the current function.
141   /// These scopes are also included in DbgScopeMap.
142   DenseMap<MDNode *, DbgScope *> ConcreteScopes;
143
144   /// AbstractScopes - Tracks the abstract scopes a module. These scopes are
145   /// not included DbgScopeMap.  AbstractScopes owns its DbgScope*s.
146   DenseMap<MDNode *, DbgScope *> AbstractScopes;
147
148   /// AbstractScopesList - Tracks abstract scopes constructed while processing
149   /// a function. This list is cleared during endFunction().
150   SmallVector<DbgScope *, 4>AbstractScopesList;
151
152   /// AbstractVariables - Collection on abstract variables.  Owned by the
153   /// DbgScopes in AbstractScopes.
154   DenseMap<MDNode *, DbgVariable *> AbstractVariables;
155
156   /// DbgValueStartMap - Tracks starting scope of variable DIEs.
157   /// If the scope of an object begins sometime after the low pc value for the 
158   /// scope most closely enclosing the object, the object entry may have a 
159   /// DW_AT_start_scope attribute.
160   DenseMap<const MachineInstr *, DbgVariable *> DbgValueStartMap;
161
162   /// InliendSubprogramDIEs - Collection of subprgram DIEs that are marked
163   /// (at the end of the module) as DW_AT_inline.
164   SmallPtrSet<DIE *, 4> InlinedSubprogramDIEs;
165
166   DenseMap<DIE *, MDNode *> ContainingTypeMap;
167
168   /// AbstractSubprogramDIEs - Collection of abstruct subprogram DIEs.
169   SmallPtrSet<DIE *, 4> AbstractSubprogramDIEs;
170
171   /// TopLevelDIEs - Collection of top level DIEs. 
172   SmallPtrSet<DIE *, 4> TopLevelDIEs;
173   SmallVector<DIE *, 4> TopLevelDIEsVector;
174
175   typedef SmallVector<DbgScope *, 2> ScopeVector;
176   typedef DenseMap<const MachineInstr *, ScopeVector>
177     InsnToDbgScopeMapTy;
178
179   /// DbgScopeBeginMap - Maps instruction with a list of DbgScopes it starts.
180   InsnToDbgScopeMapTy DbgScopeBeginMap;
181
182   /// DbgScopeEndMap - Maps instruction with a list DbgScopes it ends.
183   InsnToDbgScopeMapTy DbgScopeEndMap;
184
185   /// InlineInfo - Keep track of inlined functions and their location.  This
186   /// information is used to populate debug_inlined section.
187   typedef std::pair<MCSymbol*, DIE *> InlineInfoLabels;
188   DenseMap<MDNode*, SmallVector<InlineInfoLabels, 4> > InlineInfo;
189   SmallVector<MDNode *, 4> InlinedSPNodes;
190
191   /// CompileUnitOffsets - A vector of the offsets of the compile units. This is
192   /// used when calculating the "origin" of a concrete instance of an inlined
193   /// function.
194   DenseMap<CompileUnit *, unsigned> CompileUnitOffsets;
195
196   /// Previous instruction's location information. This is used to determine
197   /// label location to indicate scope boundries in dwarf debug info.
198   mutable const MDNode *PrevDILoc;
199
200   /// DebugTimer - Timer for the Dwarf debug writer.
201   Timer *DebugTimer;
202   
203   struct FunctionDebugFrameInfo {
204     unsigned Number;
205     std::vector<MachineMove> Moves;
206
207     FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M)
208       : Number(Num), Moves(M) {}
209   };
210
211   std::vector<FunctionDebugFrameInfo> DebugFrames;
212
213   /// getSourceDirectoryAndFileIds - Return the directory and file ids that
214   /// maps to the source id. Source id starts at 1.
215   std::pair<unsigned, unsigned>
216   getSourceDirectoryAndFileIds(unsigned SId) const {
217     return SourceIds[SId-1];
218   }
219
220   /// getNumSourceDirectories - Return the number of source directories in the
221   /// debug info.
222   unsigned getNumSourceDirectories() const {
223     return DirectoryNames.size();
224   }
225
226   /// getSourceDirectoryName - Return the name of the directory corresponding
227   /// to the id.
228   const std::string &getSourceDirectoryName(unsigned Id) const {
229     return DirectoryNames[Id - 1];
230   }
231
232   /// getSourceFileName - Return the name of the source file corresponding
233   /// to the id.
234   const std::string &getSourceFileName(unsigned Id) const {
235     return SourceFileNames[Id - 1];
236   }
237
238   /// getNumSourceIds - Return the number of unique source ids.
239   unsigned getNumSourceIds() const {
240     return SourceIds.size();
241   }
242
243   /// assignAbbrevNumber - Define a unique number for the abbreviation.
244   ///
245   void assignAbbrevNumber(DIEAbbrev &Abbrev);
246
247   /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
248   /// information entry.
249   DIEEntry *createDIEEntry(DIE *Entry);
250
251   /// addUInt - Add an unsigned integer attribute data and value.
252   ///
253   void addUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer);
254
255   /// addSInt - Add an signed integer attribute data and value.
256   ///
257   void addSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer);
258
259   /// addString - Add a string attribute data and value.
260   ///
261   void addString(DIE *Die, unsigned Attribute, unsigned Form,
262                  const StringRef Str);
263
264   /// addLabel - Add a Dwarf label attribute data and value.
265   ///
266   void addLabel(DIE *Die, unsigned Attribute, unsigned Form,
267                 const MCSymbol *Label);
268
269   /// addDelta - Add a label delta attribute data and value.
270   ///
271   void addDelta(DIE *Die, unsigned Attribute, unsigned Form,
272                 const MCSymbol *Hi, const MCSymbol *Lo);
273
274   /// addDIEEntry - Add a DIE attribute data and value.
275   ///
276   void addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
277     Die->addValue(Attribute, Form, createDIEEntry(Entry));
278   }
279
280   /// addBlock - Add block data.
281   ///
282   void addBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block);
283
284   /// addSourceLine - Add location information to specified debug information
285   /// entry.
286   void addSourceLine(DIE *Die, const DIVariable *V);
287   void addSourceLine(DIE *Die, const DIGlobal *G);
288   void addSourceLine(DIE *Die, const DISubprogram *SP);
289   void addSourceLine(DIE *Die, const DIType *Ty);
290   void addSourceLine(DIE *Die, const DINameSpace *NS);
291
292   /// addAddress - Add an address attribute to a die based on the location
293   /// provided.
294   void addAddress(DIE *Die, unsigned Attribute,
295                   const MachineLocation &Location);
296
297   /// addComplexAddress - Start with the address based on the location provided,
298   /// and generate the DWARF information necessary to find the actual variable
299   /// (navigating the extra location information encoded in the type) based on
300   /// the starting location.  Add the DWARF information to the die.
301   ///
302   void addComplexAddress(DbgVariable *&DV, DIE *Die, unsigned Attribute,
303                          const MachineLocation &Location);
304
305   // FIXME: Should be reformulated in terms of addComplexAddress.
306   /// addBlockByrefAddress - Start with the address based on the location
307   /// provided, and generate the DWARF information necessary to find the
308   /// actual Block variable (navigating the Block struct) based on the
309   /// starting location.  Add the DWARF information to the die.  Obsolete,
310   /// please use addComplexAddress instead.
311   ///
312   void addBlockByrefAddress(DbgVariable *&DV, DIE *Die, unsigned Attribute,
313                             const MachineLocation &Location);
314
315   /// addToContextOwner - Add Die into the list of its context owner's children.
316   void addToContextOwner(DIE *Die, DIDescriptor Context);
317
318   /// addType - Add a new type attribute to the specified entity.
319   void addType(DIE *Entity, DIType Ty);
320
321  
322   /// getOrCreateNameSpace - Create a DIE for DINameSpace.
323   DIE *getOrCreateNameSpace(DINameSpace NS);
324
325   /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
326   /// given DIType.
327   DIE *getOrCreateTypeDIE(DIType Ty);
328
329   void addPubTypes(DISubprogram SP);
330
331   /// constructTypeDIE - Construct basic type die from DIBasicType.
332   void constructTypeDIE(DIE &Buffer,
333                         DIBasicType BTy);
334
335   /// constructTypeDIE - Construct derived type die from DIDerivedType.
336   void constructTypeDIE(DIE &Buffer,
337                         DIDerivedType DTy);
338
339   /// constructTypeDIE - Construct type DIE from DICompositeType.
340   void constructTypeDIE(DIE &Buffer,
341                         DICompositeType CTy);
342
343   /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
344   void constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy);
345
346   /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
347   void constructArrayTypeDIE(DIE &Buffer, 
348                              DICompositeType *CTy);
349
350   /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
351   DIE *constructEnumTypeDIE(DIEnumerator ETy);
352
353   /// createGlobalVariableDIE - Create new DIE using GV.
354   DIE *createGlobalVariableDIE(const DIGlobalVariable &GV);
355
356   /// createMemberDIE - Create new member DIE.
357   DIE *createMemberDIE(const DIDerivedType &DT);
358
359   /// createSubprogramDIE - Create new DIE using SP.
360   DIE *createSubprogramDIE(const DISubprogram &SP, bool MakeDecl = false);
361
362   /// getUpdatedDbgScope - Find or create DbgScope assicated with 
363   /// the instruction. Initialize scope and update scope hierarchy.
364   DbgScope *getUpdatedDbgScope(MDNode *N, const MachineInstr *MI, MDNode *InlinedAt);
365
366   /// createDbgScope - Create DbgScope for the scope.
367   void createDbgScope(MDNode *Scope, MDNode *InlinedAt);
368
369   DbgScope *getOrCreateAbstractScope(MDNode *N);
370
371   /// findAbstractVariable - Find abstract variable associated with Var.
372   DbgVariable *findAbstractVariable(DIVariable &Var, unsigned FrameIdx, 
373                                     DILocation &Loc);
374   DbgVariable *findAbstractVariable(DIVariable &Var, const MachineInstr *MI,
375                                     DILocation &Loc);
376
377   /// updateSubprogramScopeDIE - Find DIE for the given subprogram and 
378   /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
379   /// If there are global variables in this scope then create and insert
380   /// DIEs for these variables.
381   DIE *updateSubprogramScopeDIE(MDNode *SPNode);
382
383   /// constructLexicalScope - Construct new DW_TAG_lexical_block 
384   /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
385   DIE *constructLexicalScopeDIE(DbgScope *Scope);
386
387   /// constructInlinedScopeDIE - This scope represents inlined body of
388   /// a function. Construct DIE to represent this concrete inlined copy
389   /// of the function.
390   DIE *constructInlinedScopeDIE(DbgScope *Scope);
391
392   /// constructVariableDIE - Construct a DIE for the given DbgVariable.
393   DIE *constructVariableDIE(DbgVariable *DV, DbgScope *S);
394
395   /// constructScopeDIE - Construct a DIE for this scope.
396   DIE *constructScopeDIE(DbgScope *Scope);
397
398   /// emitInitial - Emit initial Dwarf declarations.  This is necessary for cc
399   /// tools to recognize the object file contains Dwarf information.
400   void emitInitial();
401
402   /// emitDIE - Recusively Emits a debug information entry.
403   ///
404   void emitDIE(DIE *Die);
405
406   /// computeSizeAndOffset - Compute the size and offset of a DIE.
407   ///
408   unsigned computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last);
409
410   /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
411   ///
412   void computeSizeAndOffsets();
413
414   /// EmitDebugInfo - Emit the debug info section.
415   ///
416   void emitDebugInfo();
417
418   /// emitAbbreviations - Emit the abbreviation section.
419   ///
420   void emitAbbreviations() const;
421
422   /// emitEndOfLineMatrix - Emit the last address of the section and the end of
423   /// the line matrix.
424   ///
425   void emitEndOfLineMatrix(unsigned SectionEnd);
426
427   /// emitDebugLines - Emit source line information.
428   ///
429   void emitDebugLines();
430
431   /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
432   ///
433   void emitCommonDebugFrame();
434
435   /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
436   /// section.
437   void emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo);
438
439   /// emitDebugPubNames - Emit visible names into a debug pubnames section.
440   ///
441   void emitDebugPubNames();
442
443   /// emitDebugPubTypes - Emit visible types into a debug pubtypes section.
444   ///
445   void emitDebugPubTypes();
446
447   /// emitDebugStr - Emit visible names into a debug str section.
448   ///
449   void emitDebugStr();
450
451   /// emitDebugLoc - Emit visible names into a debug loc section.
452   ///
453   void emitDebugLoc();
454
455   /// EmitDebugARanges - Emit visible names into a debug aranges section.
456   ///
457   void EmitDebugARanges();
458
459   /// emitDebugRanges - Emit visible names into a debug ranges section.
460   ///
461   void emitDebugRanges();
462
463   /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
464   ///
465   void emitDebugMacInfo();
466
467   /// emitDebugInlineInfo - Emit inline info using following format.
468   /// Section Header:
469   /// 1. length of section
470   /// 2. Dwarf version number
471   /// 3. address size.
472   ///
473   /// Entries (one "entry" for each function that was inlined):
474   ///
475   /// 1. offset into __debug_str section for MIPS linkage name, if exists; 
476   ///   otherwise offset into __debug_str for regular function name.
477   /// 2. offset into __debug_str section for regular function name.
478   /// 3. an unsigned LEB128 number indicating the number of distinct inlining 
479   /// instances for the function.
480   /// 
481   /// The rest of the entry consists of a {die_offset, low_pc}  pair for each 
482   /// inlined instance; the die_offset points to the inlined_subroutine die in
483   /// the __debug_info section, and the low_pc is the starting address  for the
484   ///  inlining instance.
485   void emitDebugInlineInfo();
486
487   /// GetOrCreateSourceID - Look up the source id with the given directory and
488   /// source file names. If none currently exists, create a new id and insert it
489   /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
490   /// as well.
491   unsigned GetOrCreateSourceID(StringRef DirName, StringRef FileName);
492
493   void constructCompileUnit(MDNode *N);
494
495   void constructGlobalVariableDIE(MDNode *N);
496
497   void constructSubprogramDIE(MDNode *N);
498
499   // FIXME: This should go away in favor of complex addresses.
500   /// Find the type the programmer originally declared the variable to be
501   /// and return that type.  Obsolete, use GetComplexAddrType instead.
502   ///
503   DIType getBlockByrefType(DIType Ty, std::string Name);
504
505 public:
506   //===--------------------------------------------------------------------===//
507   // Main entry points.
508   //
509   DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T);
510   virtual ~DwarfDebug();
511
512   /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
513   /// be emitted.
514   bool ShouldEmitDwarfDebug() const { return shouldEmit; }
515
516   /// beginModule - Emit all Dwarf sections that should come prior to the
517   /// content.
518   void beginModule(Module *M, MachineModuleInfo *MMI);
519
520   /// endModule - Emit all Dwarf sections that should come after the content.
521   ///
522   void endModule();
523
524   /// beginFunction - Gather pre-function debug information.  Assumes being
525   /// emitted immediately after the function entry point.
526   void beginFunction(const MachineFunction *MF);
527
528   /// endFunction - Gather and emit post-function debug information.
529   ///
530   void endFunction(const MachineFunction *MF);
531
532   /// recordSourceLine - Register a source line with debug info. Returns the
533   /// unique label that was emitted and which provides correspondence to
534   /// the source line list.
535   MCSymbol *recordSourceLine(unsigned Line, unsigned Col, MDNode *Scope);
536
537   /// getSourceLineCount - Return the number of source lines in the debug
538   /// info.
539   unsigned getSourceLineCount() const {
540     return Lines.size();
541   }
542                             
543   /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
544   /// timed. Look up the source id with the given directory and source file
545   /// names. If none currently exists, create a new id and insert it in the
546   /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
547   /// well.
548   unsigned getOrCreateSourceID(const std::string &DirName,
549                                const std::string &FileName);
550
551   /// extractScopeInformation - Scan machine instructions in this function
552   /// and collect DbgScopes. Return true, if atleast one scope was found.
553   bool extractScopeInformation();
554
555   /// collectVariableInfo - Populate DbgScope entries with variables' info.
556   void collectVariableInfo();
557
558   /// beginScope - Process beginning of a scope.
559   void beginScope(const MachineInstr *MI);
560
561   /// endScope - Prcess end of a scope.
562   void endScope(const MachineInstr *MI);
563 };
564 } // End of namespace llvm
565
566 #endif