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