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