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