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