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