DwarfDebug.h revision 237a389a4739043ce735c30b9b1baed85ef4dc4b
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
31namespace llvm {
32
33class CompileUnit;
34class DbgConcreteScope;
35class DbgScope;
36class DbgVariable;
37class MachineFrameInfo;
38class MachineModuleInfo;
39class MCAsmInfo;
40class Timer;
41
42//===----------------------------------------------------------------------===//
43/// SrcLineInfo - This class is used to record source line correspondence.
44///
45class 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.
50public:
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
61class 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  /// isFunctionContext - True if given Context is nested within a function.
319  bool isFunctionContext(DIE *context);
320
321  /// addType - Add a new type attribute to the specified entity.
322  void addType(DIE *Entity, DIType Ty);
323
324
325  /// getOrCreateNameSpace - Create a DIE for DINameSpace.
326  DIE *getOrCreateNameSpace(DINameSpace NS);
327
328  /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
329  /// given DIType.
330  DIE *getOrCreateTypeDIE(DIType Ty);
331
332  void addPubTypes(DISubprogram SP);
333
334  /// constructTypeDIE - Construct basic type die from DIBasicType.
335  void constructTypeDIE(DIE &Buffer,
336                        DIBasicType BTy);
337
338  /// constructTypeDIE - Construct derived type die from DIDerivedType.
339  void constructTypeDIE(DIE &Buffer,
340                        DIDerivedType DTy);
341
342  /// constructTypeDIE - Construct type DIE from DICompositeType.
343  void constructTypeDIE(DIE &Buffer,
344                        DICompositeType CTy);
345
346  /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
347  void constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy);
348
349  /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
350  void constructArrayTypeDIE(DIE &Buffer,
351                             DICompositeType *CTy);
352
353  /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
354  DIE *constructEnumTypeDIE(DIEnumerator ETy);
355
356  /// createGlobalVariableDIE - Create new DIE using GV.
357  DIE *createGlobalVariableDIE(const DIGlobalVariable &GV);
358
359  /// createMemberDIE - Create new member DIE.
360  DIE *createMemberDIE(const DIDerivedType &DT);
361
362  /// createSubprogramDIE - Create new DIE using SP.
363  DIE *createSubprogramDIE(const DISubprogram &SP, bool MakeDecl = false);
364
365  /// getUpdatedDbgScope - Find or create DbgScope assicated with
366  /// the instruction. Initialize scope and update scope hierarchy.
367  DbgScope *getUpdatedDbgScope(MDNode *N, const MachineInstr *MI, MDNode *InlinedAt);
368
369  /// createDbgScope - Create DbgScope for the scope.
370  void createDbgScope(MDNode *Scope, MDNode *InlinedAt);
371
372  DbgScope *getOrCreateAbstractScope(MDNode *N);
373
374  /// findAbstractVariable - Find abstract variable associated with Var.
375  DbgVariable *findAbstractVariable(DIVariable &Var, unsigned FrameIdx,
376                                    DILocation &Loc);
377  DbgVariable *findAbstractVariable(DIVariable &Var, const MachineInstr *MI,
378                                    DILocation &Loc);
379
380  /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
381  /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
382  /// If there are global variables in this scope then create and insert
383  /// DIEs for these variables.
384  DIE *updateSubprogramScopeDIE(MDNode *SPNode);
385
386  /// constructLexicalScope - Construct new DW_TAG_lexical_block
387  /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
388  DIE *constructLexicalScopeDIE(DbgScope *Scope);
389
390  /// constructInlinedScopeDIE - This scope represents inlined body of
391  /// a function. Construct DIE to represent this concrete inlined copy
392  /// of the function.
393  DIE *constructInlinedScopeDIE(DbgScope *Scope);
394
395  /// constructVariableDIE - Construct a DIE for the given DbgVariable.
396  DIE *constructVariableDIE(DbgVariable *DV, DbgScope *S);
397
398  /// constructScopeDIE - Construct a DIE for this scope.
399  DIE *constructScopeDIE(DbgScope *Scope);
400
401  /// emitInitial - Emit initial Dwarf declarations.  This is necessary for cc
402  /// tools to recognize the object file contains Dwarf information.
403  void emitInitial();
404
405  /// emitDIE - Recusively Emits a debug information entry.
406  ///
407  void emitDIE(DIE *Die);
408
409  /// computeSizeAndOffset - Compute the size and offset of a DIE.
410  ///
411  unsigned computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last);
412
413  /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
414  ///
415  void computeSizeAndOffsets();
416
417  /// EmitDebugInfo - Emit the debug info section.
418  ///
419  void emitDebugInfo();
420
421  /// emitAbbreviations - Emit the abbreviation section.
422  ///
423  void emitAbbreviations() const;
424
425  /// emitEndOfLineMatrix - Emit the last address of the section and the end of
426  /// the line matrix.
427  ///
428  void emitEndOfLineMatrix(unsigned SectionEnd);
429
430  /// emitDebugLines - Emit source line information.
431  ///
432  void emitDebugLines();
433
434  /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
435  ///
436  void emitCommonDebugFrame();
437
438  /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
439  /// section.
440  void emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo);
441
442  /// emitDebugPubNames - Emit visible names into a debug pubnames section.
443  ///
444  void emitDebugPubNames();
445
446  /// emitDebugPubTypes - Emit visible types into a debug pubtypes section.
447  ///
448  void emitDebugPubTypes();
449
450  /// emitDebugStr - Emit visible names into a debug str section.
451  ///
452  void emitDebugStr();
453
454  /// emitDebugLoc - Emit visible names into a debug loc section.
455  ///
456  void emitDebugLoc();
457
458  /// EmitDebugARanges - Emit visible names into a debug aranges section.
459  ///
460  void EmitDebugARanges();
461
462  /// emitDebugRanges - Emit visible names into a debug ranges section.
463  ///
464  void emitDebugRanges();
465
466  /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
467  ///
468  void emitDebugMacInfo();
469
470  /// emitDebugInlineInfo - Emit inline info using following format.
471  /// Section Header:
472  /// 1. length of section
473  /// 2. Dwarf version number
474  /// 3. address size.
475  ///
476  /// Entries (one "entry" for each function that was inlined):
477  ///
478  /// 1. offset into __debug_str section for MIPS linkage name, if exists;
479  ///   otherwise offset into __debug_str for regular function name.
480  /// 2. offset into __debug_str section for regular function name.
481  /// 3. an unsigned LEB128 number indicating the number of distinct inlining
482  /// instances for the function.
483  ///
484  /// The rest of the entry consists of a {die_offset, low_pc}  pair for each
485  /// inlined instance; the die_offset points to the inlined_subroutine die in
486  /// the __debug_info section, and the low_pc is the starting address  for the
487  ///  inlining instance.
488  void emitDebugInlineInfo();
489
490  /// GetOrCreateSourceID - Look up the source id with the given directory and
491  /// source file names. If none currently exists, create a new id and insert it
492  /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
493  /// as well.
494  unsigned GetOrCreateSourceID(StringRef DirName, StringRef FileName);
495
496  void constructCompileUnit(MDNode *N);
497
498  void constructGlobalVariableDIE(MDNode *N);
499
500  void constructSubprogramDIE(MDNode *N);
501
502  // FIXME: This should go away in favor of complex addresses.
503  /// Find the type the programmer originally declared the variable to be
504  /// and return that type.  Obsolete, use GetComplexAddrType instead.
505  ///
506  DIType getBlockByrefType(DIType Ty, std::string Name);
507
508public:
509  //===--------------------------------------------------------------------===//
510  // Main entry points.
511  //
512  DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T);
513  virtual ~DwarfDebug();
514
515  /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
516  /// be emitted.
517  bool ShouldEmitDwarfDebug() const { return shouldEmit; }
518
519  /// beginModule - Emit all Dwarf sections that should come prior to the
520  /// content.
521  void beginModule(Module *M, MachineModuleInfo *MMI);
522
523  /// endModule - Emit all Dwarf sections that should come after the content.
524  ///
525  void endModule();
526
527  /// beginFunction - Gather pre-function debug information.  Assumes being
528  /// emitted immediately after the function entry point.
529  void beginFunction(const MachineFunction *MF);
530
531  /// endFunction - Gather and emit post-function debug information.
532  ///
533  void endFunction(const MachineFunction *MF);
534
535  /// recordSourceLine - Register a source line with debug info. Returns the
536  /// unique label that was emitted and which provides correspondence to
537  /// the source line list.
538  MCSymbol *recordSourceLine(unsigned Line, unsigned Col, MDNode *Scope);
539
540  /// getSourceLineCount - Return the number of source lines in the debug
541  /// info.
542  unsigned getSourceLineCount() const {
543    return Lines.size();
544  }
545
546  /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
547  /// timed. Look up the source id with the given directory and source file
548  /// names. If none currently exists, create a new id and insert it in the
549  /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
550  /// well.
551  unsigned getOrCreateSourceID(const std::string &DirName,
552                               const std::string &FileName);
553
554  /// extractScopeInformation - Scan machine instructions in this function
555  /// and collect DbgScopes. Return true, if atleast one scope was found.
556  bool extractScopeInformation();
557
558  /// collectVariableInfo - Populate DbgScope entries with variables' info.
559  void collectVariableInfo();
560
561  /// beginScope - Process beginning of a scope.
562  void beginScope(const MachineInstr *MI);
563
564  /// endScope - Prcess end of a scope.
565  void endScope(const MachineInstr *MI);
566};
567} // End of namespace llvm
568
569#endif
570