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