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