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