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