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