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