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