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