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