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