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