DwarfDebug.cpp revision 9cdb4109d5fbbff3b881d3288a6ec518abc7712e
1//===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
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#define DEBUG_TYPE "dwarfdebug"
15#include "DwarfDebug.h"
16#include "DIE.h"
17#include "llvm/Constants.h"
18#include "llvm/Module.h"
19#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/MachineModuleInfo.h"
21#include "llvm/MC/MCAsmInfo.h"
22#include "llvm/MC/MCSection.h"
23#include "llvm/MC/MCStreamer.h"
24#include "llvm/MC/MCSymbol.h"
25#include "llvm/Target/Mangler.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetFrameInfo.h"
28#include "llvm/Target/TargetLoweringObjectFile.h"
29#include "llvm/Target/TargetMachine.h"
30#include "llvm/Target/TargetRegisterInfo.h"
31#include "llvm/Target/TargetOptions.h"
32#include "llvm/Analysis/DebugInfo.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/StringExtras.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/ValueHandle.h"
39#include "llvm/Support/FormattedStream.h"
40#include "llvm/Support/Timer.h"
41#include "llvm/System/Path.h"
42using namespace llvm;
43
44static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
45     cl::desc("Print DbgScope information for each machine instruction"));
46
47namespace {
48  const char *DWARFGroupName = "DWARF Emission";
49  const char *DbgTimerName = "DWARF Debug Writer";
50} // end anonymous namespace
51
52//===----------------------------------------------------------------------===//
53
54/// Configuration values for initial hash set sizes (log2).
55///
56static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
57
58namespace llvm {
59
60//===----------------------------------------------------------------------===//
61/// CompileUnit - This dwarf writer support class manages information associate
62/// with a source file.
63class CompileUnit {
64  /// ID - File identifier for source.
65  ///
66  unsigned ID;
67
68  /// Die - Compile unit debug information entry.
69  ///
70  const OwningPtr<DIE> CUDie;
71
72  /// IndexTyDie - An anonymous type for index type.  Owned by CUDie.
73  DIE *IndexTyDie;
74
75  /// GVToDieMap - Tracks the mapping of unit level debug informaton
76  /// variables to debug information entries.
77  /// FIXME : Rename GVToDieMap -> NodeToDieMap
78  DenseMap<MDNode *, DIE *> GVToDieMap;
79
80  /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
81  /// descriptors to debug information entries using a DIEEntry proxy.
82  /// FIXME : Rename
83  DenseMap<MDNode *, DIEEntry *> GVToDIEEntryMap;
84
85  /// Globals - A map of globally visible named entities for this unit.
86  ///
87  StringMap<DIE*> Globals;
88
89  /// GlobalTypes - A map of globally visible types for this unit.
90  ///
91  StringMap<DIE*> GlobalTypes;
92
93public:
94  CompileUnit(unsigned I, DIE *D)
95    : ID(I), CUDie(D), IndexTyDie(0) {}
96
97  // Accessors.
98  unsigned getID()                  const { return ID; }
99  DIE* getCUDie()                   const { return CUDie.get(); }
100  const StringMap<DIE*> &getGlobals()     const { return Globals; }
101  const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
102
103  /// hasContent - Return true if this compile unit has something to write out.
104  ///
105  bool hasContent() const { return !CUDie->getChildren().empty(); }
106
107  /// addGlobal - Add a new global entity to the compile unit.
108  ///
109  void addGlobal(StringRef Name, DIE *Die) { Globals[Name] = Die; }
110
111  /// addGlobalType - Add a new global type to the compile unit.
112  ///
113  void addGlobalType(StringRef Name, DIE *Die) {
114    GlobalTypes[Name] = Die;
115  }
116
117  /// getDIE - Returns the debug information entry map slot for the
118  /// specified debug variable.
119  DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); }
120
121  /// insertDIE - Insert DIE into the map.
122  void insertDIE(MDNode *N, DIE *D) {
123    GVToDieMap.insert(std::make_pair(N, D));
124  }
125
126  /// getDIEEntry - Returns the debug information entry for the speciefied
127  /// debug variable.
128  DIEEntry *getDIEEntry(MDNode *N) {
129    DenseMap<MDNode *, DIEEntry *>::iterator I = GVToDIEEntryMap.find(N);
130    if (I == GVToDIEEntryMap.end())
131      return NULL;
132    return I->second;
133  }
134
135  /// insertDIEEntry - Insert debug information entry into the map.
136  void insertDIEEntry(MDNode *N, DIEEntry *E) {
137    GVToDIEEntryMap.insert(std::make_pair(N, E));
138  }
139
140  /// addDie - Adds or interns the DIE to the compile unit.
141  ///
142  void addDie(DIE *Buffer) {
143    this->CUDie->addChild(Buffer);
144  }
145
146  // getIndexTyDie - Get an anonymous type for index type.
147  DIE *getIndexTyDie() {
148    return IndexTyDie;
149  }
150
151  // setIndexTyDie - Set D as anonymous type for index which can be reused
152  // later.
153  void setIndexTyDie(DIE *D) {
154    IndexTyDie = D;
155  }
156
157};
158
159//===----------------------------------------------------------------------===//
160/// DbgVariable - This class is used to track local variable information.
161///
162class DbgVariable {
163  DIVariable Var;                    // Variable Descriptor.
164  unsigned FrameIndex;               // Variable frame index.
165  const MachineInstr *DbgValueMInsn; // DBG_VALUE
166  // DbgValueLabel - DBG_VALUE is effective from this label.
167  MCSymbol *DbgValueLabel;
168  DbgVariable *const AbstractVar;    // Abstract variable for this variable.
169  DIE *TheDIE;
170public:
171  // AbsVar may be NULL.
172  DbgVariable(DIVariable V, unsigned I, DbgVariable *AbsVar)
173    : Var(V), FrameIndex(I), DbgValueMInsn(0),
174      DbgValueLabel(0), AbstractVar(AbsVar), TheDIE(0) {}
175  DbgVariable(DIVariable V, const MachineInstr *MI, DbgVariable *AbsVar)
176    : Var(V), FrameIndex(0), DbgValueMInsn(MI), DbgValueLabel(0),
177      AbstractVar(AbsVar), TheDIE(0)
178    {}
179
180  // Accessors.
181  DIVariable getVariable()           const { return Var; }
182  unsigned getFrameIndex()           const { return FrameIndex; }
183  const MachineInstr *getDbgValue()  const { return DbgValueMInsn; }
184  MCSymbol *getDbgValueLabel()       const { return DbgValueLabel; }
185  void setDbgValueLabel(MCSymbol *L)       { DbgValueLabel = L; }
186  DbgVariable *getAbstractVariable() const { return AbstractVar; }
187  void setDIE(DIE *D)                      { TheDIE = D; }
188  DIE *getDIE()                      const { return TheDIE; }
189};
190
191//===----------------------------------------------------------------------===//
192/// DbgRange - This is used to track range of instructions with identical
193/// debug info scope.
194///
195typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
196
197//===----------------------------------------------------------------------===//
198/// DbgScope - This class is used to track scope information.
199///
200class DbgScope {
201  DbgScope *Parent;                   // Parent to this scope.
202  DIDescriptor Desc;                  // Debug info descriptor for scope.
203  // Location at which this scope is inlined.
204  AssertingVH<MDNode> InlinedAtLocation;
205  bool AbstractScope;                 // Abstract Scope
206  const MachineInstr *LastInsn;       // Last instruction of this scope.
207  const MachineInstr *FirstInsn;      // First instruction of this scope.
208  unsigned DFSIn, DFSOut;
209  // Scopes defined in scope.  Contents not owned.
210  SmallVector<DbgScope *, 4> Scopes;
211  // Variables declared in scope.  Contents owned.
212  SmallVector<DbgVariable *, 8> Variables;
213  SmallVector<DbgRange, 4> Ranges;
214  // Private state for dump()
215  mutable unsigned IndentLevel;
216public:
217  DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
218    : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
219      LastInsn(0), FirstInsn(0),
220      DFSIn(0), DFSOut(0), IndentLevel(0) {}
221  virtual ~DbgScope();
222
223  // Accessors.
224  DbgScope *getParent()          const { return Parent; }
225  void setParent(DbgScope *P)          { Parent = P; }
226  DIDescriptor getDesc()         const { return Desc; }
227  MDNode *getInlinedAt()         const { return InlinedAtLocation; }
228  MDNode *getScopeNode()         const { return Desc.getNode(); }
229  const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
230  const SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
231  const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
232
233  /// openInsnRange - This scope covers instruction range starting from MI.
234  void openInsnRange(const MachineInstr *MI) {
235    if (!FirstInsn)
236      FirstInsn = MI;
237
238    if (Parent)
239      Parent->openInsnRange(MI);
240  }
241
242  /// extendInsnRange - Extend the current instruction range covered by
243  /// this scope.
244  void extendInsnRange(const MachineInstr *MI) {
245    assert (FirstInsn && "MI Range is not open!");
246    LastInsn = MI;
247    if (Parent)
248      Parent->extendInsnRange(MI);
249  }
250
251  /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
252  /// until now. This is used when a new scope is encountered while walking
253  /// machine instructions.
254  void closeInsnRange(DbgScope *NewScope = NULL) {
255    assert (LastInsn && "Last insn missing!");
256    Ranges.push_back(DbgRange(FirstInsn, LastInsn));
257    FirstInsn = NULL;
258    LastInsn = NULL;
259    // If Parent dominates NewScope then do not close Parent's instruction
260    // range.
261    if (Parent && (!NewScope || !Parent->dominates(NewScope)))
262      Parent->closeInsnRange(NewScope);
263  }
264
265  void setAbstractScope() { AbstractScope = true; }
266  bool isAbstractScope() const { return AbstractScope; }
267
268  // Depth First Search support to walk and mainpluate DbgScope hierarchy.
269  unsigned getDFSOut() const { return DFSOut; }
270  void setDFSOut(unsigned O) { DFSOut = O; }
271  unsigned getDFSIn() const  { return DFSIn; }
272  void setDFSIn(unsigned I)  { DFSIn = I; }
273  bool dominates(const DbgScope *S) {
274    if (S == this)
275      return true;
276    if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
277      return true;
278    return false;
279  }
280
281  /// addScope - Add a scope to the scope.
282  ///
283  void addScope(DbgScope *S) { Scopes.push_back(S); }
284
285  /// addVariable - Add a variable to the scope.
286  ///
287  void addVariable(DbgVariable *V) { Variables.push_back(V); }
288
289#ifndef NDEBUG
290  void dump() const;
291#endif
292};
293
294} // end llvm namespace
295
296#ifndef NDEBUG
297void DbgScope::dump() const {
298  raw_ostream &err = dbgs();
299  err.indent(IndentLevel);
300  MDNode *N = Desc.getNode();
301  N->dump();
302  if (AbstractScope)
303    err << "Abstract Scope\n";
304
305  IndentLevel += 2;
306  if (!Scopes.empty())
307    err << "Children ...\n";
308  for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
309    if (Scopes[i] != this)
310      Scopes[i]->dump();
311
312  IndentLevel -= 2;
313}
314#endif
315
316DbgScope::~DbgScope() {
317  for (unsigned j = 0, M = Variables.size(); j < M; ++j)
318    delete Variables[j];
319}
320
321DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
322  : Asm(A), MMI(Asm->MMI), ModuleCU(0),
323    AbbreviationsSet(InitAbbreviationsSetSize),
324    CurrentFnDbgScope(0), PrevLabel(NULL) {
325  NextStringPoolNumber = 0;
326
327  DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
328  DwarfStrSectionSym = TextSectionSym = 0;
329  DwarfDebugRangeSectionSym = 0;
330  if (TimePassesIsEnabled) {
331      NamedRegionTimer T(DbgTimerName, DWARFGroupName);
332      beginModule(M);
333  } else {
334      beginModule(M);
335  }
336}
337DwarfDebug::~DwarfDebug() {
338  for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
339    DIEBlocks[j]->~DIEBlock();
340}
341
342MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
343  std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
344  if (Entry.first) return Entry.first;
345
346  Entry.second = NextStringPoolNumber++;
347  return Entry.first = Asm->GetTempSymbol("string", Entry.second);
348}
349
350
351/// assignAbbrevNumber - Define a unique number for the abbreviation.
352///
353void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
354  // Profile the node so that we can make it unique.
355  FoldingSetNodeID ID;
356  Abbrev.Profile(ID);
357
358  // Check the set for priors.
359  DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
360
361  // If it's newly added.
362  if (InSet == &Abbrev) {
363    // Add to abbreviation list.
364    Abbreviations.push_back(&Abbrev);
365
366    // Assign the vector position + 1 as its number.
367    Abbrev.setNumber(Abbreviations.size());
368  } else {
369    // Assign existing abbreviation number.
370    Abbrev.setNumber(InSet->getNumber());
371  }
372}
373
374/// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
375/// information entry.
376DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
377  DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
378  return Value;
379}
380
381/// addUInt - Add an unsigned integer attribute data and value.
382///
383void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
384                         unsigned Form, uint64_t Integer) {
385  if (!Form) Form = DIEInteger::BestForm(false, Integer);
386  DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
387  Die->addValue(Attribute, Form, Value);
388}
389
390/// addSInt - Add an signed integer attribute data and value.
391///
392void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
393                         unsigned Form, int64_t Integer) {
394  if (!Form) Form = DIEInteger::BestForm(true, Integer);
395  DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
396  Die->addValue(Attribute, Form, Value);
397}
398
399/// addString - Add a string attribute data and value. DIEString only
400/// keeps string reference.
401void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
402                           StringRef String) {
403  DIEValue *Value = new (DIEValueAllocator) DIEString(String);
404  Die->addValue(Attribute, Form, Value);
405}
406
407/// addLabel - Add a Dwarf label attribute data and value.
408///
409void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
410                          const MCSymbol *Label) {
411  DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
412  Die->addValue(Attribute, Form, Value);
413}
414
415/// addDelta - Add a label delta attribute data and value.
416///
417void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
418                          const MCSymbol *Hi, const MCSymbol *Lo) {
419  DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
420  Die->addValue(Attribute, Form, Value);
421}
422
423/// addDIEEntry - Add a DIE attribute data and value.
424///
425void DwarfDebug::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
426                             DIE *Entry) {
427  Die->addValue(Attribute, Form, createDIEEntry(Entry));
428}
429
430
431/// addBlock - Add block data.
432///
433void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
434                          DIEBlock *Block) {
435  Block->ComputeSize(Asm);
436  DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
437  Die->addValue(Attribute, Block->BestForm(), Block);
438}
439
440/// addSourceLine - Add location information to specified debug information
441/// entry.
442void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
443  // If there is no compile unit specified, don't add a line #.
444  if (!V->getCompileUnit().Verify())
445    return;
446
447  unsigned Line = V->getLineNumber();
448  unsigned FileID = GetOrCreateSourceID(V->getContext().getDirectory(),
449                                        V->getContext().getFilename());
450  assert(FileID && "Invalid file id");
451  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
452  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
453}
454
455/// addSourceLine - Add location information to specified debug information
456/// entry.
457void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
458  // If there is no compile unit specified, don't add a line #.
459  if (!G->getCompileUnit().Verify())
460    return;
461
462  unsigned Line = G->getLineNumber();
463  unsigned FileID = GetOrCreateSourceID(G->getContext().getDirectory(),
464                                        G->getContext().getFilename());
465  assert(FileID && "Invalid file id");
466  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
467  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
468}
469
470/// addSourceLine - Add location information to specified debug information
471/// entry.
472void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
473  // If there is no compile unit specified, don't add a line #.
474  if (!SP->getCompileUnit().Verify())
475    return;
476  // If the line number is 0, don't add it.
477  if (SP->getLineNumber() == 0)
478    return;
479
480  unsigned Line = SP->getLineNumber();
481  if (!SP->getContext().Verify())
482    return;
483  unsigned FileID = GetOrCreateSourceID(SP->getDirectory(),
484                                        SP->getFilename());
485  assert(FileID && "Invalid file id");
486  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
487  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
488}
489
490/// addSourceLine - Add location information to specified debug information
491/// entry.
492void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
493  // If there is no compile unit specified, don't add a line #.
494  DICompileUnit CU = Ty->getCompileUnit();
495  if (!CU.Verify())
496    return;
497
498  unsigned Line = Ty->getLineNumber();
499  if (!Ty->getContext().Verify())
500    return;
501  unsigned FileID = GetOrCreateSourceID(Ty->getContext().getDirectory(),
502                                        Ty->getContext().getFilename());
503  assert(FileID && "Invalid file id");
504  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
505  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
506}
507
508/// addSourceLine - Add location information to specified debug information
509/// entry.
510void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
511  // If there is no compile unit specified, don't add a line #.
512  if (!NS->getCompileUnit().Verify())
513    return;
514
515  unsigned Line = NS->getLineNumber();
516  StringRef FN = NS->getFilename();
517  StringRef Dir = NS->getDirectory();
518
519  unsigned FileID = GetOrCreateSourceID(Dir, FN);
520  assert(FileID && "Invalid file id");
521  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
522  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
523}
524
525/* Byref variables, in Blocks, are declared by the programmer as
526   "SomeType VarName;", but the compiler creates a
527   __Block_byref_x_VarName struct, and gives the variable VarName
528   either the struct, or a pointer to the struct, as its type.  This
529   is necessary for various behind-the-scenes things the compiler
530   needs to do with by-reference variables in blocks.
531
532   However, as far as the original *programmer* is concerned, the
533   variable should still have type 'SomeType', as originally declared.
534
535   The following function dives into the __Block_byref_x_VarName
536   struct to find the original type of the variable.  This will be
537   passed back to the code generating the type for the Debug
538   Information Entry for the variable 'VarName'.  'VarName' will then
539   have the original type 'SomeType' in its debug information.
540
541   The original type 'SomeType' will be the type of the field named
542   'VarName' inside the __Block_byref_x_VarName struct.
543
544   NOTE: In order for this to not completely fail on the debugger
545   side, the Debug Information Entry for the variable VarName needs to
546   have a DW_AT_location that tells the debugger how to unwind through
547   the pointers and __Block_byref_x_VarName struct to find the actual
548   value of the variable.  The function addBlockByrefType does this.  */
549
550/// Find the type the programmer originally declared the variable to be
551/// and return that type.
552///
553DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
554
555  DIType subType = Ty;
556  unsigned tag = Ty.getTag();
557
558  if (tag == dwarf::DW_TAG_pointer_type) {
559    DIDerivedType DTy = DIDerivedType(Ty.getNode());
560    subType = DTy.getTypeDerivedFrom();
561  }
562
563  DICompositeType blockStruct = DICompositeType(subType.getNode());
564  DIArray Elements = blockStruct.getTypeArray();
565
566  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
567    DIDescriptor Element = Elements.getElement(i);
568    DIDerivedType DT = DIDerivedType(Element.getNode());
569    if (Name == DT.getName())
570      return (DT.getTypeDerivedFrom());
571  }
572
573  return Ty;
574}
575
576/// addComplexAddress - Start with the address based on the location provided,
577/// and generate the DWARF information necessary to find the actual variable
578/// given the extra address information encoded in the DIVariable, starting from
579/// the starting location.  Add the DWARF information to the die.
580///
581void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
582                                   unsigned Attribute,
583                                   const MachineLocation &Location) {
584  const DIVariable &VD = DV->getVariable();
585  DIType Ty = VD.getType();
586
587  // Decode the original location, and use that as the start of the byref
588  // variable's location.
589  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
590  unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
591  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
592
593  if (Location.isReg()) {
594    if (Reg < 32) {
595      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
596    } else {
597      Reg = Reg - dwarf::DW_OP_reg0;
598      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
599      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
600    }
601  } else {
602    if (Reg < 32)
603      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
604    else {
605      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
606      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
607    }
608
609    addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
610  }
611
612  for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
613    uint64_t Element = VD.getAddrElement(i);
614
615    if (Element == DIFactory::OpPlus) {
616      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
617      addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
618    } else if (Element == DIFactory::OpDeref) {
619      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
620    } else llvm_unreachable("unknown DIFactory Opcode");
621  }
622
623  // Now attach the location information to the DIE.
624  addBlock(Die, Attribute, 0, Block);
625}
626
627/* Byref variables, in Blocks, are declared by the programmer as "SomeType
628   VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
629   gives the variable VarName either the struct, or a pointer to the struct, as
630   its type.  This is necessary for various behind-the-scenes things the
631   compiler needs to do with by-reference variables in Blocks.
632
633   However, as far as the original *programmer* is concerned, the variable
634   should still have type 'SomeType', as originally declared.
635
636   The function getBlockByrefType dives into the __Block_byref_x_VarName
637   struct to find the original type of the variable, which is then assigned to
638   the variable's Debug Information Entry as its real type.  So far, so good.
639   However now the debugger will expect the variable VarName to have the type
640   SomeType.  So we need the location attribute for the variable to be an
641   expression that explains to the debugger how to navigate through the
642   pointers and struct to find the actual variable of type SomeType.
643
644   The following function does just that.  We start by getting
645   the "normal" location for the variable. This will be the location
646   of either the struct __Block_byref_x_VarName or the pointer to the
647   struct __Block_byref_x_VarName.
648
649   The struct will look something like:
650
651   struct __Block_byref_x_VarName {
652     ... <various fields>
653     struct __Block_byref_x_VarName *forwarding;
654     ... <various other fields>
655     SomeType VarName;
656     ... <maybe more fields>
657   };
658
659   If we are given the struct directly (as our starting point) we
660   need to tell the debugger to:
661
662   1).  Add the offset of the forwarding field.
663
664   2).  Follow that pointer to get the real __Block_byref_x_VarName
665   struct to use (the real one may have been copied onto the heap).
666
667   3).  Add the offset for the field VarName, to find the actual variable.
668
669   If we started with a pointer to the struct, then we need to
670   dereference that pointer first, before the other steps.
671   Translating this into DWARF ops, we will need to append the following
672   to the current location description for the variable:
673
674   DW_OP_deref                    -- optional, if we start with a pointer
675   DW_OP_plus_uconst <forward_fld_offset>
676   DW_OP_deref
677   DW_OP_plus_uconst <varName_fld_offset>
678
679   That is what this function does.  */
680
681/// addBlockByrefAddress - Start with the address based on the location
682/// provided, and generate the DWARF information necessary to find the
683/// actual Block variable (navigating the Block struct) based on the
684/// starting location.  Add the DWARF information to the die.  For
685/// more information, read large comment just above here.
686///
687void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
688                                      unsigned Attribute,
689                                      const MachineLocation &Location) {
690  const DIVariable &VD = DV->getVariable();
691  DIType Ty = VD.getType();
692  DIType TmpTy = Ty;
693  unsigned Tag = Ty.getTag();
694  bool isPointer = false;
695
696  StringRef varName = VD.getName();
697
698  if (Tag == dwarf::DW_TAG_pointer_type) {
699    DIDerivedType DTy = DIDerivedType(Ty.getNode());
700    TmpTy = DTy.getTypeDerivedFrom();
701    isPointer = true;
702  }
703
704  DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
705
706  // Find the __forwarding field and the variable field in the __Block_byref
707  // struct.
708  DIArray Fields = blockStruct.getTypeArray();
709  DIDescriptor varField = DIDescriptor();
710  DIDescriptor forwardingField = DIDescriptor();
711
712  for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
713    DIDescriptor Element = Fields.getElement(i);
714    DIDerivedType DT = DIDerivedType(Element.getNode());
715    StringRef fieldName = DT.getName();
716    if (fieldName == "__forwarding")
717      forwardingField = Element;
718    else if (fieldName == varName)
719      varField = Element;
720  }
721
722  // Get the offsets for the forwarding field and the variable field.
723  unsigned forwardingFieldOffset =
724    DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
725  unsigned varFieldOffset =
726    DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
727
728  // Decode the original location, and use that as the start of the byref
729  // variable's location.
730  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
731  unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
732  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
733
734  if (Location.isReg()) {
735    if (Reg < 32)
736      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
737    else {
738      Reg = Reg - dwarf::DW_OP_reg0;
739      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
740      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
741    }
742  } else {
743    if (Reg < 32)
744      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
745    else {
746      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
747      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
748    }
749
750    addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
751  }
752
753  // If we started with a pointer to the __Block_byref... struct, then
754  // the first thing we need to do is dereference the pointer (DW_OP_deref).
755  if (isPointer)
756    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
757
758  // Next add the offset for the '__forwarding' field:
759  // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
760  // adding the offset if it's 0.
761  if (forwardingFieldOffset > 0) {
762    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
763    addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
764  }
765
766  // Now dereference the __forwarding field to get to the real __Block_byref
767  // struct:  DW_OP_deref.
768  addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
769
770  // Now that we've got the real __Block_byref... struct, add the offset
771  // for the variable's field to get to the location of the actual variable:
772  // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
773  if (varFieldOffset > 0) {
774    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
775    addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
776  }
777
778  // Now attach the location information to the DIE.
779  addBlock(Die, Attribute, 0, Block);
780}
781
782/// addAddress - Add an address attribute to a die based on the location
783/// provided.
784void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
785                            const MachineLocation &Location) {
786  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
787  unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
788  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
789
790  if (Location.isReg()) {
791    if (Reg < 32) {
792      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
793    } else {
794      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
795      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
796    }
797  } else {
798    if (Reg < 32) {
799      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
800    } else {
801      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
802      addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
803    }
804
805    addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
806  }
807
808  addBlock(Die, Attribute, 0, Block);
809}
810
811/// addToContextOwner - Add Die into the list of its context owner's children.
812void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
813  if (Context.isType()) {
814    DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode()));
815    ContextDIE->addChild(Die);
816  } else if (Context.isNameSpace()) {
817    DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context.getNode()));
818    ContextDIE->addChild(Die);
819  } else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode()))
820    ContextDIE->addChild(Die);
821  else
822    ModuleCU->addDie(Die);
823}
824
825/// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
826/// given DIType.
827DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
828  DIE *TyDIE = ModuleCU->getDIE(Ty.getNode());
829  if (TyDIE)
830    return TyDIE;
831
832  // Create new type.
833  TyDIE = new DIE(dwarf::DW_TAG_base_type);
834  ModuleCU->insertDIE(Ty.getNode(), TyDIE);
835  if (Ty.isBasicType())
836    constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode()));
837  else if (Ty.isCompositeType())
838    constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode()));
839  else {
840    assert(Ty.isDerivedType() && "Unknown kind of DIType");
841    constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode()));
842  }
843
844  addToContextOwner(TyDIE, Ty.getContext());
845  return TyDIE;
846}
847
848/// addType - Add a new type attribute to the specified entity.
849void DwarfDebug::addType(DIE *Entity, DIType Ty) {
850  if (!Ty.isValid())
851    return;
852
853  // Check for pre-existence.
854  DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
855  // If it exists then use the existing value.
856  if (Entry) {
857    Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
858    return;
859  }
860
861  // Construct type.
862  DIE *Buffer = getOrCreateTypeDIE(Ty);
863
864  // Set up proxy.
865  Entry = createDIEEntry(Buffer);
866  ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
867
868  Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
869}
870
871/// constructTypeDIE - Construct basic type die from DIBasicType.
872void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
873  // Get core information.
874  StringRef Name = BTy.getName();
875  Buffer.setTag(dwarf::DW_TAG_base_type);
876  addUInt(&Buffer, dwarf::DW_AT_encoding,  dwarf::DW_FORM_data1,
877          BTy.getEncoding());
878
879  // Add name if not anonymous or intermediate type.
880  if (!Name.empty())
881    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
882  uint64_t Size = BTy.getSizeInBits() >> 3;
883  addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
884}
885
886/// constructTypeDIE - Construct derived type die from DIDerivedType.
887void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
888  // Get core information.
889  StringRef Name = DTy.getName();
890  uint64_t Size = DTy.getSizeInBits() >> 3;
891  unsigned Tag = DTy.getTag();
892
893  // FIXME - Workaround for templates.
894  if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
895
896  Buffer.setTag(Tag);
897
898  // Map to main type, void will not have a type.
899  DIType FromTy = DTy.getTypeDerivedFrom();
900  addType(&Buffer, FromTy);
901
902  // Add name if not anonymous or intermediate type.
903  if (!Name.empty())
904    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
905
906  // Add size if non-zero (derived types might be zero-sized.)
907  if (Size)
908    addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
909
910  // Add source line info if available and TyDesc is not a forward declaration.
911  if (!DTy.isForwardDecl())
912    addSourceLine(&Buffer, &DTy);
913}
914
915/// constructTypeDIE - Construct type DIE from DICompositeType.
916void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
917  // Get core information.
918  StringRef Name = CTy.getName();
919
920  uint64_t Size = CTy.getSizeInBits() >> 3;
921  unsigned Tag = CTy.getTag();
922  Buffer.setTag(Tag);
923
924  switch (Tag) {
925  case dwarf::DW_TAG_vector_type:
926  case dwarf::DW_TAG_array_type:
927    constructArrayTypeDIE(Buffer, &CTy);
928    break;
929  case dwarf::DW_TAG_enumeration_type: {
930    DIArray Elements = CTy.getTypeArray();
931
932    // Add enumerators to enumeration type.
933    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
934      DIE *ElemDie = NULL;
935      DIDescriptor Enum(Elements.getElement(i).getNode());
936      if (Enum.isEnumerator()) {
937        ElemDie = constructEnumTypeDIE(DIEnumerator(Enum.getNode()));
938        Buffer.addChild(ElemDie);
939      }
940    }
941  }
942    break;
943  case dwarf::DW_TAG_subroutine_type: {
944    // Add return type.
945    DIArray Elements = CTy.getTypeArray();
946    DIDescriptor RTy = Elements.getElement(0);
947    addType(&Buffer, DIType(RTy.getNode()));
948
949    // Add prototype flag.
950    addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
951
952    // Add arguments.
953    for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
954      DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
955      DIDescriptor Ty = Elements.getElement(i);
956      addType(Arg, DIType(Ty.getNode()));
957      Buffer.addChild(Arg);
958    }
959  }
960    break;
961  case dwarf::DW_TAG_structure_type:
962  case dwarf::DW_TAG_union_type:
963  case dwarf::DW_TAG_class_type: {
964    // Add elements to structure type.
965    DIArray Elements = CTy.getTypeArray();
966
967    // A forward struct declared type may not have elements available.
968    unsigned N = Elements.getNumElements();
969    if (N == 0)
970      break;
971
972    // Add elements to structure type.
973    for (unsigned i = 0; i < N; ++i) {
974      DIDescriptor Element = Elements.getElement(i);
975      DIE *ElemDie = NULL;
976      if (Element.isSubprogram())
977        ElemDie = createSubprogramDIE(DISubprogram(Element.getNode()));
978      else if (Element.isVariable()) {
979        DIVariable DV(Element.getNode());
980        ElemDie = new DIE(dwarf::DW_TAG_variable);
981        addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
982                  DV.getName());
983        addType(ElemDie, DV.getType());
984        addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
985        addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
986        addSourceLine(ElemDie, &DV);
987      } else if (Element.isDerivedType())
988        ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
989      else
990        continue;
991      Buffer.addChild(ElemDie);
992    }
993
994    if (CTy.isAppleBlockExtension())
995      addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
996
997    unsigned RLang = CTy.getRunTimeLang();
998    if (RLang)
999      addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1000              dwarf::DW_FORM_data1, RLang);
1001
1002    DICompositeType ContainingType = CTy.getContainingType();
1003    if (DIDescriptor(ContainingType.getNode()).isCompositeType())
1004      addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1005                  getOrCreateTypeDIE(DIType(ContainingType.getNode())));
1006    break;
1007  }
1008  default:
1009    break;
1010  }
1011
1012  // Add name if not anonymous or intermediate type.
1013  if (!Name.empty())
1014    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1015
1016  if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
1017      Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1018    // Add size if non-zero (derived types might be zero-sized.)
1019    if (Size)
1020      addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1021    else {
1022      // Add zero size if it is not a forward declaration.
1023      if (CTy.isForwardDecl())
1024        addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1025      else
1026        addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1027    }
1028
1029    // Add source line info if available.
1030    if (!CTy.isForwardDecl())
1031      addSourceLine(&Buffer, &CTy);
1032  }
1033}
1034
1035/// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1036void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1037  int64_t L = SR.getLo();
1038  int64_t H = SR.getHi();
1039  DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1040
1041  addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1042  if (L)
1043    addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1044  addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1045
1046  Buffer.addChild(DW_Subrange);
1047}
1048
1049/// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1050void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1051                                       DICompositeType *CTy) {
1052  Buffer.setTag(dwarf::DW_TAG_array_type);
1053  if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1054    addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1055
1056  // Emit derived type.
1057  addType(&Buffer, CTy->getTypeDerivedFrom());
1058  DIArray Elements = CTy->getTypeArray();
1059
1060  // Get an anonymous type for index type.
1061  DIE *IdxTy = ModuleCU->getIndexTyDie();
1062  if (!IdxTy) {
1063    // Construct an anonymous type for index type.
1064    IdxTy = new DIE(dwarf::DW_TAG_base_type);
1065    addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1066    addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1067            dwarf::DW_ATE_signed);
1068    ModuleCU->addDie(IdxTy);
1069    ModuleCU->setIndexTyDie(IdxTy);
1070  }
1071
1072  // Add subranges to array type.
1073  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1074    DIDescriptor Element = Elements.getElement(i);
1075    if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1076      constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1077  }
1078}
1079
1080/// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1081DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1082  DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1083  StringRef Name = ETy.getName();
1084  addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1085  int64_t Value = ETy.getEnumValue();
1086  addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1087  return Enumerator;
1088}
1089
1090/// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1091/// printer to not emit usual symbol prefix before the symbol name is used then
1092/// return linkage name after skipping this special LLVM prefix.
1093static StringRef getRealLinkageName(StringRef LinkageName) {
1094  char One = '\1';
1095  if (LinkageName.startswith(StringRef(&One, 1)))
1096    return LinkageName.substr(1);
1097  return LinkageName;
1098}
1099
1100/// createGlobalVariableDIE - Create new DIE using GV.
1101DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1102  // If the global variable was optmized out then no need to create debug info
1103  // entry.
1104  if (!GV.getGlobal()) return NULL;
1105  if (GV.getDisplayName().empty()) return NULL;
1106
1107  DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1108  addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1109            GV.getDisplayName());
1110
1111  StringRef LinkageName = GV.getLinkageName();
1112  if (!LinkageName.empty())
1113    addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1114              getRealLinkageName(LinkageName));
1115
1116  addType(GVDie, GV.getType());
1117  if (!GV.isLocalToUnit())
1118    addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1119  addSourceLine(GVDie, &GV);
1120
1121  return GVDie;
1122}
1123
1124/// createMemberDIE - Create new member DIE.
1125DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1126  DIE *MemberDie = new DIE(DT.getTag());
1127  StringRef Name = DT.getName();
1128  if (!Name.empty())
1129    addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1130
1131  addType(MemberDie, DT.getTypeDerivedFrom());
1132
1133  addSourceLine(MemberDie, &DT);
1134
1135  DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1136  addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1137
1138  uint64_t Size = DT.getSizeInBits();
1139  uint64_t FieldSize = DT.getOriginalTypeSize();
1140
1141  if (Size != FieldSize) {
1142    // Handle bitfield.
1143    addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1144    addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1145
1146    uint64_t Offset = DT.getOffsetInBits();
1147    uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1148    uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1149    uint64_t FieldOffset = (HiMark - FieldSize);
1150    Offset -= FieldOffset;
1151
1152    // Maybe we need to work from the other end.
1153    if (Asm->getTargetData().isLittleEndian())
1154      Offset = FieldSize - (Offset + Size);
1155    addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1156
1157    // Here WD_AT_data_member_location points to the anonymous
1158    // field that includes this bit field.
1159    addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1160
1161  } else
1162    // This is not a bitfield.
1163    addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1164
1165  if (DT.getTag() == dwarf::DW_TAG_inheritance
1166      && DT.isVirtual()) {
1167
1168    // For C++, virtual base classes are not at fixed offset. Use following
1169    // expression to extract appropriate offset from vtable.
1170    // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1171
1172    DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1173    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1174    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1175    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1176    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1177    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1178    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1179    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1180
1181    addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1182             VBaseLocationDie);
1183  } else
1184    addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1185
1186  if (DT.isProtected())
1187    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1188            dwarf::DW_ACCESS_protected);
1189  else if (DT.isPrivate())
1190    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1191            dwarf::DW_ACCESS_private);
1192  else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1193    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1194            dwarf::DW_ACCESS_public);
1195  if (DT.isVirtual())
1196    addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1197            dwarf::DW_VIRTUALITY_virtual);
1198  return MemberDie;
1199}
1200
1201/// createSubprogramDIE - Create new DIE using SP.
1202DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1203  DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1204  if (SPDie)
1205    return SPDie;
1206
1207  SPDie = new DIE(dwarf::DW_TAG_subprogram);
1208  // Constructors and operators for anonymous aggregates do not have names.
1209  if (!SP.getName().empty())
1210    addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1211
1212  StringRef LinkageName = SP.getLinkageName();
1213  if (!LinkageName.empty())
1214    addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1215              getRealLinkageName(LinkageName));
1216
1217  addSourceLine(SPDie, &SP);
1218
1219  // Add prototyped tag, if C or ObjC.
1220  unsigned Lang = SP.getCompileUnit().getLanguage();
1221  if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1222      Lang == dwarf::DW_LANG_ObjC)
1223    addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1224
1225  // Add Return Type.
1226  DICompositeType SPTy = SP.getType();
1227  DIArray Args = SPTy.getTypeArray();
1228  unsigned SPTag = SPTy.getTag();
1229
1230  if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1231    addType(SPDie, SPTy);
1232  else
1233    addType(SPDie, DIType(Args.getElement(0).getNode()));
1234
1235  unsigned VK = SP.getVirtuality();
1236  if (VK) {
1237    addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1238    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1239    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1240    addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1241    addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1242    ContainingTypeMap.insert(std::make_pair(SPDie,
1243                                            SP.getContainingType().getNode()));
1244  }
1245
1246  if (MakeDecl || !SP.isDefinition()) {
1247    addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1248
1249    // Add arguments. Do not add arguments for subprogram definition. They will
1250    // be handled while processing variables.
1251    DICompositeType SPTy = SP.getType();
1252    DIArray Args = SPTy.getTypeArray();
1253    unsigned SPTag = SPTy.getTag();
1254
1255    if (SPTag == dwarf::DW_TAG_subroutine_type)
1256      for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1257        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1258        DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1259        addType(Arg, ATy);
1260        if (ATy.isArtificial())
1261          addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1262        SPDie->addChild(Arg);
1263      }
1264  }
1265
1266  if (SP.isArtificial())
1267    addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1268
1269  // DW_TAG_inlined_subroutine may refer to this DIE.
1270  ModuleCU->insertDIE(SP.getNode(), SPDie);
1271
1272  if (!DisableFramePointerElim(*Asm->MF))
1273    addUInt(SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr, dwarf::DW_FORM_flag, 1);
1274
1275  return SPDie;
1276}
1277
1278DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1279  assert(N && "Invalid Scope encoding!");
1280
1281  DbgScope *AScope = AbstractScopes.lookup(N);
1282  if (AScope)
1283    return AScope;
1284
1285  DbgScope *Parent = NULL;
1286
1287  DIDescriptor Scope(N);
1288  if (Scope.isLexicalBlock()) {
1289    DILexicalBlock DB(N);
1290    DIDescriptor ParentDesc = DB.getContext();
1291    Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1292  }
1293
1294  AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1295
1296  if (Parent)
1297    Parent->addScope(AScope);
1298  AScope->setAbstractScope();
1299  AbstractScopes[N] = AScope;
1300  if (DIDescriptor(N).isSubprogram())
1301    AbstractScopesList.push_back(AScope);
1302  return AScope;
1303}
1304
1305/// isSubprogramContext - Return true if Context is either a subprogram
1306/// or another context nested inside a subprogram.
1307static bool isSubprogramContext(MDNode *Context) {
1308  if (!Context)
1309    return false;
1310  DIDescriptor D(Context);
1311  if (D.isSubprogram())
1312    return true;
1313  if (D.isType())
1314    return isSubprogramContext(DIType(Context).getContext().getNode());
1315  return false;
1316}
1317
1318/// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1319/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1320/// If there are global variables in this scope then create and insert
1321/// DIEs for these variables.
1322DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1323  DIE *SPDie = ModuleCU->getDIE(SPNode);
1324  assert(SPDie && "Unable to find subprogram DIE!");
1325  DISubprogram SP(SPNode);
1326
1327  // There is not any need to generate specification DIE for a function
1328  // defined at compile unit level. If a function is defined inside another
1329  // function then gdb prefers the definition at top level and but does not
1330  // expect specification DIE in parent function. So avoid creating
1331  // specification DIE for a function defined inside a function.
1332  if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1333      !SP.getContext().isFile() &&
1334      !isSubprogramContext(SP.getContext().getNode())) {
1335    addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1336
1337    // Add arguments.
1338    DICompositeType SPTy = SP.getType();
1339    DIArray Args = SPTy.getTypeArray();
1340    unsigned SPTag = SPTy.getTag();
1341    if (SPTag == dwarf::DW_TAG_subroutine_type)
1342      for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1343        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1344        DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1345        addType(Arg, ATy);
1346        if (ATy.isArtificial())
1347          addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1348        SPDie->addChild(Arg);
1349      }
1350    DIE *SPDeclDie = SPDie;
1351    SPDie = new DIE(dwarf::DW_TAG_subprogram);
1352    addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1353                SPDeclDie);
1354    ModuleCU->addDie(SPDie);
1355  }
1356
1357  addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1358           Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1359  addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1360           Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1361  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1362  MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1363  addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1364
1365  if (!DISubprogram(SPNode).isLocalToUnit())
1366    addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1367
1368  return SPDie;
1369}
1370
1371/// constructLexicalScope - Construct new DW_TAG_lexical_block
1372/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1373DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1374
1375  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1376  if (Scope->isAbstractScope())
1377    return ScopeDIE;
1378
1379  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1380  if (Ranges.empty())
1381    return 0;
1382
1383  SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1384  if (Ranges.size() > 1) {
1385    // .debug_range section has not been laid out yet. Emit offset in
1386    // .debug_range as a uint, size 4, for now. emitDIE will handle
1387    // DW_AT_ranges appropriately.
1388    addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1389            DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1390    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1391         RE = Ranges.end(); RI != RE; ++RI) {
1392      DebugRangeSymbols.push_back(InsnBeforeLabelMap.lookup(RI->first));
1393      DebugRangeSymbols.push_back(InsnAfterLabelMap.lookup(RI->second));
1394    }
1395    DebugRangeSymbols.push_back(NULL);
1396    DebugRangeSymbols.push_back(NULL);
1397    return ScopeDIE;
1398  }
1399
1400  MCSymbol *Start = InsnBeforeLabelMap.lookup(RI->first);
1401  MCSymbol *End = InsnAfterLabelMap.lookup(RI->second);
1402
1403  if (Start == 0 || End == 0) return 0;
1404
1405  assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1406  assert(End->isDefined() && "Invalid end label for an inlined scope!");
1407
1408  addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1409           Start ? Start : Asm->GetTempSymbol("func_begin",
1410                                              Asm->getFunctionNumber()));
1411  addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1412           End ? End : Asm->GetTempSymbol("func_end",Asm->getFunctionNumber()));
1413
1414  return ScopeDIE;
1415}
1416
1417/// constructInlinedScopeDIE - This scope represents inlined body of
1418/// a function. Construct DIE to represent this concrete inlined copy
1419/// of the function.
1420DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1421
1422  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1423  assert (Ranges.empty() == false
1424          && "DbgScope does not have instruction markers!");
1425
1426  // FIXME : .debug_inlined section specification does not clearly state how
1427  // to emit inlined scope that is split into multiple instruction ranges.
1428  // For now, use first instruction range and emit low_pc/high_pc pair and
1429  // corresponding .debug_inlined section entry for this pair.
1430  SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1431  MCSymbol *StartLabel = InsnBeforeLabelMap.lookup(RI->first);
1432  MCSymbol *EndLabel = InsnAfterLabelMap.lookup(RI->second);
1433
1434  if (StartLabel == 0 || EndLabel == 0) {
1435    assert (0 && "Unexpected Start and End  labels for a inlined scope!");
1436    return 0;
1437  }
1438  assert(StartLabel->isDefined() &&
1439         "Invalid starting label for an inlined scope!");
1440  assert(EndLabel->isDefined() &&
1441         "Invalid end label for an inlined scope!");
1442
1443  if (!Scope->getScopeNode())
1444    return NULL;
1445  DIScope DS(Scope->getScopeNode());
1446  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1447
1448  DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1449  DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1450  assert(OriginDIE && "Unable to find Origin DIE!");
1451  addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1452              dwarf::DW_FORM_ref4, OriginDIE);
1453
1454  addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1455  addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1456
1457  InlinedSubprogramDIEs.insert(OriginDIE);
1458
1459  // Track the start label for this inlined function.
1460  DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1461    I = InlineInfo.find(InlinedSP.getNode());
1462
1463  if (I == InlineInfo.end()) {
1464    InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartLabel,
1465                                                             ScopeDIE));
1466    InlinedSPNodes.push_back(InlinedSP.getNode());
1467  } else
1468    I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1469
1470  DILocation DL(Scope->getInlinedAt());
1471  addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1472  addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1473
1474  return ScopeDIE;
1475}
1476
1477
1478/// constructVariableDIE - Construct a DIE for the given DbgVariable.
1479DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1480  // Get the descriptor.
1481  const DIVariable &VD = DV->getVariable();
1482  StringRef Name = VD.getName();
1483  if (Name.empty())
1484    return NULL;
1485
1486  // Translate tag to proper Dwarf tag.  The result variable is dropped for
1487  // now.
1488  unsigned Tag;
1489  switch (VD.getTag()) {
1490  case dwarf::DW_TAG_return_variable:
1491    return NULL;
1492  case dwarf::DW_TAG_arg_variable:
1493    Tag = dwarf::DW_TAG_formal_parameter;
1494    break;
1495  case dwarf::DW_TAG_auto_variable:    // fall thru
1496  default:
1497    Tag = dwarf::DW_TAG_variable;
1498    break;
1499  }
1500
1501  // Define variable debug information entry.
1502  DIE *VariableDie = new DIE(Tag);
1503
1504
1505  DIE *AbsDIE = NULL;
1506  if (DbgVariable *AV = DV->getAbstractVariable())
1507    AbsDIE = AV->getDIE();
1508
1509  if (AbsDIE) {
1510    DIScope DS(Scope->getScopeNode());
1511    DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1512    DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1513    (void) OriginSPDIE;
1514    assert(OriginSPDIE && "Unable to find Origin DIE for the SP!");
1515    DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1516    assert(AbsDIE && "Unable to find Origin DIE for the Variable!");
1517    addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1518                dwarf::DW_FORM_ref4, AbsDIE);
1519  }
1520  else {
1521    addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1522    addSourceLine(VariableDie, &VD);
1523
1524    // Add variable type.
1525    // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1526    // addresses instead.
1527    if (VD.isBlockByrefVariable())
1528      addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1529    else
1530      addType(VariableDie, VD.getType());
1531  }
1532
1533  // Add variable address.
1534  if (!Scope->isAbstractScope()) {
1535    // Check if variable is described by DBG_VALUE instruction.
1536    if (const MachineInstr *DbgValueInsn = DV->getDbgValue()) {
1537      if (DbgValueInsn->getNumOperands() == 3) {
1538        // FIXME : Handle getNumOperands != 3
1539        if (DbgValueInsn->getOperand(0).getType()
1540            == MachineOperand::MO_Register
1541            && DbgValueInsn->getOperand(0).getReg()) {
1542          MachineLocation Location;
1543          Location.set(DbgValueInsn->getOperand(0).getReg());
1544          addAddress(VariableDie, dwarf::DW_AT_location, Location);
1545          if (MCSymbol *VS = DV->getDbgValueLabel())
1546            addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1547                     VS);
1548        } else if (DbgValueInsn->getOperand(0).getType() ==
1549                   MachineOperand::MO_Immediate) {
1550          DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1551          unsigned Imm = DbgValueInsn->getOperand(0).getImm();
1552          addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
1553          addBlock(VariableDie, dwarf::DW_AT_const_value, 0, Block);
1554          if (MCSymbol *VS = DV->getDbgValueLabel())
1555            addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1556                     VS);
1557        } else if (DbgValueInsn->getOperand(0).getType() ==
1558                   MachineOperand::MO_FPImmediate) {
1559          DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1560          APFloat FPImm = DbgValueInsn->getOperand(0).getFPImm()->getValueAPF();
1561
1562          // Get the raw data form of the floating point.
1563          const APInt FltVal = FPImm.bitcastToAPInt();
1564          const char *FltPtr = (const char*)FltVal.getRawData();
1565
1566          int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
1567          bool LittleEndian = Asm->getTargetData().isLittleEndian();
1568          int Incr = (LittleEndian ? 1 : -1);
1569          int Start = (LittleEndian ? 0 : NumBytes - 1);
1570          int Stop = (LittleEndian ? NumBytes : -1);
1571
1572          // Output the constant to DWARF one byte at a time.
1573          for (; Start != Stop; Start += Incr)
1574            addUInt(Block, 0, dwarf::DW_FORM_data1,
1575                    (unsigned char)0xFF & FltPtr[Start]);
1576
1577          addBlock(VariableDie, dwarf::DW_AT_const_value, 0, Block);
1578
1579          if (MCSymbol *VS = DV->getDbgValueLabel())
1580            addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1581                     VS);
1582        } else {
1583          //FIXME : Handle other operand types.
1584          delete VariableDie;
1585          return NULL;
1586        }
1587      }
1588    } else {
1589      MachineLocation Location;
1590      unsigned FrameReg;
1591      const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1592      int Offset = RI->getFrameIndexReference(*Asm->MF, DV->getFrameIndex(),
1593                                              FrameReg);
1594      Location.set(FrameReg, Offset);
1595
1596      if (VD.hasComplexAddress())
1597        addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1598      else if (VD.isBlockByrefVariable())
1599        addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1600      else
1601        addAddress(VariableDie, dwarf::DW_AT_location, Location);
1602    }
1603  }
1604
1605  if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
1606    addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1607  DV->setDIE(VariableDie);
1608  return VariableDie;
1609
1610}
1611
1612void DwarfDebug::addPubTypes(DISubprogram SP) {
1613  DICompositeType SPTy = SP.getType();
1614  unsigned SPTag = SPTy.getTag();
1615  if (SPTag != dwarf::DW_TAG_subroutine_type)
1616    return;
1617
1618  DIArray Args = SPTy.getTypeArray();
1619  for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1620    DIType ATy(Args.getElement(i).getNode());
1621    if (!ATy.isValid())
1622      continue;
1623    DICompositeType CATy = getDICompositeType(ATy);
1624    if (DIDescriptor(CATy.getNode()).Verify() && !CATy.getName().empty()
1625        && !CATy.isForwardDecl()) {
1626      if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1627        ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1628    }
1629  }
1630}
1631
1632/// constructScopeDIE - Construct a DIE for this scope.
1633DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1634  if (!Scope || !Scope->getScopeNode())
1635    return NULL;
1636
1637  DIScope DS(Scope->getScopeNode());
1638  DIE *ScopeDIE = NULL;
1639  if (Scope->getInlinedAt())
1640    ScopeDIE = constructInlinedScopeDIE(Scope);
1641  else if (DS.isSubprogram()) {
1642    if (Scope->isAbstractScope())
1643      ScopeDIE = ModuleCU->getDIE(DS.getNode());
1644    else
1645      ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1646  }
1647  else
1648    ScopeDIE = constructLexicalScopeDIE(Scope);
1649  if (!ScopeDIE) return NULL;
1650
1651  // Add variables to scope.
1652  const SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1653  for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1654    DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1655    if (VariableDIE)
1656      ScopeDIE->addChild(VariableDIE);
1657  }
1658
1659  // Add nested scopes.
1660  const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1661  for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1662    // Define the Scope debug information entry.
1663    DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1664    if (NestedDIE)
1665      ScopeDIE->addChild(NestedDIE);
1666  }
1667
1668  if (DS.isSubprogram())
1669    addPubTypes(DISubprogram(DS.getNode()));
1670
1671 return ScopeDIE;
1672}
1673
1674/// GetOrCreateSourceID - Look up the source id with the given directory and
1675/// source file names. If none currently exists, create a new id and insert it
1676/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1677/// maps as well.
1678unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1679  unsigned DId;
1680  StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1681  if (DI != DirectoryIdMap.end()) {
1682    DId = DI->getValue();
1683  } else {
1684    DId = DirectoryNames.size() + 1;
1685    DirectoryIdMap[DirName] = DId;
1686    DirectoryNames.push_back(DirName);
1687  }
1688
1689  unsigned FId;
1690  StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1691  if (FI != SourceFileIdMap.end()) {
1692    FId = FI->getValue();
1693  } else {
1694    FId = SourceFileNames.size() + 1;
1695    SourceFileIdMap[FileName] = FId;
1696    SourceFileNames.push_back(FileName);
1697  }
1698
1699  DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1700    SourceIdMap.find(std::make_pair(DId, FId));
1701  if (SI != SourceIdMap.end())
1702    return SI->second;
1703
1704  unsigned SrcId = SourceIds.size() + 1;  // DW_AT_decl_file cannot be 0.
1705  SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1706  SourceIds.push_back(std::make_pair(DId, FId));
1707
1708  return SrcId;
1709}
1710
1711/// getOrCreateNameSpace - Create a DIE for DINameSpace.
1712DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1713  DIE *NDie = ModuleCU->getDIE(NS.getNode());
1714  if (NDie)
1715    return NDie;
1716  NDie = new DIE(dwarf::DW_TAG_namespace);
1717  ModuleCU->insertDIE(NS.getNode(), NDie);
1718  if (!NS.getName().empty())
1719    addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1720  addSourceLine(NDie, &NS);
1721  addToContextOwner(NDie, NS.getContext());
1722  return NDie;
1723}
1724
1725void DwarfDebug::constructCompileUnit(MDNode *N) {
1726  DICompileUnit DIUnit(N);
1727  // Use first compile unit marked as isMain as the compile unit for this
1728  // module.
1729  if (ModuleCU || !DIUnit.isMain())
1730    return;
1731  StringRef FN = DIUnit.getFilename();
1732  StringRef Dir = DIUnit.getDirectory();
1733  unsigned ID = GetOrCreateSourceID(Dir, FN);
1734
1735  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1736  addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1737            DIUnit.getProducer());
1738  addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1739          DIUnit.getLanguage());
1740  addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1741  addLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, TextSectionSym);
1742  addLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1743           Asm->GetTempSymbol("text_end"));
1744  // DW_AT_stmt_list is a offset of line number information for this
1745  // compile unit in debug_line section. It is always zero when only one
1746  // compile unit is emitted in one object file.
1747  addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1748
1749  if (!Dir.empty())
1750    addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1751  if (DIUnit.isOptimized())
1752    addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1753
1754  StringRef Flags = DIUnit.getFlags();
1755  if (!Flags.empty())
1756    addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1757
1758  unsigned RVer = DIUnit.getRunTimeVersion();
1759  if (RVer)
1760    addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1761            dwarf::DW_FORM_data1, RVer);
1762
1763  assert(!ModuleCU &&
1764         "ModuleCU assigned since the top of constructCompileUnit");
1765  ModuleCU = new CompileUnit(ID, Die);
1766}
1767
1768void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1769  DIGlobalVariable DI_GV(N);
1770
1771  // If debug information is malformed then ignore it.
1772  if (DI_GV.Verify() == false)
1773    return;
1774
1775  // Check for pre-existence.
1776  if (ModuleCU->getDIE(DI_GV.getNode()))
1777    return;
1778
1779  DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1780  if (!VariableDie)
1781    return;
1782
1783  // Add to map.
1784  ModuleCU->insertDIE(N, VariableDie);
1785
1786  // Add to context owner.
1787  DIDescriptor GVContext = DI_GV.getContext();
1788  // Do not create specification DIE if context is either compile unit
1789  // or a subprogram.
1790  if (DI_GV.isDefinition() && !GVContext.isCompileUnit() &&
1791      !GVContext.isFile() &&
1792      !isSubprogramContext(GVContext.getNode())) {
1793    // Create specification DIE.
1794    DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1795    addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1796                dwarf::DW_FORM_ref4, VariableDie);
1797    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1798    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1799    addLabel(Block, 0, dwarf::DW_FORM_udata,
1800             Asm->Mang->getSymbol(DI_GV.getGlobal()));
1801    addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1802    addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1803    ModuleCU->addDie(VariableSpecDIE);
1804  } else {
1805    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1806    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1807    addLabel(Block, 0, dwarf::DW_FORM_udata,
1808             Asm->Mang->getSymbol(DI_GV.getGlobal()));
1809    addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1810  }
1811  addToContextOwner(VariableDie, GVContext);
1812
1813  // Expose as global. FIXME - need to check external flag.
1814  ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1815
1816  DIType GTy = DI_GV.getType();
1817  if (GTy.isCompositeType() && !GTy.getName().empty()
1818      && !GTy.isForwardDecl()) {
1819    DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1820    assert(Entry && "Missing global type!");
1821    ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1822  }
1823  return;
1824}
1825
1826void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1827  DISubprogram SP(N);
1828
1829  // Check for pre-existence.
1830  if (ModuleCU->getDIE(N))
1831    return;
1832
1833  if (!SP.isDefinition())
1834    // This is a method declaration which will be handled while constructing
1835    // class type.
1836    return;
1837
1838  DIE *SubprogramDie = createSubprogramDIE(SP);
1839
1840  // Add to map.
1841  ModuleCU->insertDIE(N, SubprogramDie);
1842
1843  // Add to context owner.
1844  addToContextOwner(SubprogramDie, SP.getContext());
1845
1846  // Expose as global.
1847  ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1848
1849  return;
1850}
1851
1852/// beginModule - Emit all Dwarf sections that should come prior to the
1853/// content. Create global DIEs and emit initial debug info sections.
1854/// This is inovked by the target AsmPrinter.
1855void DwarfDebug::beginModule(Module *M) {
1856  DebugInfoFinder DbgFinder;
1857  DbgFinder.processModule(*M);
1858
1859  bool HasDebugInfo = false;
1860
1861  // Scan all the compile-units to see if there are any marked as the main unit.
1862  // if not, we do not generate debug info.
1863  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1864       E = DbgFinder.compile_unit_end(); I != E; ++I) {
1865    if (DICompileUnit(*I).isMain()) {
1866      HasDebugInfo = true;
1867      break;
1868    }
1869  }
1870
1871  if (!HasDebugInfo) return;
1872
1873  // Tell MMI that we have debug info.
1874  MMI->setDebugInfoAvailability(true);
1875
1876  // Emit initial sections.
1877  EmitSectionLabels();
1878
1879  // Create all the compile unit DIEs.
1880  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1881         E = DbgFinder.compile_unit_end(); I != E; ++I)
1882    constructCompileUnit(*I);
1883
1884  // Create DIEs for each subprogram.
1885  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1886         E = DbgFinder.subprogram_end(); I != E; ++I)
1887    constructSubprogramDIE(*I);
1888
1889  // Create DIEs for each global variable.
1890  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1891         E = DbgFinder.global_variable_end(); I != E; ++I)
1892    constructGlobalVariableDIE(*I);
1893
1894  // Prime section data.
1895  SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1896
1897  // Print out .file directives to specify files for .loc directives. These are
1898  // printed out early so that they precede any .loc directives.
1899  if (Asm->MAI->hasDotLocAndDotFile()) {
1900    for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1901      // Remember source id starts at 1.
1902      std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1903      // FIXME: don't use sys::path for this!  This should not depend on the
1904      // host.
1905      sys::Path FullPath(getSourceDirectoryName(Id.first));
1906      bool AppendOk =
1907        FullPath.appendComponent(getSourceFileName(Id.second));
1908      assert(AppendOk && "Could not append filename to directory!");
1909      AppendOk = false;
1910      Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
1911    }
1912  }
1913}
1914
1915/// endModule - Emit all Dwarf sections that should come after the content.
1916///
1917void DwarfDebug::endModule() {
1918  if (!ModuleCU) return;
1919
1920  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1921  for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1922         AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1923    DIE *ISP = *AI;
1924    addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1925  }
1926
1927  for (DenseMap<DIE *, MDNode *>::iterator CI = ContainingTypeMap.begin(),
1928         CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1929    DIE *SPDie = CI->first;
1930    MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1931    if (!N) continue;
1932    DIE *NDie = ModuleCU->getDIE(N);
1933    if (!NDie) continue;
1934    addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1935  }
1936
1937  // Standard sections final addresses.
1938  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1939  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1940  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1941  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1942
1943  // End text sections.
1944  for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1945    Asm->OutStreamer.SwitchSection(SectionMap[i]);
1946    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1947  }
1948
1949  // Emit common frame information.
1950  emitCommonDebugFrame();
1951
1952  // Emit function debug frame information
1953  for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1954         E = DebugFrames.end(); I != E; ++I)
1955    emitFunctionDebugFrame(*I);
1956
1957  // Compute DIE offsets and sizes.
1958  computeSizeAndOffsets();
1959
1960  // Emit all the DIEs into a debug info section
1961  emitDebugInfo();
1962
1963  // Corresponding abbreviations into a abbrev section.
1964  emitAbbreviations();
1965
1966  // Emit source line correspondence into a debug line section.
1967  emitDebugLines();
1968
1969  // Emit info into a debug pubnames section.
1970  emitDebugPubNames();
1971
1972  // Emit info into a debug pubtypes section.
1973  emitDebugPubTypes();
1974
1975  // Emit info into a debug loc section.
1976  emitDebugLoc();
1977
1978  // Emit info into a debug aranges section.
1979  EmitDebugARanges();
1980
1981  // Emit info into a debug ranges section.
1982  emitDebugRanges();
1983
1984  // Emit info into a debug macinfo section.
1985  emitDebugMacInfo();
1986
1987  // Emit inline info.
1988  emitDebugInlineInfo();
1989
1990  // Emit info into a debug str section.
1991  emitDebugStr();
1992
1993  delete ModuleCU;
1994  ModuleCU = NULL;  // Reset for the next Module, if any.
1995}
1996
1997/// findAbstractVariable - Find abstract variable, if any, associated with Var.
1998DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1999                                              unsigned FrameIdx,
2000                                              DebugLoc ScopeLoc) {
2001
2002  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
2003  if (AbsDbgVariable)
2004    return AbsDbgVariable;
2005
2006  LLVMContext &Ctx = Var.getNode()->getContext();
2007  DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2008  if (!Scope)
2009    return NULL;
2010
2011  AbsDbgVariable = new DbgVariable(Var, FrameIdx,
2012                                   NULL /* No more-abstract variable*/);
2013  Scope->addVariable(AbsDbgVariable);
2014  AbstractVariables[Var.getNode()] = AbsDbgVariable;
2015  return AbsDbgVariable;
2016}
2017
2018/// findAbstractVariable - Find abstract variable, if any, associated with Var.
2019/// FIXME : Refactor findAbstractVariable.
2020DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2021                                              const MachineInstr *MI,
2022                                              DebugLoc ScopeLoc) {
2023
2024  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
2025  if (AbsDbgVariable)
2026    return AbsDbgVariable;
2027
2028  LLVMContext &Ctx = Var.getNode()->getContext();
2029  DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2030  if (!Scope)
2031    return NULL;
2032
2033  AbsDbgVariable = new DbgVariable(Var, MI,
2034                                   NULL /* No more-abstract variable*/);
2035  Scope->addVariable(AbsDbgVariable);
2036  AbstractVariables[Var.getNode()] = AbsDbgVariable;
2037  DbgValueStartMap[MI] = AbsDbgVariable;
2038  return AbsDbgVariable;
2039}
2040
2041/// collectVariableInfo - Populate DbgScope entries with variables' info.
2042void DwarfDebug::collectVariableInfo() {
2043  const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2044
2045  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2046  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2047         VE = VMap.end(); VI != VE; ++VI) {
2048    MDNode *Var = VI->first;
2049    if (!Var) continue;
2050    DIVariable DV(Var);
2051    const std::pair<unsigned, DebugLoc> &VP = VI->second;
2052
2053    DbgScope *Scope = 0;
2054    if (MDNode *IA = VP.second.getInlinedAt(Ctx))
2055      Scope = ConcreteScopes.lookup(IA);
2056    if (Scope == 0)
2057      Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2058
2059    // If variable scope is not found then skip this variable.
2060    if (Scope == 0)
2061      continue;
2062
2063    DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, VP.second);
2064    DbgVariable *RegVar = new DbgVariable(DV, VP.first, AbsDbgVariable);
2065    Scope->addVariable(RegVar);
2066  }
2067
2068  // Collect variable information from DBG_VALUE machine instructions;
2069  for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2070       I != E; ++I) {
2071    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2072         II != IE; ++II) {
2073      const MachineInstr *MInsn = II;
2074      if (!MInsn->isDebugValue())
2075        continue;
2076
2077      // FIXME : Lift this restriction.
2078      if (MInsn->getNumOperands() != 3)
2079        continue;
2080      DIVariable DV(
2081        const_cast<MDNode *>(MInsn->getOperand(MInsn->getNumOperands() - 1)
2082                               .getMetadata()));
2083      if (DV.getTag() == dwarf::DW_TAG_arg_variable)  {
2084        // FIXME Handle inlined subroutine arguments.
2085        DbgVariable *ArgVar = new DbgVariable(DV, MInsn, NULL);
2086        CurrentFnDbgScope->addVariable(ArgVar);
2087        DbgValueStartMap[MInsn] = ArgVar;
2088        continue;
2089      }
2090
2091      DebugLoc DL = MInsn->getDebugLoc();
2092      if (DL.isUnknown()) continue;
2093      DbgScope *Scope = 0;
2094      if (MDNode *IA = DL.getInlinedAt(Ctx))
2095        Scope = ConcreteScopes.lookup(IA);
2096      if (Scope == 0)
2097        Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2098
2099      // If variable scope is not found then skip this variable.
2100      if (Scope == 0)
2101        continue;
2102
2103      DbgVariable *AbsDbgVariable = findAbstractVariable(DV, MInsn, DL);
2104      DbgVariable *RegVar = new DbgVariable(DV, MInsn, AbsDbgVariable);
2105      DbgValueStartMap[MInsn] = RegVar;
2106      Scope->addVariable(RegVar);
2107    }
2108  }
2109}
2110
2111/// beginScope - Process beginning of a scope.
2112void DwarfDebug::beginScope(const MachineInstr *MI) {
2113  // Check location.
2114  DebugLoc DL = MI->getDebugLoc();
2115  if (DL.isUnknown())
2116    return;
2117
2118  MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2119
2120  // FIXME: Should only verify each scope once!
2121  if (!DIScope(Scope).Verify())
2122    return;
2123
2124  // DBG_VALUE instruction establishes new value.
2125  if (MI->isDebugValue()) {
2126    DenseMap<const MachineInstr *, DbgVariable *>::iterator DI
2127      = DbgValueStartMap.find(MI);
2128    if (DI != DbgValueStartMap.end()) {
2129      MCSymbol *Label = NULL;
2130      if (DL == PrevInstLoc)
2131        Label = PrevLabel;
2132      else {
2133        Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2134        PrevInstLoc = DL;
2135        PrevLabel = Label;
2136      }
2137      DI->second->setDbgValueLabel(Label);
2138    }
2139    return;
2140  }
2141
2142  // Emit a label to indicate location change. This is used for line
2143  // table even if this instruction does not start a new scope.
2144  MCSymbol *Label = NULL;
2145  if (DL == PrevInstLoc)
2146    Label = PrevLabel;
2147  else {
2148    Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2149    PrevInstLoc = DL;
2150    PrevLabel = Label;
2151  }
2152
2153  // If this instruction begins a scope then note down corresponding label.
2154  if (InsnsBeginScopeSet.count(MI) != 0)
2155    InsnBeforeLabelMap[MI] = Label;
2156}
2157
2158/// endScope - Process end of a scope.
2159void DwarfDebug::endScope(const MachineInstr *MI) {
2160  if (InsnsEndScopeSet.count(MI) != 0) {
2161    // Emit a label if this instruction ends a scope.
2162    MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2163    Asm->OutStreamer.EmitLabel(Label);
2164    InsnAfterLabelMap[MI] = Label;
2165  }
2166}
2167
2168/// getOrCreateDbgScope - Create DbgScope for the scope.
2169DbgScope *DwarfDebug::getOrCreateDbgScope(MDNode *Scope, MDNode *InlinedAt) {
2170  if (!InlinedAt) {
2171    DbgScope *WScope = DbgScopeMap.lookup(Scope);
2172    if (WScope)
2173      return WScope;
2174    WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2175    DbgScopeMap.insert(std::make_pair(Scope, WScope));
2176    if (DIDescriptor(Scope).isLexicalBlock()) {
2177      DbgScope *Parent =
2178        getOrCreateDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
2179      WScope->setParent(Parent);
2180      Parent->addScope(WScope);
2181    }
2182
2183    if (!WScope->getParent()) {
2184      StringRef SPName = DISubprogram(Scope).getLinkageName();
2185      if (SPName == Asm->MF->getFunction()->getName())
2186        CurrentFnDbgScope = WScope;
2187    }
2188
2189    return WScope;
2190  }
2191
2192  DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2193  if (WScope)
2194    return WScope;
2195
2196  WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2197  DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2198  DILocation DL(InlinedAt);
2199  DbgScope *Parent =
2200    getOrCreateDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2201  WScope->setParent(Parent);
2202  Parent->addScope(WScope);
2203
2204  ConcreteScopes[InlinedAt] = WScope;
2205  getOrCreateAbstractScope(Scope);
2206
2207  return WScope;
2208}
2209
2210/// hasValidLocation - Return true if debug location entry attached with
2211/// machine instruction encodes valid location info.
2212static bool hasValidLocation(LLVMContext &Ctx,
2213                             const MachineInstr *MInsn,
2214                             MDNode *&Scope, MDNode *&InlinedAt) {
2215  if (MInsn->isDebugValue())
2216    return false;
2217  DebugLoc DL = MInsn->getDebugLoc();
2218  if (DL.isUnknown()) return false;
2219
2220  MDNode *S = DL.getScope(Ctx);
2221
2222  // There is no need to create another DIE for compile unit. For all
2223  // other scopes, create one DbgScope now. This will be translated
2224  // into a scope DIE at the end.
2225  if (DIScope(S).isCompileUnit()) return false;
2226
2227  Scope = S;
2228  InlinedAt = DL.getInlinedAt(Ctx);
2229  return true;
2230}
2231
2232/// calculateDominanceGraph - Calculate dominance graph for DbgScope
2233/// hierarchy.
2234static void calculateDominanceGraph(DbgScope *Scope) {
2235  assert (Scope && "Unable to calculate scop edominance graph!");
2236  SmallVector<DbgScope *, 4> WorkStack;
2237  WorkStack.push_back(Scope);
2238  unsigned Counter = 0;
2239  while (!WorkStack.empty()) {
2240    DbgScope *WS = WorkStack.back();
2241    const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2242    bool visitedChildren = false;
2243    for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2244           SE = Children.end(); SI != SE; ++SI) {
2245      DbgScope *ChildScope = *SI;
2246      if (!ChildScope->getDFSOut()) {
2247        WorkStack.push_back(ChildScope);
2248        visitedChildren = true;
2249        ChildScope->setDFSIn(++Counter);
2250        break;
2251      }
2252    }
2253    if (!visitedChildren) {
2254      WorkStack.pop_back();
2255      WS->setDFSOut(++Counter);
2256    }
2257  }
2258}
2259
2260/// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2261static
2262void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2263                       DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2264{
2265#ifndef NDEBUG
2266  unsigned PrevDFSIn = 0;
2267  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2268       I != E; ++I) {
2269    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2270         II != IE; ++II) {
2271      const MachineInstr *MInsn = II;
2272      MDNode *Scope = NULL;
2273      MDNode *InlinedAt = NULL;
2274
2275      // Check if instruction has valid location information.
2276      if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2277        dbgs() << " [ ";
2278        if (InlinedAt)
2279          dbgs() << "*";
2280        DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2281          MI2ScopeMap.find(MInsn);
2282        if (DI != MI2ScopeMap.end()) {
2283          DbgScope *S = DI->second;
2284          dbgs() << S->getDFSIn();
2285          PrevDFSIn = S->getDFSIn();
2286        } else
2287          dbgs() << PrevDFSIn;
2288      } else
2289        dbgs() << " [ x" << PrevDFSIn;
2290      dbgs() << " ]";
2291      MInsn->dump();
2292    }
2293    dbgs() << "\n";
2294  }
2295#endif
2296}
2297/// extractScopeInformation - Scan machine instructions in this function
2298/// and collect DbgScopes. Return true, if at least one scope was found.
2299bool DwarfDebug::extractScopeInformation() {
2300  // If scope information was extracted using .dbg intrinsics then there is not
2301  // any need to extract these information by scanning each instruction.
2302  if (!DbgScopeMap.empty())
2303    return false;
2304
2305  // Scan each instruction and create scopes. First build working set of scopes.
2306  LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2307  SmallVector<DbgRange, 4> MIRanges;
2308  DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2309  MDNode *PrevScope = NULL;
2310  MDNode *PrevInlinedAt = NULL;
2311  const MachineInstr *RangeBeginMI = NULL;
2312  const MachineInstr *PrevMI = NULL;
2313  for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2314       I != E; ++I) {
2315    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2316         II != IE; ++II) {
2317      const MachineInstr *MInsn = II;
2318      MDNode *Scope = NULL;
2319      MDNode *InlinedAt = NULL;
2320
2321      // Check if instruction has valid location information.
2322      if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2323        PrevMI = MInsn;
2324        continue;
2325      }
2326
2327      // If scope has not changed then skip this instruction.
2328      if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2329        PrevMI = MInsn;
2330        continue;
2331      }
2332
2333      if (RangeBeginMI) {
2334        // If we have alread seen a beginning of a instruction range and
2335        // current instruction scope does not match scope of first instruction
2336        // in this range then create a new instruction range.
2337        DbgRange R(RangeBeginMI, PrevMI);
2338        MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2339        MIRanges.push_back(R);
2340      }
2341
2342      // This is a beginning of a new instruction range.
2343      RangeBeginMI = MInsn;
2344
2345      // Reset previous markers.
2346      PrevMI = MInsn;
2347      PrevScope = Scope;
2348      PrevInlinedAt = InlinedAt;
2349    }
2350  }
2351
2352  // Create last instruction range.
2353  if (RangeBeginMI && PrevMI && PrevScope) {
2354    DbgRange R(RangeBeginMI, PrevMI);
2355    MIRanges.push_back(R);
2356    MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2357  }
2358
2359  if (!CurrentFnDbgScope)
2360    return false;
2361
2362  calculateDominanceGraph(CurrentFnDbgScope);
2363  if (PrintDbgScope)
2364    printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2365
2366  // Find ranges of instructions covered by each DbgScope;
2367  DbgScope *PrevDbgScope = NULL;
2368  for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2369         RE = MIRanges.end(); RI != RE; ++RI) {
2370    const DbgRange &R = *RI;
2371    DbgScope *S = MI2ScopeMap.lookup(R.first);
2372    assert (S && "Lost DbgScope for a machine instruction!");
2373    if (PrevDbgScope && !PrevDbgScope->dominates(S))
2374      PrevDbgScope->closeInsnRange(S);
2375    S->openInsnRange(R.first);
2376    S->extendInsnRange(R.second);
2377    PrevDbgScope = S;
2378  }
2379
2380  if (PrevDbgScope)
2381    PrevDbgScope->closeInsnRange();
2382
2383  identifyScopeMarkers();
2384
2385  return !DbgScopeMap.empty();
2386}
2387
2388/// identifyScopeMarkers() -
2389/// Each DbgScope has first instruction and last instruction to mark beginning
2390/// and end of a scope respectively. Create an inverse map that list scopes
2391/// starts (and ends) with an instruction. One instruction may start (or end)
2392/// multiple scopes. Ignore scopes that are not reachable.
2393void DwarfDebug::identifyScopeMarkers() {
2394  SmallVector<DbgScope *, 4> WorkList;
2395  WorkList.push_back(CurrentFnDbgScope);
2396  while (!WorkList.empty()) {
2397    DbgScope *S = WorkList.pop_back_val();
2398
2399    const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2400    if (!Children.empty())
2401      for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2402             SE = Children.end(); SI != SE; ++SI)
2403        WorkList.push_back(*SI);
2404
2405    if (S->isAbstractScope())
2406      continue;
2407
2408    const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2409    if (Ranges.empty())
2410      continue;
2411    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2412           RE = Ranges.end(); RI != RE; ++RI) {
2413      assert(RI->first && "DbgRange does not have first instruction!");
2414      assert(RI->second && "DbgRange does not have second instruction!");
2415      InsnsBeginScopeSet.insert(RI->first);
2416      InsnsEndScopeSet.insert(RI->second);
2417    }
2418  }
2419}
2420
2421/// FindFirstDebugLoc - Find the first debug location in the function. This
2422/// is intended to be an approximation for the source position of the
2423/// beginning of the function.
2424static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2425  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2426       I != E; ++I)
2427    for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2428         MBBI != MBBE; ++MBBI) {
2429      DebugLoc DL = MBBI->getDebugLoc();
2430      if (!DL.isUnknown())
2431        return DL;
2432    }
2433  return DebugLoc();
2434}
2435
2436/// beginFunction - Gather pre-function debug information.  Assumes being
2437/// emitted immediately after the function entry point.
2438void DwarfDebug::beginFunction(const MachineFunction *MF) {
2439  if (!MMI->hasDebugInfo()) return;
2440  if (!extractScopeInformation()) return;
2441
2442  collectVariableInfo();
2443
2444  // Assumes in correct section after the entry point.
2445  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_begin",
2446                                                Asm->getFunctionNumber()));
2447
2448  // Emit label for the implicitly defined dbg.stoppoint at the start of the
2449  // function.
2450  DebugLoc FDL = FindFirstDebugLoc(MF);
2451  if (FDL.isUnknown()) return;
2452
2453  MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2454
2455  DISubprogram SP = getDISubprogram(Scope);
2456  unsigned Line, Col;
2457  if (SP.Verify()) {
2458    Line = SP.getLineNumber();
2459    Col = 0;
2460  } else {
2461    Line = FDL.getLine();
2462    Col = FDL.getCol();
2463  }
2464
2465  recordSourceLine(Line, Col, Scope);
2466}
2467
2468/// endFunction - Gather and emit post-function debug information.
2469///
2470void DwarfDebug::endFunction(const MachineFunction *MF) {
2471  if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2472
2473  if (CurrentFnDbgScope) {
2474    // Define end label for subprogram.
2475    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_end",
2476                                                  Asm->getFunctionNumber()));
2477
2478    // Get function line info.
2479    if (!Lines.empty()) {
2480      // Get section line info.
2481      unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2482      if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2483      std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2484      // Append the function info to section info.
2485      SectionLineInfos.insert(SectionLineInfos.end(),
2486                              Lines.begin(), Lines.end());
2487    }
2488
2489    // Construct abstract scopes.
2490    for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2491           AE = AbstractScopesList.end(); AI != AE; ++AI)
2492      constructScopeDIE(*AI);
2493
2494    constructScopeDIE(CurrentFnDbgScope);
2495
2496    DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2497                                                 MMI->getFrameMoves()));
2498  }
2499
2500  // Clear debug info
2501  CurrentFnDbgScope = NULL;
2502  DeleteContainerSeconds(DbgScopeMap);
2503  InsnsBeginScopeSet.clear();
2504  InsnsEndScopeSet.clear();
2505  DbgValueStartMap.clear();
2506  ConcreteScopes.clear();
2507  DeleteContainerSeconds(AbstractScopes);
2508  AbstractScopesList.clear();
2509  AbstractVariables.clear();
2510  InsnBeforeLabelMap.clear();
2511  InsnAfterLabelMap.clear();
2512  Lines.clear();
2513  PrevLabel = NULL;
2514}
2515
2516/// recordSourceLine - Register a source line with debug info. Returns the
2517/// unique label that was emitted and which provides correspondence to
2518/// the source line list.
2519MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, MDNode *S) {
2520  StringRef Dir;
2521  StringRef Fn;
2522
2523  DIDescriptor Scope(S);
2524  if (Scope.isCompileUnit()) {
2525    DICompileUnit CU(S);
2526    Dir = CU.getDirectory();
2527    Fn = CU.getFilename();
2528  } else if (Scope.isSubprogram()) {
2529    DISubprogram SP(S);
2530    Dir = SP.getDirectory();
2531    Fn = SP.getFilename();
2532  } else if (Scope.isLexicalBlock()) {
2533    DILexicalBlock DB(S);
2534    Dir = DB.getDirectory();
2535    Fn = DB.getFilename();
2536  } else
2537    assert(0 && "Unexpected scope info");
2538
2539  unsigned Src = GetOrCreateSourceID(Dir, Fn);
2540  MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2541  Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
2542
2543  Asm->OutStreamer.EmitLabel(Label);
2544  return Label;
2545}
2546
2547//===----------------------------------------------------------------------===//
2548// Emit Methods
2549//===----------------------------------------------------------------------===//
2550
2551/// computeSizeAndOffset - Compute the size and offset of a DIE.
2552///
2553unsigned
2554DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2555  // Get the children.
2556  const std::vector<DIE *> &Children = Die->getChildren();
2557
2558  // If not last sibling and has children then add sibling offset attribute.
2559  if (!Last && !Children.empty())
2560    Die->addSiblingOffset(DIEValueAllocator);
2561
2562  // Record the abbreviation.
2563  assignAbbrevNumber(Die->getAbbrev());
2564
2565  // Get the abbreviation for this DIE.
2566  unsigned AbbrevNumber = Die->getAbbrevNumber();
2567  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2568
2569  // Set DIE offset
2570  Die->setOffset(Offset);
2571
2572  // Start the size with the size of abbreviation code.
2573  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2574
2575  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2576  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2577
2578  // Size the DIE attribute values.
2579  for (unsigned i = 0, N = Values.size(); i < N; ++i)
2580    // Size attribute value.
2581    Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2582
2583  // Size the DIE children if any.
2584  if (!Children.empty()) {
2585    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2586           "Children flag not set");
2587
2588    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2589      Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2590
2591    // End of children marker.
2592    Offset += sizeof(int8_t);
2593  }
2594
2595  Die->setSize(Offset - Die->getOffset());
2596  return Offset;
2597}
2598
2599/// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2600///
2601void DwarfDebug::computeSizeAndOffsets() {
2602  // Compute size of compile unit header.
2603  static unsigned Offset =
2604    sizeof(int32_t) + // Length of Compilation Unit Info
2605    sizeof(int16_t) + // DWARF version number
2606    sizeof(int32_t) + // Offset Into Abbrev. Section
2607    sizeof(int8_t);   // Pointer Size (in bytes)
2608
2609  computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2610}
2611
2612/// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2613/// temporary label to it if SymbolStem is specified.
2614static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2615                                const char *SymbolStem = 0) {
2616  Asm->OutStreamer.SwitchSection(Section);
2617  if (!SymbolStem) return 0;
2618
2619  MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2620  Asm->OutStreamer.EmitLabel(TmpSym);
2621  return TmpSym;
2622}
2623
2624/// EmitSectionLabels - Emit initial Dwarf sections with a label at
2625/// the start of each one.
2626void DwarfDebug::EmitSectionLabels() {
2627  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2628
2629  // Dwarf sections base addresses.
2630  if (Asm->MAI->doesDwarfRequireFrameSection()) {
2631    DwarfFrameSectionSym =
2632      EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2633   }
2634
2635  DwarfInfoSectionSym =
2636    EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2637  DwarfAbbrevSectionSym =
2638    EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2639  EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2640
2641  if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2642    EmitSectionSym(Asm, MacroInfo);
2643
2644  EmitSectionSym(Asm, TLOF.getDwarfLineSection());
2645  EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2646  EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2647  EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2648  DwarfStrSectionSym =
2649    EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2650  DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2651                                             "debug_range");
2652
2653  TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2654  EmitSectionSym(Asm, TLOF.getDataSection());
2655}
2656
2657/// emitDIE - Recusively Emits a debug information entry.
2658///
2659void DwarfDebug::emitDIE(DIE *Die) {
2660  // Get the abbreviation for this DIE.
2661  unsigned AbbrevNumber = Die->getAbbrevNumber();
2662  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2663
2664  // Emit the code (index) for the abbreviation.
2665  if (Asm->isVerbose())
2666    Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2667                                Twine::utohexstr(Die->getOffset()) + ":0x" +
2668                                Twine::utohexstr(Die->getSize()) + " " +
2669                                dwarf::TagString(Abbrev->getTag()));
2670  Asm->EmitULEB128(AbbrevNumber);
2671
2672  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2673  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2674
2675  // Emit the DIE attribute values.
2676  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2677    unsigned Attr = AbbrevData[i].getAttribute();
2678    unsigned Form = AbbrevData[i].getForm();
2679    assert(Form && "Too many attributes for DIE (check abbreviation)");
2680
2681    if (Asm->isVerbose())
2682      Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2683
2684    switch (Attr) {
2685    case dwarf::DW_AT_sibling:
2686      Asm->EmitInt32(Die->getSiblingOffset());
2687      break;
2688    case dwarf::DW_AT_abstract_origin: {
2689      DIEEntry *E = cast<DIEEntry>(Values[i]);
2690      DIE *Origin = E->getEntry();
2691      unsigned Addr = Origin->getOffset();
2692      Asm->EmitInt32(Addr);
2693      break;
2694    }
2695    case dwarf::DW_AT_ranges: {
2696      // DW_AT_range Value encodes offset in debug_range section.
2697      DIEInteger *V = cast<DIEInteger>(Values[i]);
2698      Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2699                                     V->getValue(),
2700                                     DwarfDebugRangeSectionSym,
2701                                     4);
2702      break;
2703    }
2704    default:
2705      // Emit an attribute using the defined form.
2706      Values[i]->EmitValue(Asm, Form);
2707      break;
2708    }
2709  }
2710
2711  // Emit the DIE children if any.
2712  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2713    const std::vector<DIE *> &Children = Die->getChildren();
2714
2715    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2716      emitDIE(Children[j]);
2717
2718    if (Asm->isVerbose())
2719      Asm->OutStreamer.AddComment("End Of Children Mark");
2720    Asm->EmitInt8(0);
2721  }
2722}
2723
2724/// emitDebugInfo - Emit the debug info section.
2725///
2726void DwarfDebug::emitDebugInfo() {
2727  // Start debug info section.
2728  Asm->OutStreamer.SwitchSection(
2729                            Asm->getObjFileLowering().getDwarfInfoSection());
2730  DIE *Die = ModuleCU->getCUDie();
2731
2732  // Emit the compile units header.
2733  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2734                                                ModuleCU->getID()));
2735
2736  // Emit size of content not including length itself
2737  unsigned ContentSize = Die->getSize() +
2738    sizeof(int16_t) + // DWARF version number
2739    sizeof(int32_t) + // Offset Into Abbrev. Section
2740    sizeof(int8_t) +  // Pointer Size (in bytes)
2741    sizeof(int32_t);  // FIXME - extra pad for gdb bug.
2742
2743  Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2744  Asm->EmitInt32(ContentSize);
2745  Asm->OutStreamer.AddComment("DWARF version number");
2746  Asm->EmitInt16(dwarf::DWARF_VERSION);
2747  Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2748  Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2749                         DwarfAbbrevSectionSym);
2750  Asm->OutStreamer.AddComment("Address Size (in bytes)");
2751  Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2752
2753  emitDIE(Die);
2754  // FIXME - extra padding for gdb bug.
2755  Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2756  Asm->EmitInt8(0);
2757  Asm->EmitInt8(0);
2758  Asm->EmitInt8(0);
2759  Asm->EmitInt8(0);
2760  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", ModuleCU->getID()));
2761}
2762
2763/// emitAbbreviations - Emit the abbreviation section.
2764///
2765void DwarfDebug::emitAbbreviations() const {
2766  // Check to see if it is worth the effort.
2767  if (!Abbreviations.empty()) {
2768    // Start the debug abbrev section.
2769    Asm->OutStreamer.SwitchSection(
2770                            Asm->getObjFileLowering().getDwarfAbbrevSection());
2771
2772    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2773
2774    // For each abbrevation.
2775    for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2776      // Get abbreviation data
2777      const DIEAbbrev *Abbrev = Abbreviations[i];
2778
2779      // Emit the abbrevations code (base 1 index.)
2780      Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2781
2782      // Emit the abbreviations data.
2783      Abbrev->Emit(Asm);
2784    }
2785
2786    // Mark end of abbreviations.
2787    Asm->EmitULEB128(0, "EOM(3)");
2788
2789    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2790  }
2791}
2792
2793/// emitEndOfLineMatrix - Emit the last address of the section and the end of
2794/// the line matrix.
2795///
2796void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2797  // Define last address of section.
2798  Asm->OutStreamer.AddComment("Extended Op");
2799  Asm->EmitInt8(0);
2800
2801  Asm->OutStreamer.AddComment("Op size");
2802  Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2803  Asm->OutStreamer.AddComment("DW_LNE_set_address");
2804  Asm->EmitInt8(dwarf::DW_LNE_set_address);
2805
2806  Asm->OutStreamer.AddComment("Section end label");
2807
2808  Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2809                                   Asm->getTargetData().getPointerSize(),
2810                                   0/*AddrSpace*/);
2811
2812  // Mark end of matrix.
2813  Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2814  Asm->EmitInt8(0);
2815  Asm->EmitInt8(1);
2816  Asm->EmitInt8(1);
2817}
2818
2819/// emitDebugLines - Emit source line information.
2820///
2821void DwarfDebug::emitDebugLines() {
2822  // If the target is using .loc/.file, the assembler will be emitting the
2823  // .debug_line table automatically.
2824  if (Asm->MAI->hasDotLocAndDotFile())
2825    return;
2826
2827  // Minimum line delta, thus ranging from -10..(255-10).
2828  const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2829  // Maximum line delta, thus ranging from -10..(255-10).
2830  const int MaxLineDelta = 255 + MinLineDelta;
2831
2832  // Start the dwarf line section.
2833  Asm->OutStreamer.SwitchSection(
2834                            Asm->getObjFileLowering().getDwarfLineSection());
2835
2836  // Construct the section header.
2837  Asm->OutStreamer.AddComment("Length of Source Line Info");
2838  Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
2839                           Asm->GetTempSymbol("line_begin"), 4);
2840  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
2841
2842  Asm->OutStreamer.AddComment("DWARF version number");
2843  Asm->EmitInt16(dwarf::DWARF_VERSION);
2844
2845  Asm->OutStreamer.AddComment("Prolog Length");
2846  Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
2847                           Asm->GetTempSymbol("line_prolog_begin"), 4);
2848  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
2849
2850  Asm->OutStreamer.AddComment("Minimum Instruction Length");
2851  Asm->EmitInt8(1);
2852  Asm->OutStreamer.AddComment("Default is_stmt_start flag");
2853  Asm->EmitInt8(1);
2854  Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
2855  Asm->EmitInt8(MinLineDelta);
2856  Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
2857  Asm->EmitInt8(MaxLineDelta);
2858  Asm->OutStreamer.AddComment("Special Opcode Base");
2859  Asm->EmitInt8(-MinLineDelta);
2860
2861  // Line number standard opcode encodings argument count
2862  Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
2863  Asm->EmitInt8(0);
2864  Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
2865  Asm->EmitInt8(1);
2866  Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
2867  Asm->EmitInt8(1);
2868  Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
2869  Asm->EmitInt8(1);
2870  Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
2871  Asm->EmitInt8(1);
2872  Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
2873  Asm->EmitInt8(0);
2874  Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
2875  Asm->EmitInt8(0);
2876  Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
2877  Asm->EmitInt8(0);
2878  Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
2879  Asm->EmitInt8(1);
2880
2881  // Emit directories.
2882  for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2883    const std::string &Dir = getSourceDirectoryName(DI);
2884    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
2885    Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
2886  }
2887
2888  Asm->OutStreamer.AddComment("End of directories");
2889  Asm->EmitInt8(0);
2890
2891  // Emit files.
2892  for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2893    // Remember source id starts at 1.
2894    std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2895    const std::string &FN = getSourceFileName(Id.second);
2896    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
2897    Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
2898
2899    Asm->EmitULEB128(Id.first, "Directory #");
2900    Asm->EmitULEB128(0, "Mod date");
2901    Asm->EmitULEB128(0, "File size");
2902  }
2903
2904  Asm->OutStreamer.AddComment("End of files");
2905  Asm->EmitInt8(0);
2906
2907  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
2908
2909  // A sequence for each text section.
2910  unsigned SecSrcLinesSize = SectionSourceLines.size();
2911
2912  for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2913    // Isolate current sections line info.
2914    const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2915
2916    // Dwarf assumes we start with first line of first source file.
2917    unsigned Source = 1;
2918    unsigned Line = 1;
2919
2920    // Construct rows of the address, source, line, column matrix.
2921    for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2922      const SrcLineInfo &LineInfo = LineInfos[i];
2923      MCSymbol *Label = LineInfo.getLabel();
2924      if (!Label->isDefined()) continue; // Not emitted, in dead code.
2925
2926      if (LineInfo.getLine() == 0) continue;
2927
2928      if (Asm->isVerbose()) {
2929        std::pair<unsigned, unsigned> SrcID =
2930          getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2931        Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
2932                                    "/" +
2933                                    Twine(getSourceFileName(SrcID.second)) +
2934                                    ":" + Twine(LineInfo.getLine()));
2935      }
2936
2937      // Define the line address.
2938      Asm->OutStreamer.AddComment("Extended Op");
2939      Asm->EmitInt8(0);
2940      Asm->OutStreamer.AddComment("Op size");
2941      Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2942
2943      Asm->OutStreamer.AddComment("DW_LNE_set_address");
2944      Asm->EmitInt8(dwarf::DW_LNE_set_address);
2945
2946      Asm->OutStreamer.AddComment("Location label");
2947      Asm->OutStreamer.EmitSymbolValue(Label,
2948                                       Asm->getTargetData().getPointerSize(),
2949                                       0/*AddrSpace*/);
2950
2951      // If change of source, then switch to the new source.
2952      if (Source != LineInfo.getSourceID()) {
2953        Source = LineInfo.getSourceID();
2954        Asm->OutStreamer.AddComment("DW_LNS_set_file");
2955        Asm->EmitInt8(dwarf::DW_LNS_set_file);
2956        Asm->EmitULEB128(Source, "New Source");
2957      }
2958
2959      // If change of line.
2960      if (Line != LineInfo.getLine()) {
2961        // Determine offset.
2962        int Offset = LineInfo.getLine() - Line;
2963        int Delta = Offset - MinLineDelta;
2964
2965        // Update line.
2966        Line = LineInfo.getLine();
2967
2968        // If delta is small enough and in range...
2969        if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2970          // ... then use fast opcode.
2971          Asm->OutStreamer.AddComment("Line Delta");
2972          Asm->EmitInt8(Delta - MinLineDelta);
2973        } else {
2974          // ... otherwise use long hand.
2975          Asm->OutStreamer.AddComment("DW_LNS_advance_line");
2976          Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2977          Asm->EmitSLEB128(Offset, "Line Offset");
2978          Asm->OutStreamer.AddComment("DW_LNS_copy");
2979          Asm->EmitInt8(dwarf::DW_LNS_copy);
2980        }
2981      } else {
2982        // Copy the previous row (different address or source)
2983        Asm->OutStreamer.AddComment("DW_LNS_copy");
2984        Asm->EmitInt8(dwarf::DW_LNS_copy);
2985      }
2986    }
2987
2988    emitEndOfLineMatrix(j + 1);
2989  }
2990
2991  if (SecSrcLinesSize == 0)
2992    // Because we're emitting a debug_line section, we still need a line
2993    // table. The linker and friends expect it to exist. If there's nothing to
2994    // put into it, emit an empty table.
2995    emitEndOfLineMatrix(1);
2996
2997  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
2998}
2999
3000/// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3001///
3002void DwarfDebug::emitCommonDebugFrame() {
3003  if (!Asm->MAI->doesDwarfRequireFrameSection())
3004    return;
3005
3006  int stackGrowth = Asm->getTargetData().getPointerSize();
3007  if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3008      TargetFrameInfo::StackGrowsDown)
3009    stackGrowth *= -1;
3010
3011  // Start the dwarf frame section.
3012  Asm->OutStreamer.SwitchSection(
3013                              Asm->getObjFileLowering().getDwarfFrameSection());
3014
3015  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3016  Asm->OutStreamer.AddComment("Length of Common Information Entry");
3017  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3018                           Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3019
3020  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3021  Asm->OutStreamer.AddComment("CIE Identifier Tag");
3022  Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3023  Asm->OutStreamer.AddComment("CIE Version");
3024  Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3025  Asm->OutStreamer.AddComment("CIE Augmentation");
3026  Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3027  Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3028  Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3029  Asm->OutStreamer.AddComment("CIE RA Column");
3030  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3031  Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3032
3033  std::vector<MachineMove> Moves;
3034  RI->getInitialFrameState(Moves);
3035
3036  Asm->EmitFrameMoves(Moves, 0, false);
3037
3038  Asm->EmitAlignment(2, 0, 0, false);
3039  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3040}
3041
3042/// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3043/// section.
3044void DwarfDebug::
3045emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3046  if (!Asm->MAI->doesDwarfRequireFrameSection())
3047    return;
3048
3049  // Start the dwarf frame section.
3050  Asm->OutStreamer.SwitchSection(
3051                              Asm->getObjFileLowering().getDwarfFrameSection());
3052
3053  Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3054  MCSymbol *DebugFrameBegin =
3055    Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3056  MCSymbol *DebugFrameEnd =
3057    Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3058  Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3059
3060  Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3061
3062  Asm->OutStreamer.AddComment("FDE CIE offset");
3063  Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3064                         DwarfFrameSectionSym);
3065
3066  Asm->OutStreamer.AddComment("FDE initial location");
3067  MCSymbol *FuncBeginSym =
3068    Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3069  Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3070                                   Asm->getTargetData().getPointerSize(),
3071                                   0/*AddrSpace*/);
3072
3073
3074  Asm->OutStreamer.AddComment("FDE address range");
3075  Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3076                           FuncBeginSym, Asm->getTargetData().getPointerSize());
3077
3078  Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3079
3080  Asm->EmitAlignment(2, 0, 0, false);
3081  Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3082}
3083
3084/// emitDebugPubNames - Emit visible names into a debug pubnames section.
3085///
3086void DwarfDebug::emitDebugPubNames() {
3087  // Start the dwarf pubnames section.
3088  Asm->OutStreamer.SwitchSection(
3089                          Asm->getObjFileLowering().getDwarfPubNamesSection());
3090
3091  Asm->OutStreamer.AddComment("Length of Public Names Info");
3092  Asm->EmitLabelDifference(
3093                 Asm->GetTempSymbol("pubnames_end", ModuleCU->getID()),
3094                 Asm->GetTempSymbol("pubnames_begin", ModuleCU->getID()), 4);
3095
3096  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3097                                                ModuleCU->getID()));
3098
3099  Asm->OutStreamer.AddComment("DWARF Version");
3100  Asm->EmitInt16(dwarf::DWARF_VERSION);
3101
3102  Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3103  Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3104                         DwarfInfoSectionSym);
3105
3106  Asm->OutStreamer.AddComment("Compilation Unit Length");
3107  Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3108                           Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3109                           4);
3110
3111  const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
3112  for (StringMap<DIE*>::const_iterator
3113         GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3114    const char *Name = GI->getKeyData();
3115    DIE *Entity = GI->second;
3116
3117    Asm->OutStreamer.AddComment("DIE offset");
3118    Asm->EmitInt32(Entity->getOffset());
3119
3120    if (Asm->isVerbose())
3121      Asm->OutStreamer.AddComment("External Name");
3122    Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3123  }
3124
3125  Asm->OutStreamer.AddComment("End Mark");
3126  Asm->EmitInt32(0);
3127  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3128                                                ModuleCU->getID()));
3129}
3130
3131void DwarfDebug::emitDebugPubTypes() {
3132  // Start the dwarf pubnames section.
3133  Asm->OutStreamer.SwitchSection(
3134                          Asm->getObjFileLowering().getDwarfPubTypesSection());
3135  Asm->OutStreamer.AddComment("Length of Public Types Info");
3136  Asm->EmitLabelDifference(
3137                    Asm->GetTempSymbol("pubtypes_end", ModuleCU->getID()),
3138                    Asm->GetTempSymbol("pubtypes_begin", ModuleCU->getID()), 4);
3139
3140  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3141                                                ModuleCU->getID()));
3142
3143  if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3144  Asm->EmitInt16(dwarf::DWARF_VERSION);
3145
3146  Asm->OutStreamer.AddComment("Offset of Compilation ModuleCU Info");
3147  Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3148                         DwarfInfoSectionSym);
3149
3150  Asm->OutStreamer.AddComment("Compilation ModuleCU Length");
3151  Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3152                           Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3153                           4);
3154
3155  const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
3156  for (StringMap<DIE*>::const_iterator
3157         GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3158    const char *Name = GI->getKeyData();
3159    DIE * Entity = GI->second;
3160
3161    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3162    Asm->EmitInt32(Entity->getOffset());
3163
3164    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3165    Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3166  }
3167
3168  Asm->OutStreamer.AddComment("End Mark");
3169  Asm->EmitInt32(0);
3170  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3171                                                ModuleCU->getID()));
3172}
3173
3174/// emitDebugStr - Emit visible names into a debug str section.
3175///
3176void DwarfDebug::emitDebugStr() {
3177  // Check to see if it is worth the effort.
3178  if (StringPool.empty()) return;
3179
3180  // Start the dwarf str section.
3181  Asm->OutStreamer.SwitchSection(
3182                                Asm->getObjFileLowering().getDwarfStrSection());
3183
3184  // Get all of the string pool entries and put them in an array by their ID so
3185  // we can sort them.
3186  SmallVector<std::pair<unsigned,
3187      StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3188
3189  for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3190       I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3191    Entries.push_back(std::make_pair(I->second.second, &*I));
3192
3193  array_pod_sort(Entries.begin(), Entries.end());
3194
3195  for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3196    // Emit a label for reference from debug information entries.
3197    Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3198
3199    // Emit the string itself.
3200    Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3201  }
3202}
3203
3204/// emitDebugLoc - Emit visible names into a debug loc section.
3205///
3206void DwarfDebug::emitDebugLoc() {
3207  // Start the dwarf loc section.
3208  Asm->OutStreamer.SwitchSection(
3209                              Asm->getObjFileLowering().getDwarfLocSection());
3210}
3211
3212/// EmitDebugARanges - Emit visible names into a debug aranges section.
3213///
3214void DwarfDebug::EmitDebugARanges() {
3215  // Start the dwarf aranges section.
3216  Asm->OutStreamer.SwitchSection(
3217                          Asm->getObjFileLowering().getDwarfARangesSection());
3218}
3219
3220/// emitDebugRanges - Emit visible names into a debug ranges section.
3221///
3222void DwarfDebug::emitDebugRanges() {
3223  // Start the dwarf ranges section.
3224  Asm->OutStreamer.SwitchSection(
3225    Asm->getObjFileLowering().getDwarfRangesSection());
3226  for (SmallVector<const MCSymbol *, 8>::const_iterator I = DebugRangeSymbols.begin(),
3227         E = DebugRangeSymbols.end(); I != E; ++I) {
3228    if (*I)
3229      Asm->EmitLabelDifference(*I, TextSectionSym,
3230                               Asm->getTargetData().getPointerSize());
3231    else
3232      Asm->OutStreamer.EmitIntValue(0, Asm->getTargetData().getPointerSize(),
3233                                    /*addrspace*/0);
3234  }
3235}
3236
3237/// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3238///
3239void DwarfDebug::emitDebugMacInfo() {
3240  if (const MCSection *LineInfo =
3241      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3242    // Start the dwarf macinfo section.
3243    Asm->OutStreamer.SwitchSection(LineInfo);
3244  }
3245}
3246
3247/// emitDebugInlineInfo - Emit inline info using following format.
3248/// Section Header:
3249/// 1. length of section
3250/// 2. Dwarf version number
3251/// 3. address size.
3252///
3253/// Entries (one "entry" for each function that was inlined):
3254///
3255/// 1. offset into __debug_str section for MIPS linkage name, if exists;
3256///   otherwise offset into __debug_str for regular function name.
3257/// 2. offset into __debug_str section for regular function name.
3258/// 3. an unsigned LEB128 number indicating the number of distinct inlining
3259/// instances for the function.
3260///
3261/// The rest of the entry consists of a {die_offset, low_pc} pair for each
3262/// inlined instance; the die_offset points to the inlined_subroutine die in the
3263/// __debug_info section, and the low_pc is the starting address for the
3264/// inlining instance.
3265void DwarfDebug::emitDebugInlineInfo() {
3266  if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3267    return;
3268
3269  if (!ModuleCU)
3270    return;
3271
3272  Asm->OutStreamer.SwitchSection(
3273                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
3274
3275  Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3276  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3277                           Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3278
3279  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3280
3281  Asm->OutStreamer.AddComment("Dwarf Version");
3282  Asm->EmitInt16(dwarf::DWARF_VERSION);
3283  Asm->OutStreamer.AddComment("Address Size (in bytes)");
3284  Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3285
3286  for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3287         E = InlinedSPNodes.end(); I != E; ++I) {
3288
3289    MDNode *Node = *I;
3290    DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3291      = InlineInfo.find(Node);
3292    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3293    DISubprogram SP(Node);
3294    StringRef LName = SP.getLinkageName();
3295    StringRef Name = SP.getName();
3296
3297    Asm->OutStreamer.AddComment("MIPS linkage name");
3298    if (LName.empty()) {
3299      Asm->OutStreamer.EmitBytes(Name, 0);
3300      Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3301    } else
3302      Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3303                             DwarfStrSectionSym);
3304
3305    Asm->OutStreamer.AddComment("Function name");
3306    Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3307    Asm->EmitULEB128(Labels.size(), "Inline count");
3308
3309    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3310           LE = Labels.end(); LI != LE; ++LI) {
3311      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3312      Asm->EmitInt32(LI->second->getOffset());
3313
3314      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3315      Asm->OutStreamer.EmitSymbolValue(LI->first,
3316                                       Asm->getTargetData().getPointerSize(),0);
3317    }
3318  }
3319
3320  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
3321}
3322