1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
16 #include "DIE.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCSection.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Target/Mangler.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetFrameInfo.h"
28 #include "llvm/Target/TargetLoweringObjectFile.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Analysis/DebugInfo.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/ValueHandle.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/System/Path.h"
42 using namespace llvm;
43 
44 static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
45      cl::desc("Print DbgScope information for each machine instruction"));
46 
47 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
48                                               cl::Hidden,
49      cl::desc("Disable debug info printing"));
50 
51 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
52      cl::desc("Make an absense of debug location information explicit."),
53      cl::init(false));
54 
55 namespace {
56   const char *DWARFGroupName = "DWARF Emission";
57   const char *DbgTimerName = "DWARF Debug Writer";
58 } // end anonymous namespace
59 
60 //===----------------------------------------------------------------------===//
61 
62 /// Configuration values for initial hash set sizes (log2).
63 ///
64 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
65 
66 namespace llvm {
67 
68 //===----------------------------------------------------------------------===//
69 /// CompileUnit - This dwarf writer support class manages information associate
70 /// with a source file.
71 class CompileUnit {
72   /// ID - File identifier for source.
73   ///
74   unsigned ID;
75 
76   /// Die - Compile unit debug information entry.
77   ///
78   const OwningPtr<DIE> CUDie;
79 
80   /// IndexTyDie - An anonymous type for index type.  Owned by CUDie.
81   DIE *IndexTyDie;
82 
83   /// MDNodeToDieMap - Tracks the mapping of unit level debug informaton
84   /// variables to debug information entries.
85   DenseMap<const MDNode *, DIE *> MDNodeToDieMap;
86 
87   /// MDNodeToDIEEntryMap - Tracks the mapping of unit level debug informaton
88   /// descriptors to debug information entries using a DIEEntry proxy.
89   DenseMap<const MDNode *, DIEEntry *> MDNodeToDIEEntryMap;
90 
91   /// Globals - A map of globally visible named entities for this unit.
92   ///
93   StringMap<DIE*> Globals;
94 
95   /// GlobalTypes - A map of globally visible types for this unit.
96   ///
97   StringMap<DIE*> GlobalTypes;
98 
99 public:
100   CompileUnit(unsigned I, DIE *D)
101     : ID(I), CUDie(D), IndexTyDie(0) {}
102 
103   // Accessors.
104   unsigned getID()                  const { return ID; }
105   DIE* getCUDie()                   const { return CUDie.get(); }
106   const StringMap<DIE*> &getGlobals()     const { return Globals; }
107   const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
108 
109   /// hasContent - Return true if this compile unit has something to write out.
110   ///
111   bool hasContent() const { return !CUDie->getChildren().empty(); }
112 
113   /// addGlobal - Add a new global entity to the compile unit.
114   ///
115   void addGlobal(StringRef Name, DIE *Die) { Globals[Name] = Die; }
116 
117   /// addGlobalType - Add a new global type to the compile unit.
118   ///
119   void addGlobalType(StringRef Name, DIE *Die) {
120     GlobalTypes[Name] = Die;
121   }
122 
123   /// getDIE - Returns the debug information entry map slot for the
124   /// specified debug variable.
125   DIE *getDIE(const MDNode *N) { return MDNodeToDieMap.lookup(N); }
126 
127   /// insertDIE - Insert DIE into the map.
128   void insertDIE(const MDNode *N, DIE *D) {
129     MDNodeToDieMap.insert(std::make_pair(N, D));
130   }
131 
132   /// getDIEEntry - Returns the debug information entry for the speciefied
133   /// debug variable.
134   DIEEntry *getDIEEntry(const MDNode *N) {
135     DenseMap<const MDNode *, DIEEntry *>::iterator I =
136       MDNodeToDIEEntryMap.find(N);
137     if (I == MDNodeToDIEEntryMap.end())
138       return NULL;
139     return I->second;
140   }
141 
142   /// insertDIEEntry - Insert debug information entry into the map.
143   void insertDIEEntry(const MDNode *N, DIEEntry *E) {
144     MDNodeToDIEEntryMap.insert(std::make_pair(N, E));
145   }
146 
147   /// addDie - Adds or interns the DIE to the compile unit.
148   ///
149   void addDie(DIE *Buffer) {
150     this->CUDie->addChild(Buffer);
151   }
152 
153   // getIndexTyDie - Get an anonymous type for index type.
154   DIE *getIndexTyDie() {
155     return IndexTyDie;
156   }
157 
158   // setIndexTyDie - Set D as anonymous type for index which can be reused
159   // later.
160   void setIndexTyDie(DIE *D) {
161     IndexTyDie = D;
162   }
163 
164 };
165 
166 //===----------------------------------------------------------------------===//
167 /// DbgVariable - This class is used to track local variable information.
168 ///
169 class DbgVariable {
170   DIVariable Var;                    // Variable Descriptor.
171   DIE *TheDIE;                       // Variable DIE.
172   unsigned DotDebugLocOffset;        // Offset in DotDebugLocEntries.
173 public:
174   // AbsVar may be NULL.
175   DbgVariable(DIVariable V) : Var(V), TheDIE(0), DotDebugLocOffset(~0U) {}
176 
177   // Accessors.
178   DIVariable getVariable()           const { return Var; }
179   void setDIE(DIE *D)                      { TheDIE = D; }
180   DIE *getDIE()                      const { return TheDIE; }
181   void setDotDebugLocOffset(unsigned O)    { DotDebugLocOffset = O; }
182   unsigned getDotDebugLocOffset()    const { return DotDebugLocOffset; }
183   StringRef getName()                const { return Var.getName(); }
184   unsigned getTag()                  const { return Var.getTag(); }
185   bool variableHasComplexAddress()   const {
186     assert(Var.Verify() && "Invalid complex DbgVariable!");
187     return Var.hasComplexAddress();
188   }
189   bool isBlockByrefVariable()        const {
190     assert(Var.Verify() && "Invalid complex DbgVariable!");
191     return Var.isBlockByrefVariable();
192   }
193   unsigned getNumAddrElements()      const {
194     assert(Var.Verify() && "Invalid complex DbgVariable!");
195     return Var.getNumAddrElements();
196   }
197   uint64_t getAddrElement(unsigned i) const {
198     return Var.getAddrElement(i);
199   }
200   DIType getType()               const {
201     DIType Ty = Var.getType();
202     // FIXME: isBlockByrefVariable should be reformulated in terms of complex
203     // addresses instead.
204     if (Var.isBlockByrefVariable()) {
205       /* Byref variables, in Blocks, are declared by the programmer as
206          "SomeType VarName;", but the compiler creates a
207          __Block_byref_x_VarName struct, and gives the variable VarName
208          either the struct, or a pointer to the struct, as its type.  This
209          is necessary for various behind-the-scenes things the compiler
210          needs to do with by-reference variables in blocks.
211 
212          However, as far as the original *programmer* is concerned, the
213          variable should still have type 'SomeType', as originally declared.
214 
215          The following function dives into the __Block_byref_x_VarName
216          struct to find the original type of the variable.  This will be
217          passed back to the code generating the type for the Debug
218          Information Entry for the variable 'VarName'.  'VarName' will then
219          have the original type 'SomeType' in its debug information.
220 
221          The original type 'SomeType' will be the type of the field named
222          'VarName' inside the __Block_byref_x_VarName struct.
223 
224          NOTE: In order for this to not completely fail on the debugger
225          side, the Debug Information Entry for the variable VarName needs to
226          have a DW_AT_location that tells the debugger how to unwind through
227          the pointers and __Block_byref_x_VarName struct to find the actual
228          value of the variable.  The function addBlockByrefType does this.  */
229       DIType subType = Ty;
230       unsigned tag = Ty.getTag();
231 
232       if (tag == dwarf::DW_TAG_pointer_type) {
233         DIDerivedType DTy = DIDerivedType(Ty);
234         subType = DTy.getTypeDerivedFrom();
235       }
236 
237       DICompositeType blockStruct = DICompositeType(subType);
238       DIArray Elements = blockStruct.getTypeArray();
239 
240       for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
241         DIDescriptor Element = Elements.getElement(i);
242         DIDerivedType DT = DIDerivedType(Element);
243         if (getName() == DT.getName())
244           return (DT.getTypeDerivedFrom());
245       }
246       return Ty;
247     }
248     return Ty;
249   }
250 };
251 
252 //===----------------------------------------------------------------------===//
253 /// DbgRange - This is used to track range of instructions with identical
254 /// debug info scope.
255 ///
256 typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
257 
258 //===----------------------------------------------------------------------===//
259 /// DbgScope - This class is used to track scope information.
260 ///
261 class DbgScope {
262   DbgScope *Parent;                   // Parent to this scope.
263   DIDescriptor Desc;                  // Debug info descriptor for scope.
264   // Location at which this scope is inlined.
265   AssertingVH<const MDNode> InlinedAtLocation;
266   bool AbstractScope;                 // Abstract Scope
267   const MachineInstr *LastInsn;       // Last instruction of this scope.
268   const MachineInstr *FirstInsn;      // First instruction of this scope.
269   unsigned DFSIn, DFSOut;
270   // Scopes defined in scope.  Contents not owned.
271   SmallVector<DbgScope *, 4> Scopes;
272   // Variables declared in scope.  Contents owned.
273   SmallVector<DbgVariable *, 8> Variables;
274   SmallVector<DbgRange, 4> Ranges;
275   // Private state for dump()
276   mutable unsigned IndentLevel;
277 public:
278   DbgScope(DbgScope *P, DIDescriptor D, const MDNode *I = 0)
279     : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
280       LastInsn(0), FirstInsn(0),
281       DFSIn(0), DFSOut(0), IndentLevel(0) {}
282   virtual ~DbgScope();
283 
284   // Accessors.
285   DbgScope *getParent()          const { return Parent; }
286   void setParent(DbgScope *P)          { Parent = P; }
287   DIDescriptor getDesc()         const { return Desc; }
288   const MDNode *getInlinedAt()         const { return InlinedAtLocation; }
289   const MDNode *getScopeNode()         const { return Desc; }
290   const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
291   const SmallVector<DbgVariable *, 8> &getDbgVariables() { return Variables; }
292   const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
293 
294   /// openInsnRange - This scope covers instruction range starting from MI.
295   void openInsnRange(const MachineInstr *MI) {
296     if (!FirstInsn)
297       FirstInsn = MI;
298 
299     if (Parent)
300       Parent->openInsnRange(MI);
301   }
302 
303   /// extendInsnRange - Extend the current instruction range covered by
304   /// this scope.
305   void extendInsnRange(const MachineInstr *MI) {
306     assert (FirstInsn && "MI Range is not open!");
307     LastInsn = MI;
308     if (Parent)
309       Parent->extendInsnRange(MI);
310   }
311 
312   /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
313   /// until now. This is used when a new scope is encountered while walking
314   /// machine instructions.
315   void closeInsnRange(DbgScope *NewScope = NULL) {
316     assert (LastInsn && "Last insn missing!");
317     Ranges.push_back(DbgRange(FirstInsn, LastInsn));
318     FirstInsn = NULL;
319     LastInsn = NULL;
320     // If Parent dominates NewScope then do not close Parent's instruction
321     // range.
322     if (Parent && (!NewScope || !Parent->dominates(NewScope)))
323       Parent->closeInsnRange(NewScope);
324   }
325 
326   void setAbstractScope() { AbstractScope = true; }
327   bool isAbstractScope() const { return AbstractScope; }
328 
329   // Depth First Search support to walk and mainpluate DbgScope hierarchy.
330   unsigned getDFSOut() const { return DFSOut; }
331   void setDFSOut(unsigned O) { DFSOut = O; }
332   unsigned getDFSIn() const  { return DFSIn; }
333   void setDFSIn(unsigned I)  { DFSIn = I; }
334   bool dominates(const DbgScope *S) {
335     if (S == this)
336       return true;
337     if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
338       return true;
339     return false;
340   }
341 
342   /// addScope - Add a scope to the scope.
343   ///
344   void addScope(DbgScope *S) { Scopes.push_back(S); }
345 
346   /// addVariable - Add a variable to the scope.
347   ///
348   void addVariable(DbgVariable *V) { Variables.push_back(V); }
349 
350 #ifndef NDEBUG
351   void dump() const;
352 #endif
353 };
354 
355 } // end llvm namespace
356 
357 #ifndef NDEBUG
358 void DbgScope::dump() const {
359   raw_ostream &err = dbgs();
360   err.indent(IndentLevel);
361   const MDNode *N = Desc;
362   N->dump();
363   if (AbstractScope)
364     err << "Abstract Scope\n";
365 
366   IndentLevel += 2;
367   if (!Scopes.empty())
368     err << "Children ...\n";
369   for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
370     if (Scopes[i] != this)
371       Scopes[i]->dump();
372 
373   IndentLevel -= 2;
374 }
375 #endif
376 
377 DbgScope::~DbgScope() {
378   for (unsigned j = 0, M = Variables.size(); j < M; ++j)
379     delete Variables[j];
380 }
381 
382 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
383   : Asm(A), MMI(Asm->MMI), FirstCU(0),
384     AbbreviationsSet(InitAbbreviationsSetSize),
385     CurrentFnDbgScope(0), PrevLabel(NULL) {
386   NextStringPoolNumber = 0;
387 
388   DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
389   DwarfStrSectionSym = TextSectionSym = 0;
390   DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
391   FunctionBeginSym = FunctionEndSym = 0;
392   DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
393   {
394     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
395     beginModule(M);
396   }
397 }
398 DwarfDebug::~DwarfDebug() {
399   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
400     DIEBlocks[j]->~DIEBlock();
401 }
402 
403 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
404   std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
405   if (Entry.first) return Entry.first;
406 
407   Entry.second = NextStringPoolNumber++;
408   return Entry.first = Asm->GetTempSymbol("string", Entry.second);
409 }
410 
411 
412 /// assignAbbrevNumber - Define a unique number for the abbreviation.
413 ///
414 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
415   // Profile the node so that we can make it unique.
416   FoldingSetNodeID ID;
417   Abbrev.Profile(ID);
418 
419   // Check the set for priors.
420   DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
421 
422   // If it's newly added.
423   if (InSet == &Abbrev) {
424     // Add to abbreviation list.
425     Abbreviations.push_back(&Abbrev);
426 
427     // Assign the vector position + 1 as its number.
428     Abbrev.setNumber(Abbreviations.size());
429   } else {
430     // Assign existing abbreviation number.
431     Abbrev.setNumber(InSet->getNumber());
432   }
433 }
434 
435 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
436 /// information entry.
437 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
438   DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
439   return Value;
440 }
441 
442 /// addUInt - Add an unsigned integer attribute data and value.
443 ///
444 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
445                          unsigned Form, uint64_t Integer) {
446   if (!Form) Form = DIEInteger::BestForm(false, Integer);
447   DIEValue *Value = Integer == 1 ?
448     DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
449   Die->addValue(Attribute, Form, Value);
450 }
451 
452 /// addSInt - Add an signed integer attribute data and value.
453 ///
454 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
455                          unsigned Form, int64_t Integer) {
456   if (!Form) Form = DIEInteger::BestForm(true, Integer);
457   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
458   Die->addValue(Attribute, Form, Value);
459 }
460 
461 /// addString - Add a string attribute data and value. DIEString only
462 /// keeps string reference.
463 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
464                            StringRef String) {
465   DIEValue *Value = new (DIEValueAllocator) DIEString(String);
466   Die->addValue(Attribute, Form, Value);
467 }
468 
469 /// addLabel - Add a Dwarf label attribute data and value.
470 ///
471 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
472                           const MCSymbol *Label) {
473   DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
474   Die->addValue(Attribute, Form, Value);
475 }
476 
477 /// addDelta - Add a label delta attribute data and value.
478 ///
479 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
480                           const MCSymbol *Hi, const MCSymbol *Lo) {
481   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
482   Die->addValue(Attribute, Form, Value);
483 }
484 
485 /// addDIEEntry - Add a DIE attribute data and value.
486 ///
487 void DwarfDebug::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
488                              DIE *Entry) {
489   Die->addValue(Attribute, Form, createDIEEntry(Entry));
490 }
491 
492 
493 /// addBlock - Add block data.
494 ///
495 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
496                           DIEBlock *Block) {
497   Block->ComputeSize(Asm);
498   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
499   Die->addValue(Attribute, Block->BestForm(), Block);
500 }
501 
502 /// addSourceLine - Add location information to specified debug information
503 /// entry.
504 void DwarfDebug::addSourceLine(DIE *Die, DIVariable V) {
505   // Verify variable.
506   if (!V.Verify())
507     return;
508 
509   unsigned Line = V.getLineNumber();
510   if (Line == 0)
511     return;
512   unsigned FileID = GetOrCreateSourceID(V.getContext().getDirectory(),
513                                         V.getContext().getFilename());
514   assert(FileID && "Invalid file id");
515   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
516   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
517 }
518 
519 /// addSourceLine - Add location information to specified debug information
520 /// entry.
521 void DwarfDebug::addSourceLine(DIE *Die, DIGlobalVariable G) {
522   // Verify global variable.
523   if (!G.Verify())
524     return;
525 
526   unsigned Line = G.getLineNumber();
527   if (Line == 0)
528     return;
529   unsigned FileID = GetOrCreateSourceID(G.getContext().getDirectory(),
530                                         G.getContext().getFilename());
531   assert(FileID && "Invalid file id");
532   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
533   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
534 }
535 
536 /// addSourceLine - Add location information to specified debug information
537 /// entry.
538 void DwarfDebug::addSourceLine(DIE *Die, DISubprogram SP) {
539   // Verify subprogram.
540   if (!SP.Verify())
541     return;
542   // If the line number is 0, don't add it.
543   if (SP.getLineNumber() == 0)
544     return;
545 
546   unsigned Line = SP.getLineNumber();
547   if (!SP.getContext().Verify())
548     return;
549   unsigned FileID = GetOrCreateSourceID(SP.getDirectory(),
550                                         SP.getFilename());
551   assert(FileID && "Invalid file id");
552   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
553   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
554 }
555 
556 /// addSourceLine - Add location information to specified debug information
557 /// entry.
558 void DwarfDebug::addSourceLine(DIE *Die, DIType Ty) {
559   // Verify type.
560   if (!Ty.Verify())
561     return;
562 
563   unsigned Line = Ty.getLineNumber();
564   if (Line == 0 || !Ty.getContext().Verify())
565     return;
566   unsigned FileID = GetOrCreateSourceID(Ty.getContext().getDirectory(),
567                                         Ty.getContext().getFilename());
568   assert(FileID && "Invalid file id");
569   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
570   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
571 }
572 
573 /// addSourceLine - Add location information to specified debug information
574 /// entry.
575 void DwarfDebug::addSourceLine(DIE *Die, DINameSpace NS) {
576   // Verify namespace.
577   if (!NS.Verify())
578     return;
579 
580   unsigned Line = NS.getLineNumber();
581   if (Line == 0)
582     return;
583   StringRef FN = NS.getFilename();
584   StringRef Dir = NS.getDirectory();
585 
586   unsigned FileID = GetOrCreateSourceID(Dir, FN);
587   assert(FileID && "Invalid file id");
588   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
589   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
590 }
591 
592 /// addVariableAddress - Add DW_AT_location attribute for a DbgVariable based
593 /// on provided frame index.
594 void DwarfDebug::addVariableAddress(DbgVariable *&DV, DIE *Die, int64_t FI) {
595   MachineLocation Location;
596   unsigned FrameReg;
597   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
598   int Offset = RI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
599   Location.set(FrameReg, Offset);
600 
601   if (DV->variableHasComplexAddress())
602     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
603   else if (DV->isBlockByrefVariable())
604     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
605   else
606     addAddress(Die, dwarf::DW_AT_location, Location);
607 }
608 
609 /// addComplexAddress - Start with the address based on the location provided,
610 /// and generate the DWARF information necessary to find the actual variable
611 /// given the extra address information encoded in the DIVariable, starting from
612 /// the starting location.  Add the DWARF information to the die.
613 ///
614 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
615                                    unsigned Attribute,
616                                    const MachineLocation &Location) {
617   DIType Ty = DV->getType();
618 
619   // Decode the original location, and use that as the start of the byref
620   // variable's location.
621   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
622   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
623   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
624 
625   if (Location.isReg()) {
626     if (Reg < 32) {
627       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
628     } else {
629       Reg = Reg - dwarf::DW_OP_reg0;
630       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
631       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
632     }
633   } else {
634     if (Reg < 32)
635       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
636     else {
637       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
638       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
639     }
640 
641     addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
642   }
643 
644   for (unsigned i = 0, N = DV->getNumAddrElements(); i < N; ++i) {
645     uint64_t Element = DV->getAddrElement(i);
646 
647     if (Element == DIFactory::OpPlus) {
648       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
649       addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
650     } else if (Element == DIFactory::OpDeref) {
651       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
652     } else llvm_unreachable("unknown DIFactory Opcode");
653   }
654 
655   // Now attach the location information to the DIE.
656   addBlock(Die, Attribute, 0, Block);
657 }
658 
659 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
660    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
661    gives the variable VarName either the struct, or a pointer to the struct, as
662    its type.  This is necessary for various behind-the-scenes things the
663    compiler needs to do with by-reference variables in Blocks.
664 
665    However, as far as the original *programmer* is concerned, the variable
666    should still have type 'SomeType', as originally declared.
667 
668    The function getBlockByrefType dives into the __Block_byref_x_VarName
669    struct to find the original type of the variable, which is then assigned to
670    the variable's Debug Information Entry as its real type.  So far, so good.
671    However now the debugger will expect the variable VarName to have the type
672    SomeType.  So we need the location attribute for the variable to be an
673    expression that explains to the debugger how to navigate through the
674    pointers and struct to find the actual variable of type SomeType.
675 
676    The following function does just that.  We start by getting
677    the "normal" location for the variable. This will be the location
678    of either the struct __Block_byref_x_VarName or the pointer to the
679    struct __Block_byref_x_VarName.
680 
681    The struct will look something like:
682 
683    struct __Block_byref_x_VarName {
684      ... <various fields>
685      struct __Block_byref_x_VarName *forwarding;
686      ... <various other fields>
687      SomeType VarName;
688      ... <maybe more fields>
689    };
690 
691    If we are given the struct directly (as our starting point) we
692    need to tell the debugger to:
693 
694    1).  Add the offset of the forwarding field.
695 
696    2).  Follow that pointer to get the real __Block_byref_x_VarName
697    struct to use (the real one may have been copied onto the heap).
698 
699    3).  Add the offset for the field VarName, to find the actual variable.
700 
701    If we started with a pointer to the struct, then we need to
702    dereference that pointer first, before the other steps.
703    Translating this into DWARF ops, we will need to append the following
704    to the current location description for the variable:
705 
706    DW_OP_deref                    -- optional, if we start with a pointer
707    DW_OP_plus_uconst <forward_fld_offset>
708    DW_OP_deref
709    DW_OP_plus_uconst <varName_fld_offset>
710 
711    That is what this function does.  */
712 
713 /// addBlockByrefAddress - Start with the address based on the location
714 /// provided, and generate the DWARF information necessary to find the
715 /// actual Block variable (navigating the Block struct) based on the
716 /// starting location.  Add the DWARF information to the die.  For
717 /// more information, read large comment just above here.
718 ///
719 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
720                                       unsigned Attribute,
721                                       const MachineLocation &Location) {
722   DIType Ty = DV->getType();
723   DIType TmpTy = Ty;
724   unsigned Tag = Ty.getTag();
725   bool isPointer = false;
726 
727   StringRef varName = DV->getName();
728 
729   if (Tag == dwarf::DW_TAG_pointer_type) {
730     DIDerivedType DTy = DIDerivedType(Ty);
731     TmpTy = DTy.getTypeDerivedFrom();
732     isPointer = true;
733   }
734 
735   DICompositeType blockStruct = DICompositeType(TmpTy);
736 
737   // Find the __forwarding field and the variable field in the __Block_byref
738   // struct.
739   DIArray Fields = blockStruct.getTypeArray();
740   DIDescriptor varField = DIDescriptor();
741   DIDescriptor forwardingField = DIDescriptor();
742 
743   for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
744     DIDescriptor Element = Fields.getElement(i);
745     DIDerivedType DT = DIDerivedType(Element);
746     StringRef fieldName = DT.getName();
747     if (fieldName == "__forwarding")
748       forwardingField = Element;
749     else if (fieldName == varName)
750       varField = Element;
751   }
752 
753   // Get the offsets for the forwarding field and the variable field.
754   unsigned forwardingFieldOffset =
755     DIDerivedType(forwardingField).getOffsetInBits() >> 3;
756   unsigned varFieldOffset =
757     DIDerivedType(varField).getOffsetInBits() >> 3;
758 
759   // Decode the original location, and use that as the start of the byref
760   // variable's location.
761   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
762   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
763   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
764 
765   if (Location.isReg()) {
766     if (Reg < 32)
767       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
768     else {
769       Reg = Reg - dwarf::DW_OP_reg0;
770       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
771       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
772     }
773   } else {
774     if (Reg < 32)
775       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
776     else {
777       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
778       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
779     }
780 
781     addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
782   }
783 
784   // If we started with a pointer to the __Block_byref... struct, then
785   // the first thing we need to do is dereference the pointer (DW_OP_deref).
786   if (isPointer)
787     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
788 
789   // Next add the offset for the '__forwarding' field:
790   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
791   // adding the offset if it's 0.
792   if (forwardingFieldOffset > 0) {
793     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
794     addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
795   }
796 
797   // Now dereference the __forwarding field to get to the real __Block_byref
798   // struct:  DW_OP_deref.
799   addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
800 
801   // Now that we've got the real __Block_byref... struct, add the offset
802   // for the variable's field to get to the location of the actual variable:
803   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
804   if (varFieldOffset > 0) {
805     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
806     addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
807   }
808 
809   // Now attach the location information to the DIE.
810   addBlock(Die, Attribute, 0, Block);
811 }
812 
813 /// addAddress - Add an address attribute to a die based on the location
814 /// provided.
815 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
816                             const MachineLocation &Location) {
817   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
818   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
819   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
820   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
821 
822   if (TRI->getFrameRegister(*Asm->MF) == Location.getReg()
823       && Location.getOffset()) {
824     // If variable offset is based in frame register then use fbreg.
825     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
826     addSInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
827     addBlock(Die, Attribute, 0, Block);
828     return;
829   }
830 
831   if (Location.isReg()) {
832     if (Reg < 32) {
833       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
834     } else {
835       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
836       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
837     }
838   } else {
839     if (Reg < 32) {
840       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
841     } else {
842       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
843       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
844     }
845 
846     addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
847   }
848 
849   addBlock(Die, Attribute, 0, Block);
850 }
851 
852 /// addRegisterAddress - Add register location entry in variable DIE.
853 bool DwarfDebug::addRegisterAddress(DIE *Die, const MCSymbol *VS,
854                                     const MachineOperand &MO) {
855   assert (MO.isReg() && "Invalid machine operand!");
856   if (!MO.getReg())
857     return false;
858   MachineLocation Location;
859   Location.set(MO.getReg());
860   addAddress(Die, dwarf::DW_AT_location, Location);
861   if (VS)
862     addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
863   return true;
864 }
865 
866 /// addConstantValue - Add constant value entry in variable DIE.
867 bool DwarfDebug::addConstantValue(DIE *Die, const MCSymbol *VS,
868                                   const MachineOperand &MO) {
869   assert (MO.isImm() && "Invalid machine operand!");
870   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
871   unsigned Imm = MO.getImm();
872   addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
873   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
874   if (VS)
875     addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
876   return true;
877 }
878 
879 /// addConstantFPValue - Add constant value entry in variable DIE.
880 bool DwarfDebug::addConstantFPValue(DIE *Die, const MCSymbol *VS,
881                                     const MachineOperand &MO) {
882   assert (MO.isFPImm() && "Invalid machine operand!");
883   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
884   APFloat FPImm = MO.getFPImm()->getValueAPF();
885 
886   // Get the raw data form of the floating point.
887   const APInt FltVal = FPImm.bitcastToAPInt();
888   const char *FltPtr = (const char*)FltVal.getRawData();
889 
890   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
891   bool LittleEndian = Asm->getTargetData().isLittleEndian();
892   int Incr = (LittleEndian ? 1 : -1);
893   int Start = (LittleEndian ? 0 : NumBytes - 1);
894   int Stop = (LittleEndian ? NumBytes : -1);
895 
896   // Output the constant to DWARF one byte at a time.
897   for (; Start != Stop; Start += Incr)
898     addUInt(Block, 0, dwarf::DW_FORM_data1,
899             (unsigned char)0xFF & FltPtr[Start]);
900 
901   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
902   if (VS)
903     addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
904   return true;
905 }
906 
907 
908 /// addToContextOwner - Add Die into the list of its context owner's children.
909 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
910   if (Context.isType()) {
911     DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
912     ContextDIE->addChild(Die);
913   } else if (Context.isNameSpace()) {
914     DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
915     ContextDIE->addChild(Die);
916   } else if (Context.isSubprogram()) {
917     DIE *ContextDIE = createSubprogramDIE(DISubprogram(Context));
918     ContextDIE->addChild(Die);
919   } else if (DIE *ContextDIE = getCompileUnit(Context)->getDIE(Context))
920     ContextDIE->addChild(Die);
921   else
922     getCompileUnit(Context)->addDie(Die);
923 }
924 
925 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
926 /// given DIType.
927 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
928   CompileUnit *TypeCU = getCompileUnit(Ty);
929   DIE *TyDIE = TypeCU->getDIE(Ty);
930   if (TyDIE)
931     return TyDIE;
932 
933   // Create new type.
934   TyDIE = new DIE(dwarf::DW_TAG_base_type);
935   TypeCU->insertDIE(Ty, TyDIE);
936   if (Ty.isBasicType())
937     constructTypeDIE(*TyDIE, DIBasicType(Ty));
938   else if (Ty.isCompositeType())
939     constructTypeDIE(*TyDIE, DICompositeType(Ty));
940   else {
941     assert(Ty.isDerivedType() && "Unknown kind of DIType");
942     constructTypeDIE(*TyDIE, DIDerivedType(Ty));
943   }
944 
945   addToContextOwner(TyDIE, Ty.getContext());
946   return TyDIE;
947 }
948 
949 /// addType - Add a new type attribute to the specified entity.
950 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
951   if (!Ty.Verify())
952     return;
953 
954   // Check for pre-existence.
955   CompileUnit *TypeCU = getCompileUnit(Ty);
956   DIEEntry *Entry = TypeCU->getDIEEntry(Ty);
957   // If it exists then use the existing value.
958   if (Entry) {
959     Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
960     return;
961   }
962 
963   // Construct type.
964   DIE *Buffer = getOrCreateTypeDIE(Ty);
965 
966   // Set up proxy.
967   Entry = createDIEEntry(Buffer);
968   TypeCU->insertDIEEntry(Ty, Entry);
969 
970   Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
971 }
972 
973 /// constructTypeDIE - Construct basic type die from DIBasicType.
974 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
975   // Get core information.
976   StringRef Name = BTy.getName();
977   Buffer.setTag(dwarf::DW_TAG_base_type);
978   addUInt(&Buffer, dwarf::DW_AT_encoding,  dwarf::DW_FORM_data1,
979           BTy.getEncoding());
980 
981   // Add name if not anonymous or intermediate type.
982   if (!Name.empty())
983     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
984   uint64_t Size = BTy.getSizeInBits() >> 3;
985   addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
986 }
987 
988 /// constructTypeDIE - Construct derived type die from DIDerivedType.
989 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
990   // Get core information.
991   StringRef Name = DTy.getName();
992   uint64_t Size = DTy.getSizeInBits() >> 3;
993   unsigned Tag = DTy.getTag();
994 
995   // FIXME - Workaround for templates.
996   if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
997 
998   Buffer.setTag(Tag);
999 
1000   // Map to main type, void will not have a type.
1001   DIType FromTy = DTy.getTypeDerivedFrom();
1002   addType(&Buffer, FromTy);
1003 
1004   // Add name if not anonymous or intermediate type.
1005   if (!Name.empty())
1006     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1007 
1008   // Add size if non-zero (derived types might be zero-sized.)
1009   if (Size)
1010     addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1011 
1012   // Add source line info if available and TyDesc is not a forward declaration.
1013   if (!DTy.isForwardDecl())
1014     addSourceLine(&Buffer, DTy);
1015 }
1016 
1017 /// constructTypeDIE - Construct type DIE from DICompositeType.
1018 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1019   // Get core information.
1020   StringRef Name = CTy.getName();
1021 
1022   uint64_t Size = CTy.getSizeInBits() >> 3;
1023   unsigned Tag = CTy.getTag();
1024   Buffer.setTag(Tag);
1025 
1026   switch (Tag) {
1027   case dwarf::DW_TAG_vector_type:
1028   case dwarf::DW_TAG_array_type:
1029     constructArrayTypeDIE(Buffer, &CTy);
1030     break;
1031   case dwarf::DW_TAG_enumeration_type: {
1032     DIArray Elements = CTy.getTypeArray();
1033 
1034     // Add enumerators to enumeration type.
1035     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1036       DIE *ElemDie = NULL;
1037       DIDescriptor Enum(Elements.getElement(i));
1038       if (Enum.isEnumerator()) {
1039         ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
1040         Buffer.addChild(ElemDie);
1041       }
1042     }
1043   }
1044     break;
1045   case dwarf::DW_TAG_subroutine_type: {
1046     // Add return type.
1047     DIArray Elements = CTy.getTypeArray();
1048     DIDescriptor RTy = Elements.getElement(0);
1049     addType(&Buffer, DIType(RTy));
1050 
1051     bool isPrototyped = true;
1052     // Add arguments.
1053     for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1054       DIDescriptor Ty = Elements.getElement(i);
1055       if (Ty.isUnspecifiedParameter()) {
1056         DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
1057         Buffer.addChild(Arg);
1058         isPrototyped = false;
1059       } else {
1060         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1061         addType(Arg, DIType(Ty));
1062         Buffer.addChild(Arg);
1063       }
1064     }
1065     // Add prototype flag.
1066     if (isPrototyped)
1067       addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1068   }
1069     break;
1070   case dwarf::DW_TAG_structure_type:
1071   case dwarf::DW_TAG_union_type:
1072   case dwarf::DW_TAG_class_type: {
1073     // Add elements to structure type.
1074     DIArray Elements = CTy.getTypeArray();
1075 
1076     // A forward struct declared type may not have elements available.
1077     unsigned N = Elements.getNumElements();
1078     if (N == 0)
1079       break;
1080 
1081     // Add elements to structure type.
1082     for (unsigned i = 0; i < N; ++i) {
1083       DIDescriptor Element = Elements.getElement(i);
1084       DIE *ElemDie = NULL;
1085       if (Element.isSubprogram()) {
1086         DISubprogram SP(Element);
1087         ElemDie = createSubprogramDIE(DISubprogram(Element));
1088         if (SP.isProtected())
1089           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1090                   dwarf::DW_ACCESS_protected);
1091         else if (SP.isPrivate())
1092           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1093                   dwarf::DW_ACCESS_private);
1094         else
1095           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1096             dwarf::DW_ACCESS_public);
1097         if (SP.isExplicit())
1098           addUInt(ElemDie, dwarf::DW_AT_explicit, dwarf::DW_FORM_flag, 1);
1099       }
1100       else if (Element.isVariable()) {
1101         DIVariable DV(Element);
1102         ElemDie = new DIE(dwarf::DW_TAG_variable);
1103         addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1104                   DV.getName());
1105         addType(ElemDie, DV.getType());
1106         addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1107         addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1108         addSourceLine(ElemDie, DV);
1109       } else if (Element.isDerivedType())
1110         ElemDie = createMemberDIE(DIDerivedType(Element));
1111       else
1112         continue;
1113       Buffer.addChild(ElemDie);
1114     }
1115 
1116     if (CTy.isAppleBlockExtension())
1117       addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1118 
1119     unsigned RLang = CTy.getRunTimeLang();
1120     if (RLang)
1121       addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1122               dwarf::DW_FORM_data1, RLang);
1123 
1124     DICompositeType ContainingType = CTy.getContainingType();
1125     if (DIDescriptor(ContainingType).isCompositeType())
1126       addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1127                   getOrCreateTypeDIE(DIType(ContainingType)));
1128     else {
1129       DIDescriptor Context = CTy.getContext();
1130       addToContextOwner(&Buffer, Context);
1131     }
1132     break;
1133   }
1134   default:
1135     break;
1136   }
1137 
1138   // Add name if not anonymous or intermediate type.
1139   if (!Name.empty())
1140     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1141 
1142   if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type
1143       || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1144     {
1145     // Add size if non-zero (derived types might be zero-sized.)
1146     if (Size)
1147       addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1148     else {
1149       // Add zero size if it is not a forward declaration.
1150       if (CTy.isForwardDecl())
1151         addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1152       else
1153         addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1154     }
1155 
1156     // Add source line info if available.
1157     if (!CTy.isForwardDecl())
1158       addSourceLine(&Buffer, CTy);
1159   }
1160 }
1161 
1162 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1163 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1164   int64_t L = SR.getLo();
1165   int64_t H = SR.getHi();
1166   DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1167 
1168   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1169   if (L)
1170     addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1171   addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1172 
1173   Buffer.addChild(DW_Subrange);
1174 }
1175 
1176 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1177 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1178                                        DICompositeType *CTy) {
1179   Buffer.setTag(dwarf::DW_TAG_array_type);
1180   if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1181     addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1182 
1183   // Emit derived type.
1184   addType(&Buffer, CTy->getTypeDerivedFrom());
1185   DIArray Elements = CTy->getTypeArray();
1186 
1187   // Get an anonymous type for index type.
1188   CompileUnit *TheCU = getCompileUnit(*CTy);
1189   DIE *IdxTy = TheCU->getIndexTyDie();
1190   if (!IdxTy) {
1191     // Construct an anonymous type for index type.
1192     IdxTy = new DIE(dwarf::DW_TAG_base_type);
1193     addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1194     addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1195             dwarf::DW_ATE_signed);
1196     TheCU->addDie(IdxTy);
1197     TheCU->setIndexTyDie(IdxTy);
1198   }
1199 
1200   // Add subranges to array type.
1201   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1202     DIDescriptor Element = Elements.getElement(i);
1203     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1204       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1205   }
1206 }
1207 
1208 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1209 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1210   DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1211   StringRef Name = ETy.getName();
1212   addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1213   int64_t Value = ETy.getEnumValue();
1214   addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1215   return Enumerator;
1216 }
1217 
1218 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1219 /// printer to not emit usual symbol prefix before the symbol name is used then
1220 /// return linkage name after skipping this special LLVM prefix.
1221 static StringRef getRealLinkageName(StringRef LinkageName) {
1222   char One = '\1';
1223   if (LinkageName.startswith(StringRef(&One, 1)))
1224     return LinkageName.substr(1);
1225   return LinkageName;
1226 }
1227 
1228 /// createMemberDIE - Create new member DIE.
1229 DIE *DwarfDebug::createMemberDIE(DIDerivedType DT) {
1230   DIE *MemberDie = new DIE(DT.getTag());
1231   StringRef Name = DT.getName();
1232   if (!Name.empty())
1233     addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1234 
1235   addType(MemberDie, DT.getTypeDerivedFrom());
1236 
1237   addSourceLine(MemberDie, DT);
1238 
1239   DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1240   addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1241 
1242   uint64_t Size = DT.getSizeInBits();
1243   uint64_t FieldSize = DT.getOriginalTypeSize();
1244 
1245   if (Size != FieldSize) {
1246     // Handle bitfield.
1247     addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1248     addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1249 
1250     uint64_t Offset = DT.getOffsetInBits();
1251     uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1252     uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1253     uint64_t FieldOffset = (HiMark - FieldSize);
1254     Offset -= FieldOffset;
1255 
1256     // Maybe we need to work from the other end.
1257     if (Asm->getTargetData().isLittleEndian())
1258       Offset = FieldSize - (Offset + Size);
1259     addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1260 
1261     // Here WD_AT_data_member_location points to the anonymous
1262     // field that includes this bit field.
1263     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1264 
1265   } else
1266     // This is not a bitfield.
1267     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1268 
1269   if (DT.getTag() == dwarf::DW_TAG_inheritance
1270       && DT.isVirtual()) {
1271 
1272     // For C++, virtual base classes are not at fixed offset. Use following
1273     // expression to extract appropriate offset from vtable.
1274     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1275 
1276     DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1277     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1278     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1279     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1280     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1281     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1282     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1283     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1284 
1285     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1286              VBaseLocationDie);
1287   } else
1288     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1289 
1290   if (DT.isProtected())
1291     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1292             dwarf::DW_ACCESS_protected);
1293   else if (DT.isPrivate())
1294     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1295             dwarf::DW_ACCESS_private);
1296   // Otherwise C++ member and base classes are considered public.
1297   else if (DT.getCompileUnit().getLanguage() == dwarf::DW_LANG_C_plus_plus)
1298     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1299             dwarf::DW_ACCESS_public);
1300   if (DT.isVirtual())
1301     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1302             dwarf::DW_VIRTUALITY_virtual);
1303   return MemberDie;
1304 }
1305 
1306 /// createSubprogramDIE - Create new DIE using SP.
1307 DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
1308   CompileUnit *SPCU = getCompileUnit(SP);
1309   DIE *SPDie = SPCU->getDIE(SP);
1310   if (SPDie)
1311     return SPDie;
1312 
1313   SPDie = new DIE(dwarf::DW_TAG_subprogram);
1314   // Constructors and operators for anonymous aggregates do not have names.
1315   if (!SP.getName().empty())
1316     addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1317 
1318   StringRef LinkageName = SP.getLinkageName();
1319   if (!LinkageName.empty())
1320     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1321               getRealLinkageName(LinkageName));
1322 
1323   addSourceLine(SPDie, SP);
1324 
1325   if (SP.isPrototyped())
1326     addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1327 
1328   // Add Return Type.
1329   DICompositeType SPTy = SP.getType();
1330   DIArray Args = SPTy.getTypeArray();
1331   unsigned SPTag = SPTy.getTag();
1332 
1333   if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1334     addType(SPDie, SPTy);
1335   else
1336     addType(SPDie, DIType(Args.getElement(0)));
1337 
1338   unsigned VK = SP.getVirtuality();
1339   if (VK) {
1340     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1341     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1342     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1343     addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1344     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1345     ContainingTypeMap.insert(std::make_pair(SPDie,
1346                                             SP.getContainingType()));
1347   }
1348 
1349   if (!SP.isDefinition()) {
1350     addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1351 
1352     // Add arguments. Do not add arguments for subprogram definition. They will
1353     // be handled while processing variables.
1354     DICompositeType SPTy = SP.getType();
1355     DIArray Args = SPTy.getTypeArray();
1356     unsigned SPTag = SPTy.getTag();
1357 
1358     if (SPTag == dwarf::DW_TAG_subroutine_type)
1359       for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1360         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1361         DIType ATy = DIType(DIType(Args.getElement(i)));
1362         addType(Arg, ATy);
1363         if (ATy.isArtificial())
1364           addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1365         SPDie->addChild(Arg);
1366       }
1367   }
1368 
1369   if (SP.isArtificial())
1370     addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1371 
1372   if (!SP.isLocalToUnit())
1373     addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1374 
1375   if (SP.isOptimized())
1376     addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1377 
1378   if (unsigned isa = Asm->getISAEncoding()) {
1379     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1380   }
1381 
1382   // DW_TAG_inlined_subroutine may refer to this DIE.
1383   SPCU->insertDIE(SP, SPDie);
1384 
1385   // Add to context owner.
1386   addToContextOwner(SPDie, SP.getContext());
1387 
1388   return SPDie;
1389 }
1390 
1391 DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
1392   assert(N && "Invalid Scope encoding!");
1393 
1394   DbgScope *AScope = AbstractScopes.lookup(N);
1395   if (AScope)
1396     return AScope;
1397 
1398   DbgScope *Parent = NULL;
1399 
1400   DIDescriptor Scope(N);
1401   if (Scope.isLexicalBlock()) {
1402     DILexicalBlock DB(N);
1403     DIDescriptor ParentDesc = DB.getContext();
1404     Parent = getOrCreateAbstractScope(ParentDesc);
1405   }
1406 
1407   AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1408 
1409   if (Parent)
1410     Parent->addScope(AScope);
1411   AScope->setAbstractScope();
1412   AbstractScopes[N] = AScope;
1413   if (DIDescriptor(N).isSubprogram())
1414     AbstractScopesList.push_back(AScope);
1415   return AScope;
1416 }
1417 
1418 /// isSubprogramContext - Return true if Context is either a subprogram
1419 /// or another context nested inside a subprogram.
1420 static bool isSubprogramContext(const MDNode *Context) {
1421   if (!Context)
1422     return false;
1423   DIDescriptor D(Context);
1424   if (D.isSubprogram())
1425     return true;
1426   if (D.isType())
1427     return isSubprogramContext(DIType(Context).getContext());
1428   return false;
1429 }
1430 
1431 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1432 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1433 /// If there are global variables in this scope then create and insert
1434 /// DIEs for these variables.
1435 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
1436   CompileUnit *SPCU = getCompileUnit(SPNode);
1437   DIE *SPDie = SPCU->getDIE(SPNode);
1438 
1439   assert(SPDie && "Unable to find subprogram DIE!");
1440   DISubprogram SP(SPNode);
1441 
1442   // There is not any need to generate specification DIE for a function
1443   // defined at compile unit level. If a function is defined inside another
1444   // function then gdb prefers the definition at top level and but does not
1445   // expect specification DIE in parent function. So avoid creating
1446   // specification DIE for a function defined inside a function.
1447   if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1448       !SP.getContext().isFile() &&
1449       !isSubprogramContext(SP.getContext())) {
1450     addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1451 
1452     // Add arguments.
1453     DICompositeType SPTy = SP.getType();
1454     DIArray Args = SPTy.getTypeArray();
1455     unsigned SPTag = SPTy.getTag();
1456     if (SPTag == dwarf::DW_TAG_subroutine_type)
1457       for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1458         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1459         DIType ATy = DIType(DIType(Args.getElement(i)));
1460         addType(Arg, ATy);
1461         if (ATy.isArtificial())
1462           addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1463         SPDie->addChild(Arg);
1464       }
1465     DIE *SPDeclDie = SPDie;
1466     SPDie = new DIE(dwarf::DW_TAG_subprogram);
1467     addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1468                 SPDeclDie);
1469     SPCU->addDie(SPDie);
1470   }
1471 
1472   // Pick up abstract subprogram DIE.
1473   if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
1474     SPDie = new DIE(dwarf::DW_TAG_subprogram);
1475     addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
1476                 dwarf::DW_FORM_ref4, AbsSPDIE);
1477     SPCU->addDie(SPDie);
1478   }
1479 
1480   addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1481            Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1482   addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1483            Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1484   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1485   MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1486   addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1487 
1488   return SPDie;
1489 }
1490 
1491 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1492 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1493 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1494 
1495   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1496   if (Scope->isAbstractScope())
1497     return ScopeDIE;
1498 
1499   const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1500   if (Ranges.empty())
1501     return 0;
1502 
1503   SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1504   if (Ranges.size() > 1) {
1505     // .debug_range section has not been laid out yet. Emit offset in
1506     // .debug_range as a uint, size 4, for now. emitDIE will handle
1507     // DW_AT_ranges appropriately.
1508     addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1509             DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1510     for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1511          RE = Ranges.end(); RI != RE; ++RI) {
1512       DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
1513       DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
1514     }
1515     DebugRangeSymbols.push_back(NULL);
1516     DebugRangeSymbols.push_back(NULL);
1517     return ScopeDIE;
1518   }
1519 
1520   const MCSymbol *Start = getLabelBeforeInsn(RI->first);
1521   const MCSymbol *End = getLabelAfterInsn(RI->second);
1522 
1523   if (End == 0) return 0;
1524 
1525   assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1526   assert(End->isDefined() && "Invalid end label for an inlined scope!");
1527 
1528   addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1529   addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1530 
1531   return ScopeDIE;
1532 }
1533 
1534 /// constructInlinedScopeDIE - This scope represents inlined body of
1535 /// a function. Construct DIE to represent this concrete inlined copy
1536 /// of the function.
1537 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1538 
1539   const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1540   assert (Ranges.empty() == false
1541           && "DbgScope does not have instruction markers!");
1542 
1543   // FIXME : .debug_inlined section specification does not clearly state how
1544   // to emit inlined scope that is split into multiple instruction ranges.
1545   // For now, use first instruction range and emit low_pc/high_pc pair and
1546   // corresponding .debug_inlined section entry for this pair.
1547   SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1548   const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
1549   const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
1550 
1551   if (StartLabel == 0 || EndLabel == 0) {
1552     assert (0 && "Unexpected Start and End  labels for a inlined scope!");
1553     return 0;
1554   }
1555   assert(StartLabel->isDefined() &&
1556          "Invalid starting label for an inlined scope!");
1557   assert(EndLabel->isDefined() &&
1558          "Invalid end label for an inlined scope!");
1559 
1560   if (!Scope->getScopeNode())
1561     return NULL;
1562   DIScope DS(Scope->getScopeNode());
1563   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1564 
1565   DISubprogram InlinedSP = getDISubprogram(DS);
1566   CompileUnit *TheCU = getCompileUnit(InlinedSP);
1567   DIE *OriginDIE = TheCU->getDIE(InlinedSP);
1568   assert(OriginDIE && "Unable to find Origin DIE!");
1569   addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1570               dwarf::DW_FORM_ref4, OriginDIE);
1571 
1572   addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1573   addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1574 
1575   InlinedSubprogramDIEs.insert(OriginDIE);
1576 
1577   // Track the start label for this inlined function.
1578   DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1579     I = InlineInfo.find(InlinedSP);
1580 
1581   if (I == InlineInfo.end()) {
1582     InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
1583                                                              ScopeDIE));
1584     InlinedSPNodes.push_back(InlinedSP);
1585   } else
1586     I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1587 
1588   DILocation DL(Scope->getInlinedAt());
1589   addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
1590   addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1591 
1592   return ScopeDIE;
1593 }
1594 
1595 
1596 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1597 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1598   StringRef Name = DV->getName();
1599   if (Name.empty())
1600     return NULL;
1601 
1602   // Translate tag to proper Dwarf tag.  The result variable is dropped for
1603   // now.
1604   unsigned Tag;
1605   switch (DV->getTag()) {
1606   case dwarf::DW_TAG_return_variable:
1607     return NULL;
1608   case dwarf::DW_TAG_arg_variable:
1609     Tag = dwarf::DW_TAG_formal_parameter;
1610     break;
1611   case dwarf::DW_TAG_auto_variable:    // fall thru
1612   default:
1613     Tag = dwarf::DW_TAG_variable;
1614     break;
1615   }
1616 
1617   // Define variable debug information entry.
1618   DIE *VariableDie = new DIE(Tag);
1619 
1620   DIE *AbsDIE = NULL;
1621   DenseMap<const DbgVariable *, const DbgVariable *>::iterator
1622     V2AVI = VarToAbstractVarMap.find(DV);
1623   if (V2AVI != VarToAbstractVarMap.end())
1624     AbsDIE = V2AVI->second->getDIE();
1625 
1626   if (AbsDIE)
1627     addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1628                 dwarf::DW_FORM_ref4, AbsDIE);
1629   else {
1630     addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1631     addSourceLine(VariableDie, DV->getVariable());
1632 
1633     // Add variable type.
1634     addType(VariableDie, DV->getType());
1635   }
1636 
1637   if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
1638     addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1639   else if (DIVariable(DV->getVariable()).isArtificial())
1640     addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1641 
1642   if (Scope->isAbstractScope()) {
1643     DV->setDIE(VariableDie);
1644     return VariableDie;
1645   }
1646 
1647   // Add variable address.
1648 
1649   unsigned Offset = DV->getDotDebugLocOffset();
1650   if (Offset != ~0U) {
1651     addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
1652              Asm->GetTempSymbol("debug_loc", Offset));
1653     DV->setDIE(VariableDie);
1654     UseDotDebugLocEntry.insert(VariableDie);
1655     return VariableDie;
1656   }
1657 
1658   // Check if variable is described by a  DBG_VALUE instruction.
1659   DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
1660     DbgVariableToDbgInstMap.find(DV);
1661   if (DVI != DbgVariableToDbgInstMap.end()) {
1662     const MachineInstr *DVInsn = DVI->second;
1663     const MCSymbol *DVLabel = findVariableLabel(DV);
1664     bool updated = false;
1665     // FIXME : Handle getNumOperands != 3
1666     if (DVInsn->getNumOperands() == 3) {
1667       if (DVInsn->getOperand(0).isReg()) {
1668         const MachineOperand RegOp = DVInsn->getOperand(0);
1669         const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1670         if (DVInsn->getOperand(1).isImm() &&
1671             TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
1672           addVariableAddress(DV, VariableDie, DVInsn->getOperand(1).getImm());
1673           updated = true;
1674         } else
1675           updated = addRegisterAddress(VariableDie, DVLabel, RegOp);
1676       }
1677       else if (DVInsn->getOperand(0).isImm())
1678         updated = addConstantValue(VariableDie, DVLabel, DVInsn->getOperand(0));
1679       else if (DVInsn->getOperand(0).isFPImm())
1680         updated =
1681           addConstantFPValue(VariableDie, DVLabel, DVInsn->getOperand(0));
1682     } else {
1683       MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
1684       if (Location.getReg()) {
1685         addAddress(VariableDie, dwarf::DW_AT_location, Location);
1686         if (DVLabel)
1687           addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1688                    DVLabel);
1689         updated = true;
1690       }
1691     }
1692     if (!updated) {
1693       // If variableDie is not updated then DBG_VALUE instruction does not
1694       // have valid variable info.
1695       delete VariableDie;
1696       return NULL;
1697     }
1698     DV->setDIE(VariableDie);
1699     return VariableDie;
1700   }
1701 
1702   // .. else use frame index, if available.
1703   int FI = 0;
1704   if (findVariableFrameIndex(DV, &FI))
1705     addVariableAddress(DV, VariableDie, FI);
1706 
1707   DV->setDIE(VariableDie);
1708   return VariableDie;
1709 
1710 }
1711 
1712 void DwarfDebug::addPubTypes(DISubprogram SP) {
1713   DICompositeType SPTy = SP.getType();
1714   unsigned SPTag = SPTy.getTag();
1715   if (SPTag != dwarf::DW_TAG_subroutine_type)
1716     return;
1717 
1718   DIArray Args = SPTy.getTypeArray();
1719   for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1720     DIType ATy(Args.getElement(i));
1721     if (!ATy.Verify())
1722       continue;
1723     DICompositeType CATy = getDICompositeType(ATy);
1724     if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
1725         && !CATy.isForwardDecl()) {
1726       CompileUnit *TheCU = getCompileUnit(CATy);
1727       if (DIEEntry *Entry = TheCU->getDIEEntry(CATy))
1728         TheCU->addGlobalType(CATy.getName(), Entry->getEntry());
1729     }
1730   }
1731 }
1732 
1733 /// constructScopeDIE - Construct a DIE for this scope.
1734 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1735   if (!Scope || !Scope->getScopeNode())
1736     return NULL;
1737 
1738   DIScope DS(Scope->getScopeNode());
1739   DIE *ScopeDIE = NULL;
1740   if (Scope->getInlinedAt())
1741     ScopeDIE = constructInlinedScopeDIE(Scope);
1742   else if (DS.isSubprogram()) {
1743     ProcessedSPNodes.insert(DS);
1744     if (Scope->isAbstractScope()) {
1745       ScopeDIE = getCompileUnit(DS)->getDIE(DS);
1746       // Note down abstract DIE.
1747       if (ScopeDIE)
1748         AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
1749     }
1750     else
1751       ScopeDIE = updateSubprogramScopeDIE(DS);
1752   }
1753   else
1754     ScopeDIE = constructLexicalScopeDIE(Scope);
1755   if (!ScopeDIE) return NULL;
1756 
1757   // Add variables to scope.
1758   const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1759   for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1760     DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1761     if (VariableDIE)
1762       ScopeDIE->addChild(VariableDIE);
1763   }
1764 
1765   // Add nested scopes.
1766   const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1767   for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1768     // Define the Scope debug information entry.
1769     DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1770     if (NestedDIE)
1771       ScopeDIE->addChild(NestedDIE);
1772   }
1773 
1774   if (DS.isSubprogram())
1775     addPubTypes(DISubprogram(DS));
1776 
1777  return ScopeDIE;
1778 }
1779 
1780 /// GetOrCreateSourceID - Look up the source id with the given directory and
1781 /// source file names. If none currently exists, create a new id and insert it
1782 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1783 /// maps as well.
1784 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1785   unsigned DId;
1786   assert (DirName.empty() == false && "Invalid directory name!");
1787 
1788   // If FE did not provide a file name, then assume stdin.
1789   if (FileName.empty())
1790     return GetOrCreateSourceID(DirName, "<stdin>");
1791 
1792   StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1793   if (DI != DirectoryIdMap.end()) {
1794     DId = DI->getValue();
1795   } else {
1796     DId = DirectoryNames.size() + 1;
1797     DirectoryIdMap[DirName] = DId;
1798     DirectoryNames.push_back(DirName);
1799   }
1800 
1801   unsigned FId;
1802   StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1803   if (FI != SourceFileIdMap.end()) {
1804     FId = FI->getValue();
1805   } else {
1806     FId = SourceFileNames.size() + 1;
1807     SourceFileIdMap[FileName] = FId;
1808     SourceFileNames.push_back(FileName);
1809   }
1810 
1811   DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1812     SourceIdMap.find(std::make_pair(DId, FId));
1813   if (SI != SourceIdMap.end())
1814     return SI->second;
1815 
1816   unsigned SrcId = SourceIds.size() + 1;  // DW_AT_decl_file cannot be 0.
1817   SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1818   SourceIds.push_back(std::make_pair(DId, FId));
1819 
1820   return SrcId;
1821 }
1822 
1823 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1824 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1825   CompileUnit *TheCU = getCompileUnit(NS);
1826   DIE *NDie = TheCU->getDIE(NS);
1827   if (NDie)
1828     return NDie;
1829   NDie = new DIE(dwarf::DW_TAG_namespace);
1830   TheCU->insertDIE(NS, NDie);
1831   if (!NS.getName().empty())
1832     addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1833   addSourceLine(NDie, NS);
1834   addToContextOwner(NDie, NS.getContext());
1835   return NDie;
1836 }
1837 
1838 /// constructCompileUnit - Create new CompileUnit for the given
1839 /// metadata node with tag DW_TAG_compile_unit.
1840 void DwarfDebug::constructCompileUnit(const MDNode *N) {
1841   DICompileUnit DIUnit(N);
1842   StringRef FN = DIUnit.getFilename();
1843   StringRef Dir = DIUnit.getDirectory();
1844   unsigned ID = GetOrCreateSourceID(Dir, FN);
1845 
1846   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1847   addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1848             DIUnit.getProducer());
1849   addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1850           DIUnit.getLanguage());
1851   addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1852   // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1853   // simplifies debug range entries.
1854   addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
1855   // DW_AT_stmt_list is a offset of line number information for this
1856   // compile unit in debug_line section.
1857   if (Asm->MAI->doesDwarfUsesAbsoluteLabelForStmtList())
1858     addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_addr,
1859              Asm->GetTempSymbol("section_line"));
1860   else
1861     addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1862 
1863   if (!Dir.empty())
1864     addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1865   if (DIUnit.isOptimized())
1866     addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1867 
1868   StringRef Flags = DIUnit.getFlags();
1869   if (!Flags.empty())
1870     addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1871 
1872   unsigned RVer = DIUnit.getRunTimeVersion();
1873   if (RVer)
1874     addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1875             dwarf::DW_FORM_data1, RVer);
1876 
1877   CompileUnit *NewCU = new CompileUnit(ID, Die);
1878   if (!FirstCU)
1879     FirstCU = NewCU;
1880   CUMap.insert(std::make_pair(N, NewCU));
1881 }
1882 
1883 /// getCompielUnit - Get CompileUnit DIE.
1884 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
1885   assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
1886   DIDescriptor D(N);
1887   const MDNode *CUNode = NULL;
1888   if (D.isCompileUnit())
1889     CUNode = N;
1890   else if (D.isSubprogram())
1891     CUNode = DISubprogram(N).getCompileUnit();
1892   else if (D.isType())
1893     CUNode = DIType(N).getCompileUnit();
1894   else if (D.isGlobalVariable())
1895     CUNode = DIGlobalVariable(N).getCompileUnit();
1896   else if (D.isVariable())
1897     CUNode = DIVariable(N).getCompileUnit();
1898   else if (D.isNameSpace())
1899     CUNode = DINameSpace(N).getCompileUnit();
1900   else if (D.isFile())
1901     CUNode = DIFile(N).getCompileUnit();
1902   else
1903     return FirstCU;
1904 
1905   DenseMap<const MDNode *, CompileUnit *>::const_iterator I
1906     = CUMap.find(CUNode);
1907   if (I == CUMap.end())
1908     return FirstCU;
1909   return I->second;
1910 }
1911 
1912 /// isUnsignedDIType - Return true if type encoding is unsigned.
1913 static bool isUnsignedDIType(DIType Ty) {
1914   DIDerivedType DTy(Ty);
1915   if (DTy.Verify())
1916     return isUnsignedDIType(DTy.getTypeDerivedFrom());
1917 
1918   DIBasicType BTy(Ty);
1919   if (BTy.Verify()) {
1920     unsigned Encoding = BTy.getEncoding();
1921     if (Encoding == dwarf::DW_ATE_unsigned ||
1922         Encoding == dwarf::DW_ATE_unsigned_char)
1923       return true;
1924   }
1925   return false;
1926 }
1927 
1928 /// constructGlobalVariableDIE - Construct global variable DIE.
1929 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
1930   DIGlobalVariable GV(N);
1931 
1932   // If debug information is malformed then ignore it.
1933   if (GV.Verify() == false)
1934     return;
1935 
1936   // Check for pre-existence.
1937   CompileUnit *TheCU = getCompileUnit(N);
1938   if (TheCU->getDIE(GV))
1939     return;
1940 
1941   DIType GTy = GV.getType();
1942   DIE *VariableDIE = new DIE(GV.getTag());
1943 
1944   bool isGlobalVariable = GV.getGlobal() != NULL;
1945 
1946   // Add name.
1947   addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1948             GV.getDisplayName());
1949   StringRef LinkageName = GV.getLinkageName();
1950   if (!LinkageName.empty() && isGlobalVariable)
1951     addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1952               getRealLinkageName(LinkageName));
1953   // Add type.
1954   addType(VariableDIE, GTy);
1955   if (GTy.isCompositeType() && !GTy.getName().empty()
1956       && !GTy.isForwardDecl()) {
1957     DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1958     assert(Entry && "Missing global type!");
1959     TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1960   }
1961   // Add scoping info.
1962   if (!GV.isLocalToUnit()) {
1963     addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1964     // Expose as global.
1965     TheCU->addGlobal(GV.getName(), VariableDIE);
1966   }
1967   // Add line number info.
1968   addSourceLine(VariableDIE, GV);
1969   // Add to map.
1970   TheCU->insertDIE(N, VariableDIE);
1971   // Add to context owner.
1972   DIDescriptor GVContext = GV.getContext();
1973   addToContextOwner(VariableDIE, GVContext);
1974   // Add location.
1975   if (isGlobalVariable) {
1976     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1977     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1978     addLabel(Block, 0, dwarf::DW_FORM_udata,
1979              Asm->Mang->getSymbol(GV.getGlobal()));
1980     // Do not create specification DIE if context is either compile unit
1981     // or a subprogram.
1982     if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1983         !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1984       // Create specification DIE.
1985       DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1986       addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1987                   dwarf::DW_FORM_ref4, VariableDIE);
1988       addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1989       addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1990       TheCU->addDie(VariableSpecDIE);
1991     } else {
1992       addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1993     }
1994   } else if (Constant *C = GV.getConstant()) {
1995     if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1996       if (isUnsignedDIType(GTy))
1997           addUInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
1998                   CI->getZExtValue());
1999         else
2000           addSInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
2001                  CI->getSExtValue());
2002     }
2003   }
2004   return;
2005 }
2006 
2007 /// construct SubprogramDIE - Construct subprogram DIE.
2008 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
2009   DISubprogram SP(N);
2010 
2011   // Check for pre-existence.
2012   CompileUnit *TheCU = getCompileUnit(N);
2013   if (TheCU->getDIE(N))
2014     return;
2015 
2016   if (!SP.isDefinition())
2017     // This is a method declaration which will be handled while constructing
2018     // class type.
2019     return;
2020 
2021   DIE *SubprogramDie = createSubprogramDIE(SP);
2022 
2023   // Add to map.
2024   TheCU->insertDIE(N, SubprogramDie);
2025 
2026   // Add to context owner.
2027   addToContextOwner(SubprogramDie, SP.getContext());
2028 
2029   // Expose as global.
2030   TheCU->addGlobal(SP.getName(), SubprogramDie);
2031 
2032   return;
2033 }
2034 
2035 /// beginModule - Emit all Dwarf sections that should come prior to the
2036 /// content. Create global DIEs and emit initial debug info sections.
2037 /// This is inovked by the target AsmPrinter.
2038 void DwarfDebug::beginModule(Module *M) {
2039   if (DisableDebugInfoPrinting)
2040     return;
2041 
2042   DebugInfoFinder DbgFinder;
2043   DbgFinder.processModule(*M);
2044 
2045   bool HasDebugInfo = false;
2046 
2047   // Scan all the compile-units to see if there are any marked as the main unit.
2048   // if not, we do not generate debug info.
2049   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2050        E = DbgFinder.compile_unit_end(); I != E; ++I) {
2051     if (DICompileUnit(*I).isMain()) {
2052       HasDebugInfo = true;
2053       break;
2054     }
2055   }
2056 
2057   if (!HasDebugInfo) return;
2058 
2059   // Tell MMI that we have debug info.
2060   MMI->setDebugInfoAvailability(true);
2061 
2062   // Emit initial sections.
2063   EmitSectionLabels();
2064 
2065   // Create all the compile unit DIEs.
2066   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2067          E = DbgFinder.compile_unit_end(); I != E; ++I)
2068     constructCompileUnit(*I);
2069 
2070   // Create DIEs for each subprogram.
2071   for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
2072          E = DbgFinder.subprogram_end(); I != E; ++I)
2073     constructSubprogramDIE(*I);
2074 
2075   // Create DIEs for each global variable.
2076   for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
2077          E = DbgFinder.global_variable_end(); I != E; ++I)
2078     constructGlobalVariableDIE(*I);
2079 
2080   //getOrCreateTypeDIE
2081   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
2082     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2083       getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2084 
2085   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
2086     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2087       getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2088 
2089   // Prime section data.
2090   SectionMap.insert(Asm->getObjFileLowering().getTextSection());
2091 
2092   // Print out .file directives to specify files for .loc directives. These are
2093   // printed out early so that they precede any .loc directives.
2094   if (Asm->MAI->hasDotLocAndDotFile()) {
2095     for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2096       // Remember source id starts at 1.
2097       std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
2098       // FIXME: don't use sys::path for this!  This should not depend on the
2099       // host.
2100       sys::Path FullPath(getSourceDirectoryName(Id.first));
2101       bool AppendOk =
2102         FullPath.appendComponent(getSourceFileName(Id.second));
2103       assert(AppendOk && "Could not append filename to directory!");
2104       AppendOk = false;
2105       Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
2106     }
2107   }
2108 }
2109 
2110 /// endModule - Emit all Dwarf sections that should come after the content.
2111 ///
2112 void DwarfDebug::endModule() {
2113   if (!FirstCU) return;
2114   const Module *M = MMI->getModule();
2115   DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
2116   if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
2117     for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
2118       if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
2119       DISubprogram SP(AllSPs->getOperand(SI));
2120       if (!SP.Verify()) continue;
2121 
2122       // Collect info for variables that were optimized out.
2123       if (!SP.isDefinition()) continue;
2124       StringRef FName = SP.getLinkageName();
2125       if (FName.empty())
2126         FName = SP.getName();
2127       NamedMDNode *NMD =
2128         M->getNamedMetadata(Twine("llvm.dbg.lv.", getRealLinkageName(FName)));
2129       if (!NMD) continue;
2130       unsigned E = NMD->getNumOperands();
2131       if (!E) continue;
2132       DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
2133       DeadFnScopeMap[SP] = Scope;
2134       for (unsigned I = 0; I != E; ++I) {
2135         DIVariable DV(NMD->getOperand(I));
2136         if (!DV.Verify()) continue;
2137         Scope->addVariable(new DbgVariable(DV));
2138       }
2139 
2140       // Construct subprogram DIE and add variables DIEs.
2141       constructSubprogramDIE(SP);
2142       DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
2143       const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
2144       for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2145         DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
2146         if (VariableDIE)
2147           ScopeDIE->addChild(VariableDIE);
2148       }
2149     }
2150   }
2151 
2152   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
2153   for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
2154          AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
2155     DIE *ISP = *AI;
2156     addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
2157   }
2158 
2159   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
2160          CE = ContainingTypeMap.end(); CI != CE; ++CI) {
2161     DIE *SPDie = CI->first;
2162     const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
2163     if (!N) continue;
2164     DIE *NDie = getCompileUnit(N)->getDIE(N);
2165     if (!NDie) continue;
2166     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
2167   }
2168 
2169   // Standard sections final addresses.
2170   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
2171   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
2172   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
2173   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
2174 
2175   // End text sections.
2176   for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2177     Asm->OutStreamer.SwitchSection(SectionMap[i]);
2178     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
2179   }
2180 
2181   // Emit common frame information.
2182   emitCommonDebugFrame();
2183 
2184   // Emit function debug frame information
2185   for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2186          E = DebugFrames.end(); I != E; ++I)
2187     emitFunctionDebugFrame(*I);
2188 
2189   // Compute DIE offsets and sizes.
2190   computeSizeAndOffsets();
2191 
2192   // Emit all the DIEs into a debug info section
2193   emitDebugInfo();
2194 
2195   // Corresponding abbreviations into a abbrev section.
2196   emitAbbreviations();
2197 
2198   // Emit source line correspondence into a debug line section.
2199   emitDebugLines();
2200 
2201   // Emit info into a debug pubnames section.
2202   emitDebugPubNames();
2203 
2204   // Emit info into a debug pubtypes section.
2205   emitDebugPubTypes();
2206 
2207   // Emit info into a debug loc section.
2208   emitDebugLoc();
2209 
2210   // Emit info into a debug aranges section.
2211   EmitDebugARanges();
2212 
2213   // Emit info into a debug ranges section.
2214   emitDebugRanges();
2215 
2216   // Emit info into a debug macinfo section.
2217   emitDebugMacInfo();
2218 
2219   // Emit inline info.
2220   emitDebugInlineInfo();
2221 
2222   // Emit info into a debug str section.
2223   emitDebugStr();
2224 
2225   // clean up.
2226   DeleteContainerSeconds(DeadFnScopeMap);
2227   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2228          E = CUMap.end(); I != E; ++I)
2229     delete I->second;
2230   FirstCU = NULL;  // Reset for the next Module, if any.
2231 }
2232 
2233 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2234 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2235                                               DebugLoc ScopeLoc) {
2236 
2237   DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
2238   if (AbsDbgVariable)
2239     return AbsDbgVariable;
2240 
2241   LLVMContext &Ctx = Var->getContext();
2242   DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2243   if (!Scope)
2244     return NULL;
2245 
2246   AbsDbgVariable = new DbgVariable(Var);
2247   Scope->addVariable(AbsDbgVariable);
2248   AbstractVariables[Var] = AbsDbgVariable;
2249   return AbsDbgVariable;
2250 }
2251 
2252 /// collectVariableInfoFromMMITable - Collect variable information from
2253 /// side table maintained by MMI.
2254 void
2255 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
2256                                    SmallPtrSet<const MDNode *, 16> &Processed) {
2257   const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2258   MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2259   for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2260          VE = VMap.end(); VI != VE; ++VI) {
2261     const MDNode *Var = VI->first;
2262     if (!Var) continue;
2263     Processed.insert(Var);
2264     DIVariable DV(Var);
2265     const std::pair<unsigned, DebugLoc> &VP = VI->second;
2266 
2267     DbgScope *Scope = 0;
2268     if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
2269       Scope = ConcreteScopes.lookup(IA);
2270     if (Scope == 0)
2271       Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2272 
2273     // If variable scope is not found then skip this variable.
2274     if (Scope == 0)
2275       continue;
2276 
2277     DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
2278     DbgVariable *RegVar = new DbgVariable(DV);
2279     recordVariableFrameIndex(RegVar, VP.first);
2280     Scope->addVariable(RegVar);
2281     if (AbsDbgVariable) {
2282       recordVariableFrameIndex(AbsDbgVariable, VP.first);
2283       VarToAbstractVarMap[RegVar] = AbsDbgVariable;
2284     }
2285   }
2286 }
2287 
2288 /// isDbgValueInUndefinedReg - Return true if debug value, encoded by
2289 /// DBG_VALUE instruction, is in undefined reg.
2290 static bool isDbgValueInUndefinedReg(const MachineInstr *MI) {
2291   assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2292   if (MI->getOperand(0).isReg() && !MI->getOperand(0).getReg())
2293     return true;
2294   return false;
2295 }
2296 
2297 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
2298 /// DBG_VALUE instruction, is in a defined reg.
2299 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
2300   assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2301   if (MI->getOperand(0).isReg() && MI->getOperand(0).getReg())
2302     return true;
2303   return false;
2304 }
2305 
2306 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2307 void
2308 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
2309                                 SmallPtrSet<const MDNode *, 16> &Processed) {
2310 
2311   /// collection info from MMI table.
2312   collectVariableInfoFromMMITable(MF, Processed);
2313 
2314   SmallVector<const MachineInstr *, 8> DbgValues;
2315   // Collect variable information from DBG_VALUE machine instructions;
2316   for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2317        I != E; ++I)
2318     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2319          II != IE; ++II) {
2320       const MachineInstr *MInsn = II;
2321       if (!MInsn->isDebugValue() || isDbgValueInUndefinedReg(MInsn))
2322         continue;
2323       DbgValues.push_back(MInsn);
2324     }
2325 
2326   // This is a collection of DBV_VALUE instructions describing same variable.
2327   SmallVector<const MachineInstr *, 4> MultipleValues;
2328   for(SmallVector<const MachineInstr *, 8>::iterator I = DbgValues.begin(),
2329         E = DbgValues.end(); I != E; ++I) {
2330     const MachineInstr *MInsn = *I;
2331     MultipleValues.clear();
2332     if (isDbgValueInDefinedReg(MInsn))
2333       MultipleValues.push_back(MInsn);
2334     DIVariable DV(MInsn->getOperand(MInsn->getNumOperands() - 1).getMetadata());
2335     if (Processed.count(DV) != 0)
2336       continue;
2337 
2338     const MachineInstr *PrevMI = MInsn;
2339     for (SmallVector<const MachineInstr *, 8>::iterator MI = I+1,
2340            ME = DbgValues.end(); MI != ME; ++MI) {
2341       const MDNode *Var =
2342         (*MI)->getOperand((*MI)->getNumOperands()-1).getMetadata();
2343       if (Var == DV && isDbgValueInDefinedReg(*MI) &&
2344           !PrevMI->isIdenticalTo(*MI))
2345         MultipleValues.push_back(*MI);
2346       PrevMI = *MI;
2347     }
2348 
2349     DbgScope *Scope = findDbgScope(MInsn);
2350     bool CurFnArg = false;
2351     if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
2352         DISubprogram(DV.getContext()).describes(MF->getFunction()))
2353       CurFnArg = true;
2354     if (!Scope && CurFnArg)
2355       Scope = CurrentFnDbgScope;
2356     // If variable scope is not found then skip this variable.
2357     if (!Scope)
2358       continue;
2359 
2360     Processed.insert(DV);
2361     DbgVariable *RegVar = new DbgVariable(DV);
2362     Scope->addVariable(RegVar);
2363     if (!CurFnArg)
2364       DbgVariableLabelsMap[RegVar] = getLabelBeforeInsn(MInsn);
2365     if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
2366       DbgVariableToDbgInstMap[AbsVar] = MInsn;
2367       VarToAbstractVarMap[RegVar] = AbsVar;
2368     }
2369     if (MultipleValues.size() <= 1) {
2370       DbgVariableToDbgInstMap[RegVar] = MInsn;
2371       continue;
2372     }
2373 
2374     // handle multiple DBG_VALUE instructions describing one variable.
2375     if (DotDebugLocEntries.empty())
2376       RegVar->setDotDebugLocOffset(0);
2377     else
2378       RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
2379     const MachineInstr *Begin = NULL;
2380     const MachineInstr *End = NULL;
2381     for (SmallVector<const MachineInstr *, 4>::iterator
2382            MVI = MultipleValues.begin(), MVE = MultipleValues.end();
2383          MVI != MVE; ++MVI) {
2384       if (!Begin) {
2385         Begin = *MVI;
2386         continue;
2387       }
2388       End = *MVI;
2389       MachineLocation MLoc;
2390       if (Begin->getNumOperands() == 3) {
2391         if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2392           MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2393       } else
2394         MLoc = Asm->getDebugValueLocation(Begin);
2395 
2396       const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
2397       const MCSymbol *SLabel = getLabelBeforeInsn(End);
2398       if (MLoc.getReg())
2399         DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc));
2400 
2401       Begin = End;
2402       if (MVI + 1 == MVE) {
2403         // If End is the last instruction then its value is valid
2404         // until the end of the funtion.
2405         MachineLocation EMLoc;
2406         if (End->getNumOperands() == 3) {
2407           if (End->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2408           EMLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2409         } else
2410           EMLoc = Asm->getDebugValueLocation(End);
2411         if (EMLoc.getReg())
2412           DotDebugLocEntries.
2413             push_back(DotDebugLocEntry(SLabel, FunctionEndSym, EMLoc));
2414       }
2415     }
2416     DotDebugLocEntries.push_back(DotDebugLocEntry());
2417   }
2418 
2419   // Collect info for variables that were optimized out.
2420   const Function *F = MF->getFunction();
2421   const Module *M = F->getParent();
2422   if (NamedMDNode *NMD =
2423       M->getNamedMetadata(Twine("llvm.dbg.lv.",
2424                                 getRealLinkageName(F->getName())))) {
2425     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2426       DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2427       if (!DV || !Processed.insert(DV))
2428         continue;
2429       DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
2430       if (Scope)
2431         Scope->addVariable(new DbgVariable(DV));
2432     }
2433   }
2434 }
2435 
2436 /// getLabelBeforeInsn - Return Label preceding the instruction.
2437 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
2438   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2439     LabelsBeforeInsn.find(MI);
2440   if (I == LabelsBeforeInsn.end())
2441     // FunctionBeginSym always preceeds all the instruction in current function.
2442     return FunctionBeginSym;
2443   return I->second;
2444 }
2445 
2446 /// getLabelAfterInsn - Return Label immediately following the instruction.
2447 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
2448   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2449     LabelsAfterInsn.find(MI);
2450   if (I == LabelsAfterInsn.end())
2451     return NULL;
2452   return I->second;
2453 }
2454 
2455 /// beginScope - Process beginning of a scope.
2456 void DwarfDebug::beginScope(const MachineInstr *MI) {
2457   if (InsnNeedsLabel.count(MI) == 0) {
2458     LabelsBeforeInsn[MI] = PrevLabel;
2459     return;
2460   }
2461 
2462   // Check location.
2463   DebugLoc DL = MI->getDebugLoc();
2464   if (!DL.isUnknown()) {
2465     const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2466     PrevLabel = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2467     PrevInstLoc = DL;
2468     LabelsBeforeInsn[MI] = PrevLabel;
2469     return;
2470   }
2471 
2472   // If location is unknown then use temp label for this DBG_VALUE
2473   // instruction.
2474   if (MI->isDebugValue()) {
2475     PrevLabel = MMI->getContext().CreateTempSymbol();
2476     Asm->OutStreamer.EmitLabel(PrevLabel);
2477     LabelsBeforeInsn[MI] = PrevLabel;
2478     return;
2479   }
2480 
2481   if (UnknownLocations) {
2482     PrevLabel = recordSourceLine(0, 0, 0);
2483     LabelsBeforeInsn[MI] = PrevLabel;
2484     return;
2485   }
2486 
2487   assert (0 && "Instruction is not processed!");
2488 }
2489 
2490 /// endScope - Process end of a scope.
2491 void DwarfDebug::endScope(const MachineInstr *MI) {
2492   if (InsnsEndScopeSet.count(MI) != 0) {
2493     // Emit a label if this instruction ends a scope.
2494     MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2495     Asm->OutStreamer.EmitLabel(Label);
2496     LabelsAfterInsn[MI] = Label;
2497   }
2498 }
2499 
2500 /// getOrCreateDbgScope - Create DbgScope for the scope.
2501 DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
2502                                           const MDNode *InlinedAt) {
2503   if (!InlinedAt) {
2504     DbgScope *WScope = DbgScopeMap.lookup(Scope);
2505     if (WScope)
2506       return WScope;
2507     WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2508     DbgScopeMap.insert(std::make_pair(Scope, WScope));
2509     if (DIDescriptor(Scope).isLexicalBlock()) {
2510       DbgScope *Parent =
2511         getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
2512       WScope->setParent(Parent);
2513       Parent->addScope(WScope);
2514     }
2515 
2516     if (!WScope->getParent()) {
2517       StringRef SPName = DISubprogram(Scope).getLinkageName();
2518       // We used to check only for a linkage name, but that fails
2519       // since we began omitting the linkage name for private
2520       // functions.  The new way is to check for the name in metadata,
2521       // but that's not supported in old .ll test cases.  Ergo, we
2522       // check both.
2523       if (SPName == Asm->MF->getFunction()->getName() ||
2524           DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
2525         CurrentFnDbgScope = WScope;
2526     }
2527 
2528     return WScope;
2529   }
2530 
2531   getOrCreateAbstractScope(Scope);
2532   DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2533   if (WScope)
2534     return WScope;
2535 
2536   WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2537   DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2538   DILocation DL(InlinedAt);
2539   DbgScope *Parent =
2540     getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
2541   WScope->setParent(Parent);
2542   Parent->addScope(WScope);
2543 
2544   ConcreteScopes[InlinedAt] = WScope;
2545 
2546   return WScope;
2547 }
2548 
2549 /// hasValidLocation - Return true if debug location entry attached with
2550 /// machine instruction encodes valid location info.
2551 static bool hasValidLocation(LLVMContext &Ctx,
2552                              const MachineInstr *MInsn,
2553                              const MDNode *&Scope, const MDNode *&InlinedAt) {
2554   DebugLoc DL = MInsn->getDebugLoc();
2555   if (DL.isUnknown()) return false;
2556 
2557   const MDNode *S = DL.getScope(Ctx);
2558 
2559   // There is no need to create another DIE for compile unit. For all
2560   // other scopes, create one DbgScope now. This will be translated
2561   // into a scope DIE at the end.
2562   if (DIScope(S).isCompileUnit()) return false;
2563 
2564   Scope = S;
2565   InlinedAt = DL.getInlinedAt(Ctx);
2566   return true;
2567 }
2568 
2569 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2570 /// hierarchy.
2571 static void calculateDominanceGraph(DbgScope *Scope) {
2572   assert (Scope && "Unable to calculate scop edominance graph!");
2573   SmallVector<DbgScope *, 4> WorkStack;
2574   WorkStack.push_back(Scope);
2575   unsigned Counter = 0;
2576   while (!WorkStack.empty()) {
2577     DbgScope *WS = WorkStack.back();
2578     const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2579     bool visitedChildren = false;
2580     for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2581            SE = Children.end(); SI != SE; ++SI) {
2582       DbgScope *ChildScope = *SI;
2583       if (!ChildScope->getDFSOut()) {
2584         WorkStack.push_back(ChildScope);
2585         visitedChildren = true;
2586         ChildScope->setDFSIn(++Counter);
2587         break;
2588       }
2589     }
2590     if (!visitedChildren) {
2591       WorkStack.pop_back();
2592       WS->setDFSOut(++Counter);
2593     }
2594   }
2595 }
2596 
2597 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2598 static
2599 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2600                        DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2601 {
2602 #ifndef NDEBUG
2603   unsigned PrevDFSIn = 0;
2604   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2605        I != E; ++I) {
2606     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2607          II != IE; ++II) {
2608       const MachineInstr *MInsn = II;
2609       const MDNode *Scope = NULL;
2610       const MDNode *InlinedAt = NULL;
2611 
2612       // Check if instruction has valid location information.
2613       if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2614         dbgs() << " [ ";
2615         if (InlinedAt)
2616           dbgs() << "*";
2617         DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2618           MI2ScopeMap.find(MInsn);
2619         if (DI != MI2ScopeMap.end()) {
2620           DbgScope *S = DI->second;
2621           dbgs() << S->getDFSIn();
2622           PrevDFSIn = S->getDFSIn();
2623         } else
2624           dbgs() << PrevDFSIn;
2625       } else
2626         dbgs() << " [ x" << PrevDFSIn;
2627       dbgs() << " ]";
2628       MInsn->dump();
2629     }
2630     dbgs() << "\n";
2631   }
2632 #endif
2633 }
2634 /// extractScopeInformation - Scan machine instructions in this function
2635 /// and collect DbgScopes. Return true, if at least one scope was found.
2636 bool DwarfDebug::extractScopeInformation() {
2637   // If scope information was extracted using .dbg intrinsics then there is not
2638   // any need to extract these information by scanning each instruction.
2639   if (!DbgScopeMap.empty())
2640     return false;
2641 
2642   // Scan each instruction and create scopes. First build working set of scopes.
2643   LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2644   SmallVector<DbgRange, 4> MIRanges;
2645   DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2646   const MDNode *PrevScope = NULL;
2647   const MDNode *PrevInlinedAt = NULL;
2648   const MachineInstr *RangeBeginMI = NULL;
2649   const MachineInstr *PrevMI = NULL;
2650   for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2651        I != E; ++I) {
2652     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2653          II != IE; ++II) {
2654       const MachineInstr *MInsn = II;
2655       const MDNode *Scope = NULL;
2656       const MDNode *InlinedAt = NULL;
2657 
2658       // Check if instruction has valid location information.
2659       if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2660         PrevMI = MInsn;
2661         continue;
2662       }
2663 
2664       // If scope has not changed then skip this instruction.
2665       if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2666         PrevMI = MInsn;
2667         continue;
2668       }
2669 
2670       if (RangeBeginMI) {
2671         // If we have alread seen a beginning of a instruction range and
2672         // current instruction scope does not match scope of first instruction
2673         // in this range then create a new instruction range.
2674         DbgRange R(RangeBeginMI, PrevMI);
2675         MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
2676                                                         PrevInlinedAt);
2677         MIRanges.push_back(R);
2678       }
2679 
2680       // This is a beginning of a new instruction range.
2681       RangeBeginMI = MInsn;
2682 
2683       // Reset previous markers.
2684       PrevMI = MInsn;
2685       PrevScope = Scope;
2686       PrevInlinedAt = InlinedAt;
2687     }
2688   }
2689 
2690   // Create last instruction range.
2691   if (RangeBeginMI && PrevMI && PrevScope) {
2692     DbgRange R(RangeBeginMI, PrevMI);
2693     MIRanges.push_back(R);
2694     MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2695   }
2696 
2697   if (!CurrentFnDbgScope)
2698     return false;
2699 
2700   calculateDominanceGraph(CurrentFnDbgScope);
2701   if (PrintDbgScope)
2702     printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2703 
2704   // Find ranges of instructions covered by each DbgScope;
2705   DbgScope *PrevDbgScope = NULL;
2706   for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2707          RE = MIRanges.end(); RI != RE; ++RI) {
2708     const DbgRange &R = *RI;
2709     DbgScope *S = MI2ScopeMap.lookup(R.first);
2710     assert (S && "Lost DbgScope for a machine instruction!");
2711     if (PrevDbgScope && !PrevDbgScope->dominates(S))
2712       PrevDbgScope->closeInsnRange(S);
2713     S->openInsnRange(R.first);
2714     S->extendInsnRange(R.second);
2715     PrevDbgScope = S;
2716   }
2717 
2718   if (PrevDbgScope)
2719     PrevDbgScope->closeInsnRange();
2720 
2721   identifyScopeMarkers();
2722 
2723   return !DbgScopeMap.empty();
2724 }
2725 
2726 /// identifyScopeMarkers() -
2727 /// Each DbgScope has first instruction and last instruction to mark beginning
2728 /// and end of a scope respectively. Create an inverse map that list scopes
2729 /// starts (and ends) with an instruction. One instruction may start (or end)
2730 /// multiple scopes. Ignore scopes that are not reachable.
2731 void DwarfDebug::identifyScopeMarkers() {
2732   SmallVector<DbgScope *, 4> WorkList;
2733   WorkList.push_back(CurrentFnDbgScope);
2734   while (!WorkList.empty()) {
2735     DbgScope *S = WorkList.pop_back_val();
2736 
2737     const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2738     if (!Children.empty())
2739       for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2740              SE = Children.end(); SI != SE; ++SI)
2741         WorkList.push_back(*SI);
2742 
2743     if (S->isAbstractScope())
2744       continue;
2745 
2746     const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2747     if (Ranges.empty())
2748       continue;
2749     for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2750            RE = Ranges.end(); RI != RE; ++RI) {
2751       assert(RI->first && "DbgRange does not have first instruction!");
2752       assert(RI->second && "DbgRange does not have second instruction!");
2753       InsnsEndScopeSet.insert(RI->second);
2754     }
2755   }
2756 }
2757 
2758 /// FindFirstDebugLoc - Find the first debug location in the function. This
2759 /// is intended to be an approximation for the source position of the
2760 /// beginning of the function.
2761 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2762   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2763        I != E; ++I)
2764     for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2765          MBBI != MBBE; ++MBBI) {
2766       DebugLoc DL = MBBI->getDebugLoc();
2767       if (!DL.isUnknown())
2768         return DL;
2769     }
2770   return DebugLoc();
2771 }
2772 
2773 /// beginFunction - Gather pre-function debug information.  Assumes being
2774 /// emitted immediately after the function entry point.
2775 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2776   if (!MMI->hasDebugInfo()) return;
2777   if (!extractScopeInformation()) return;
2778 
2779   FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2780                                         Asm->getFunctionNumber());
2781   // Assumes in correct section after the entry point.
2782   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2783 
2784   // Emit label for the implicitly defined dbg.stoppoint at the start of the
2785   // function.
2786   DebugLoc FDL = FindFirstDebugLoc(MF);
2787   if (FDL.isUnknown()) return;
2788 
2789   const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2790   const MDNode *TheScope = 0;
2791 
2792   DISubprogram SP = getDISubprogram(Scope);
2793   unsigned Line, Col;
2794   if (SP.Verify()) {
2795     Line = SP.getLineNumber();
2796     Col = 0;
2797     TheScope = SP;
2798   } else {
2799     Line = FDL.getLine();
2800     Col = FDL.getCol();
2801     TheScope = Scope;
2802   }
2803 
2804   recordSourceLine(Line, Col, TheScope);
2805 
2806   /// ProcessedArgs - Collection of arguments already processed.
2807   SmallPtrSet<const MDNode *, 8> ProcessedArgs;
2808 
2809   DebugLoc PrevLoc;
2810   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2811        I != E; ++I)
2812     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2813          II != IE; ++II) {
2814       const MachineInstr *MI = II;
2815       DebugLoc DL = MI->getDebugLoc();
2816       if (MI->isDebugValue()) {
2817         assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
2818         DIVariable DV(MI->getOperand(MI->getNumOperands() - 1).getMetadata());
2819         if (!DV.Verify()) continue;
2820         // If DBG_VALUE is for a local variable then it needs a label.
2821         if (DV.getTag() != dwarf::DW_TAG_arg_variable
2822             && isDbgValueInUndefinedReg(MI) == false)
2823           InsnNeedsLabel.insert(MI);
2824         // DBG_VALUE for inlined functions argument needs a label.
2825         else if (!DISubprogram(getDISubprogram(DV.getContext())).
2826                  describes(MF->getFunction()))
2827           InsnNeedsLabel.insert(MI);
2828         // DBG_VALUE indicating argument location change needs a label.
2829         else if (isDbgValueInUndefinedReg(MI) == false
2830                  && !ProcessedArgs.insert(DV))
2831           InsnNeedsLabel.insert(MI);
2832       } else {
2833         // If location is unknown then instruction needs a location only if
2834         // UnknownLocations flag is set.
2835         if (DL.isUnknown()) {
2836           if (UnknownLocations && !PrevLoc.isUnknown())
2837             InsnNeedsLabel.insert(MI);
2838         } else if (DL != PrevLoc)
2839           // Otherwise, instruction needs a location only if it is new location.
2840           InsnNeedsLabel.insert(MI);
2841       }
2842 
2843       if (!DL.isUnknown() || UnknownLocations)
2844         PrevLoc = DL;
2845     }
2846 
2847   PrevLabel = FunctionBeginSym;
2848 }
2849 
2850 /// endFunction - Gather and emit post-function debug information.
2851 ///
2852 void DwarfDebug::endFunction(const MachineFunction *MF) {
2853   if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2854 
2855   if (CurrentFnDbgScope) {
2856 
2857     // Define end label for subprogram.
2858     FunctionEndSym = Asm->GetTempSymbol("func_end",
2859                                         Asm->getFunctionNumber());
2860     // Assumes in correct section after the entry point.
2861     Asm->OutStreamer.EmitLabel(FunctionEndSym);
2862 
2863     SmallPtrSet<const MDNode *, 16> ProcessedVars;
2864     collectVariableInfo(MF, ProcessedVars);
2865 
2866     // Get function line info.
2867     if (!Lines.empty()) {
2868       // Get section line info.
2869       unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2870       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2871       std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2872       // Append the function info to section info.
2873       SectionLineInfos.insert(SectionLineInfos.end(),
2874                               Lines.begin(), Lines.end());
2875     }
2876 
2877     // Construct abstract scopes.
2878     for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2879            AE = AbstractScopesList.end(); AI != AE; ++AI) {
2880       DISubprogram SP((*AI)->getScopeNode());
2881       if (SP.Verify()) {
2882         // Collect info for variables that were optimized out.
2883         StringRef FName = SP.getLinkageName();
2884         if (FName.empty())
2885           FName = SP.getName();
2886         const Module *M = MF->getFunction()->getParent();
2887         if (NamedMDNode *NMD =
2888             M->getNamedMetadata(Twine("llvm.dbg.lv.",
2889                                       getRealLinkageName(FName)))) {
2890           for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2891           DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2892           if (!DV || !ProcessedVars.insert(DV))
2893             continue;
2894           DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2895           if (Scope)
2896             Scope->addVariable(new DbgVariable(DV));
2897           }
2898         }
2899       }
2900       if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2901         constructScopeDIE(*AI);
2902     }
2903 
2904     DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2905 
2906     if (!DisableFramePointerElim(*MF))
2907       addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
2908               dwarf::DW_FORM_flag, 1);
2909 
2910 
2911     DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2912                                                  MMI->getFrameMoves()));
2913   }
2914 
2915   // Clear debug info
2916   CurrentFnDbgScope = NULL;
2917   InsnNeedsLabel.clear();
2918   DbgVariableToFrameIndexMap.clear();
2919   VarToAbstractVarMap.clear();
2920   DbgVariableToDbgInstMap.clear();
2921   DbgVariableLabelsMap.clear();
2922   DeleteContainerSeconds(DbgScopeMap);
2923   InsnsEndScopeSet.clear();
2924   ConcreteScopes.clear();
2925   DeleteContainerSeconds(AbstractScopes);
2926   AbstractScopesList.clear();
2927   AbstractVariables.clear();
2928   LabelsBeforeInsn.clear();
2929   LabelsAfterInsn.clear();
2930   Lines.clear();
2931   PrevLabel = NULL;
2932 }
2933 
2934 /// recordVariableFrameIndex - Record a variable's index.
2935 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2936   assert (V && "Invalid DbgVariable!");
2937   DbgVariableToFrameIndexMap[V] = Index;
2938 }
2939 
2940 /// findVariableFrameIndex - Return true if frame index for the variable
2941 /// is found. Update FI to hold value of the index.
2942 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2943   assert (V && "Invalid DbgVariable!");
2944   DenseMap<const DbgVariable *, int>::iterator I =
2945     DbgVariableToFrameIndexMap.find(V);
2946   if (I == DbgVariableToFrameIndexMap.end())
2947     return false;
2948   *FI = I->second;
2949   return true;
2950 }
2951 
2952 /// findVariableLabel - Find MCSymbol for the variable.
2953 const MCSymbol *DwarfDebug::findVariableLabel(const DbgVariable *V) {
2954   DenseMap<const DbgVariable *, const MCSymbol *>::iterator I
2955     = DbgVariableLabelsMap.find(V);
2956   if (I == DbgVariableLabelsMap.end())
2957     return NULL;
2958   else return I->second;
2959 }
2960 
2961 /// findDbgScope - Find DbgScope for the debug loc attached with an
2962 /// instruction.
2963 DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
2964   DbgScope *Scope = NULL;
2965   LLVMContext &Ctx =
2966     MInsn->getParent()->getParent()->getFunction()->getContext();
2967   DebugLoc DL = MInsn->getDebugLoc();
2968 
2969   if (DL.isUnknown())
2970     return Scope;
2971 
2972   if (const MDNode *IA = DL.getInlinedAt(Ctx))
2973     Scope = ConcreteScopes.lookup(IA);
2974   if (Scope == 0)
2975     Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2976 
2977   return Scope;
2978 }
2979 
2980 
2981 /// recordSourceLine - Register a source line with debug info. Returns the
2982 /// unique label that was emitted and which provides correspondence to
2983 /// the source line list.
2984 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2985                                        const MDNode *S) {
2986   StringRef Dir;
2987   StringRef Fn;
2988 
2989   unsigned Src = 1;
2990   if (S) {
2991     DIDescriptor Scope(S);
2992 
2993     if (Scope.isCompileUnit()) {
2994       DICompileUnit CU(S);
2995       Dir = CU.getDirectory();
2996       Fn = CU.getFilename();
2997     } else if (Scope.isSubprogram()) {
2998       DISubprogram SP(S);
2999       Dir = SP.getDirectory();
3000       Fn = SP.getFilename();
3001     } else if (Scope.isLexicalBlock()) {
3002       DILexicalBlock DB(S);
3003       Dir = DB.getDirectory();
3004       Fn = DB.getFilename();
3005     } else
3006       assert(0 && "Unexpected scope info");
3007 
3008     Src = GetOrCreateSourceID(Dir, Fn);
3009   }
3010 
3011   MCSymbol *Label = MMI->getContext().CreateTempSymbol();
3012   Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
3013 
3014   Asm->OutStreamer.EmitLabel(Label);
3015   return Label;
3016 }
3017 
3018 //===----------------------------------------------------------------------===//
3019 // Emit Methods
3020 //===----------------------------------------------------------------------===//
3021 
3022 /// computeSizeAndOffset - Compute the size and offset of a DIE.
3023 ///
3024 unsigned
3025 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
3026   // Get the children.
3027   const std::vector<DIE *> &Children = Die->getChildren();
3028 
3029   // If not last sibling and has children then add sibling offset attribute.
3030   if (!Last && !Children.empty())
3031     Die->addSiblingOffset(DIEValueAllocator);
3032 
3033   // Record the abbreviation.
3034   assignAbbrevNumber(Die->getAbbrev());
3035 
3036   // Get the abbreviation for this DIE.
3037   unsigned AbbrevNumber = Die->getAbbrevNumber();
3038   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3039 
3040   // Set DIE offset
3041   Die->setOffset(Offset);
3042 
3043   // Start the size with the size of abbreviation code.
3044   Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
3045 
3046   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3047   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3048 
3049   // Size the DIE attribute values.
3050   for (unsigned i = 0, N = Values.size(); i < N; ++i)
3051     // Size attribute value.
3052     Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
3053 
3054   // Size the DIE children if any.
3055   if (!Children.empty()) {
3056     assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
3057            "Children flag not set");
3058 
3059     for (unsigned j = 0, M = Children.size(); j < M; ++j)
3060       Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
3061 
3062     // End of children marker.
3063     Offset += sizeof(int8_t);
3064   }
3065 
3066   Die->setSize(Offset - Die->getOffset());
3067   return Offset;
3068 }
3069 
3070 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
3071 ///
3072 void DwarfDebug::computeSizeAndOffsets() {
3073   unsigned PrevOffset = 0;
3074   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3075          E = CUMap.end(); I != E; ++I) {
3076     // Compute size of compile unit header.
3077     static unsigned Offset = PrevOffset +
3078       sizeof(int32_t) + // Length of Compilation Unit Info
3079       sizeof(int16_t) + // DWARF version number
3080       sizeof(int32_t) + // Offset Into Abbrev. Section
3081       sizeof(int8_t);   // Pointer Size (in bytes)
3082     computeSizeAndOffset(I->second->getCUDie(), Offset, true);
3083     PrevOffset = Offset;
3084   }
3085 }
3086 
3087 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
3088 /// temporary label to it if SymbolStem is specified.
3089 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
3090                                 const char *SymbolStem = 0) {
3091   Asm->OutStreamer.SwitchSection(Section);
3092   if (!SymbolStem) return 0;
3093 
3094   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
3095   Asm->OutStreamer.EmitLabel(TmpSym);
3096   return TmpSym;
3097 }
3098 
3099 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
3100 /// the start of each one.
3101 void DwarfDebug::EmitSectionLabels() {
3102   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
3103 
3104   // Dwarf sections base addresses.
3105   if (Asm->MAI->doesDwarfRequireFrameSection()) {
3106     DwarfFrameSectionSym =
3107       EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
3108    }
3109 
3110   DwarfInfoSectionSym =
3111     EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
3112   DwarfAbbrevSectionSym =
3113     EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
3114   EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
3115 
3116   if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
3117     EmitSectionSym(Asm, MacroInfo);
3118 
3119   EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
3120   EmitSectionSym(Asm, TLOF.getDwarfLocSection());
3121   EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
3122   EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
3123   DwarfStrSectionSym =
3124     EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
3125   DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
3126                                              "debug_range");
3127 
3128   DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
3129                                            "section_debug_loc");
3130 
3131   TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
3132   EmitSectionSym(Asm, TLOF.getDataSection());
3133 }
3134 
3135 /// emitDIE - Recusively Emits a debug information entry.
3136 ///
3137 void DwarfDebug::emitDIE(DIE *Die) {
3138   // Get the abbreviation for this DIE.
3139   unsigned AbbrevNumber = Die->getAbbrevNumber();
3140   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3141 
3142   // Emit the code (index) for the abbreviation.
3143   if (Asm->isVerbose())
3144     Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
3145                                 Twine::utohexstr(Die->getOffset()) + ":0x" +
3146                                 Twine::utohexstr(Die->getSize()) + " " +
3147                                 dwarf::TagString(Abbrev->getTag()));
3148   Asm->EmitULEB128(AbbrevNumber);
3149 
3150   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3151   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3152 
3153   // Emit the DIE attribute values.
3154   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3155     unsigned Attr = AbbrevData[i].getAttribute();
3156     unsigned Form = AbbrevData[i].getForm();
3157     assert(Form && "Too many attributes for DIE (check abbreviation)");
3158 
3159     if (Asm->isVerbose())
3160       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
3161 
3162     switch (Attr) {
3163     case dwarf::DW_AT_sibling:
3164       Asm->EmitInt32(Die->getSiblingOffset());
3165       break;
3166     case dwarf::DW_AT_abstract_origin: {
3167       DIEEntry *E = cast<DIEEntry>(Values[i]);
3168       DIE *Origin = E->getEntry();
3169       unsigned Addr = Origin->getOffset();
3170       Asm->EmitInt32(Addr);
3171       break;
3172     }
3173     case dwarf::DW_AT_ranges: {
3174       // DW_AT_range Value encodes offset in debug_range section.
3175       DIEInteger *V = cast<DIEInteger>(Values[i]);
3176 
3177       if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
3178         Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
3179                                  V->getValue(),
3180                                  4);
3181       } else {
3182         Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
3183                                        V->getValue(),
3184                                        DwarfDebugRangeSectionSym,
3185                                        4);
3186       }
3187       break;
3188     }
3189     case dwarf::DW_AT_location: {
3190       if (UseDotDebugLocEntry.count(Die) != 0) {
3191         DIELabel *L = cast<DIELabel>(Values[i]);
3192         Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
3193       } else
3194         Values[i]->EmitValue(Asm, Form);
3195       break;
3196     }
3197     case dwarf::DW_AT_accessibility: {
3198       if (Asm->isVerbose()) {
3199         DIEInteger *V = cast<DIEInteger>(Values[i]);
3200         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
3201       }
3202       Values[i]->EmitValue(Asm, Form);
3203       break;
3204     }
3205     default:
3206       // Emit an attribute using the defined form.
3207       Values[i]->EmitValue(Asm, Form);
3208       break;
3209     }
3210   }
3211 
3212   // Emit the DIE children if any.
3213   if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
3214     const std::vector<DIE *> &Children = Die->getChildren();
3215 
3216     for (unsigned j = 0, M = Children.size(); j < M; ++j)
3217       emitDIE(Children[j]);
3218 
3219     if (Asm->isVerbose())
3220       Asm->OutStreamer.AddComment("End Of Children Mark");
3221     Asm->EmitInt8(0);
3222   }
3223 }
3224 
3225 /// emitDebugInfo - Emit the debug info section.
3226 ///
3227 void DwarfDebug::emitDebugInfo() {
3228   // Start debug info section.
3229   Asm->OutStreamer.SwitchSection(
3230                             Asm->getObjFileLowering().getDwarfInfoSection());
3231   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3232          E = CUMap.end(); I != E; ++I) {
3233     CompileUnit *TheCU = I->second;
3234     DIE *Die = TheCU->getCUDie();
3235 
3236     // Emit the compile units header.
3237     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
3238                                                   TheCU->getID()));
3239 
3240     // Emit size of content not including length itself
3241     unsigned ContentSize = Die->getSize() +
3242       sizeof(int16_t) + // DWARF version number
3243       sizeof(int32_t) + // Offset Into Abbrev. Section
3244       sizeof(int8_t) +  // Pointer Size (in bytes)
3245       sizeof(int32_t);  // FIXME - extra pad for gdb bug.
3246 
3247     Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
3248     Asm->EmitInt32(ContentSize);
3249     Asm->OutStreamer.AddComment("DWARF version number");
3250     Asm->EmitInt16(dwarf::DWARF_VERSION);
3251     Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
3252     Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
3253                            DwarfAbbrevSectionSym);
3254     Asm->OutStreamer.AddComment("Address Size (in bytes)");
3255     Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3256 
3257     emitDIE(Die);
3258     // FIXME - extra padding for gdb bug.
3259     Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
3260     Asm->EmitInt8(0);
3261     Asm->EmitInt8(0);
3262     Asm->EmitInt8(0);
3263     Asm->EmitInt8(0);
3264     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
3265   }
3266 }
3267 
3268 /// emitAbbreviations - Emit the abbreviation section.
3269 ///
3270 void DwarfDebug::emitAbbreviations() const {
3271   // Check to see if it is worth the effort.
3272   if (!Abbreviations.empty()) {
3273     // Start the debug abbrev section.
3274     Asm->OutStreamer.SwitchSection(
3275                             Asm->getObjFileLowering().getDwarfAbbrevSection());
3276 
3277     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
3278 
3279     // For each abbrevation.
3280     for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3281       // Get abbreviation data
3282       const DIEAbbrev *Abbrev = Abbreviations[i];
3283 
3284       // Emit the abbrevations code (base 1 index.)
3285       Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
3286 
3287       // Emit the abbreviations data.
3288       Abbrev->Emit(Asm);
3289     }
3290 
3291     // Mark end of abbreviations.
3292     Asm->EmitULEB128(0, "EOM(3)");
3293 
3294     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
3295   }
3296 }
3297 
3298 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
3299 /// the line matrix.
3300 ///
3301 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
3302   // Define last address of section.
3303   Asm->OutStreamer.AddComment("Extended Op");
3304   Asm->EmitInt8(0);
3305 
3306   Asm->OutStreamer.AddComment("Op size");
3307   Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3308   Asm->OutStreamer.AddComment("DW_LNE_set_address");
3309   Asm->EmitInt8(dwarf::DW_LNE_set_address);
3310 
3311   Asm->OutStreamer.AddComment("Section end label");
3312 
3313   Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
3314                                    Asm->getTargetData().getPointerSize(),
3315                                    0/*AddrSpace*/);
3316 
3317   // Mark end of matrix.
3318   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
3319   Asm->EmitInt8(0);
3320   Asm->EmitInt8(1);
3321   Asm->EmitInt8(1);
3322 }
3323 
3324 /// emitDebugLines - Emit source line information.
3325 ///
3326 void DwarfDebug::emitDebugLines() {
3327   // If the target is using .loc/.file, the assembler will be emitting the
3328   // .debug_line table automatically.
3329   if (Asm->MAI->hasDotLocAndDotFile())
3330     return;
3331 
3332   // Minimum line delta, thus ranging from -10..(255-10).
3333   const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
3334   // Maximum line delta, thus ranging from -10..(255-10).
3335   const int MaxLineDelta = 255 + MinLineDelta;
3336 
3337   // Start the dwarf line section.
3338   Asm->OutStreamer.SwitchSection(
3339                             Asm->getObjFileLowering().getDwarfLineSection());
3340 
3341   // Construct the section header.
3342   Asm->OutStreamer.AddComment("Length of Source Line Info");
3343   Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
3344                            Asm->GetTempSymbol("line_begin"), 4);
3345   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
3346 
3347   Asm->OutStreamer.AddComment("DWARF version number");
3348   Asm->EmitInt16(dwarf::DWARF_VERSION);
3349 
3350   Asm->OutStreamer.AddComment("Prolog Length");
3351   Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
3352                            Asm->GetTempSymbol("line_prolog_begin"), 4);
3353   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
3354 
3355   Asm->OutStreamer.AddComment("Minimum Instruction Length");
3356   Asm->EmitInt8(1);
3357   Asm->OutStreamer.AddComment("Default is_stmt_start flag");
3358   Asm->EmitInt8(1);
3359   Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
3360   Asm->EmitInt8(MinLineDelta);
3361   Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
3362   Asm->EmitInt8(MaxLineDelta);
3363   Asm->OutStreamer.AddComment("Special Opcode Base");
3364   Asm->EmitInt8(-MinLineDelta);
3365 
3366   // Line number standard opcode encodings argument count
3367   Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
3368   Asm->EmitInt8(0);
3369   Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
3370   Asm->EmitInt8(1);
3371   Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
3372   Asm->EmitInt8(1);
3373   Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
3374   Asm->EmitInt8(1);
3375   Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
3376   Asm->EmitInt8(1);
3377   Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
3378   Asm->EmitInt8(0);
3379   Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
3380   Asm->EmitInt8(0);
3381   Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
3382   Asm->EmitInt8(0);
3383   Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
3384   Asm->EmitInt8(1);
3385 
3386   // Emit directories.
3387   for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
3388     const std::string &Dir = getSourceDirectoryName(DI);
3389     if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
3390     Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
3391   }
3392 
3393   Asm->OutStreamer.AddComment("End of directories");
3394   Asm->EmitInt8(0);
3395 
3396   // Emit files.
3397   for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
3398     // Remember source id starts at 1.
3399     std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
3400     const std::string &FN = getSourceFileName(Id.second);
3401     if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
3402     Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
3403 
3404     Asm->EmitULEB128(Id.first, "Directory #");
3405     Asm->EmitULEB128(0, "Mod date");
3406     Asm->EmitULEB128(0, "File size");
3407   }
3408 
3409   Asm->OutStreamer.AddComment("End of files");
3410   Asm->EmitInt8(0);
3411 
3412   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
3413 
3414   // A sequence for each text section.
3415   unsigned SecSrcLinesSize = SectionSourceLines.size();
3416 
3417   for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
3418     // Isolate current sections line info.
3419     const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
3420 
3421     // Dwarf assumes we start with first line of first source file.
3422     unsigned Source = 1;
3423     unsigned Line = 1;
3424 
3425     // Construct rows of the address, source, line, column matrix.
3426     for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
3427       const SrcLineInfo &LineInfo = LineInfos[i];
3428       MCSymbol *Label = LineInfo.getLabel();
3429       if (!Label->isDefined()) continue; // Not emitted, in dead code.
3430 
3431       if (Asm->isVerbose()) {
3432         std::pair<unsigned, unsigned> SrcID =
3433           getSourceDirectoryAndFileIds(LineInfo.getSourceID());
3434         Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
3435                                     "/" +
3436                                     Twine(getSourceFileName(SrcID.second)) +
3437                                     ":" + Twine(LineInfo.getLine()));
3438       }
3439 
3440       // Define the line address.
3441       Asm->OutStreamer.AddComment("Extended Op");
3442       Asm->EmitInt8(0);
3443       Asm->OutStreamer.AddComment("Op size");
3444       Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3445 
3446       Asm->OutStreamer.AddComment("DW_LNE_set_address");
3447       Asm->EmitInt8(dwarf::DW_LNE_set_address);
3448 
3449       Asm->OutStreamer.AddComment("Location label");
3450       Asm->OutStreamer.EmitSymbolValue(Label,
3451                                        Asm->getTargetData().getPointerSize(),
3452                                        0/*AddrSpace*/);
3453 
3454       // If change of source, then switch to the new source.
3455       if (Source != LineInfo.getSourceID()) {
3456         Source = LineInfo.getSourceID();
3457         Asm->OutStreamer.AddComment("DW_LNS_set_file");
3458         Asm->EmitInt8(dwarf::DW_LNS_set_file);
3459         Asm->EmitULEB128(Source, "New Source");
3460       }
3461 
3462       // If change of line.
3463       if (Line != LineInfo.getLine()) {
3464         // Determine offset.
3465         int Offset = LineInfo.getLine() - Line;
3466         int Delta = Offset - MinLineDelta;
3467 
3468         // Update line.
3469         Line = LineInfo.getLine();
3470 
3471         // If delta is small enough and in range...
3472         if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3473           // ... then use fast opcode.
3474           Asm->OutStreamer.AddComment("Line Delta");
3475           Asm->EmitInt8(Delta - MinLineDelta);
3476         } else {
3477           // ... otherwise use long hand.
3478           Asm->OutStreamer.AddComment("DW_LNS_advance_line");
3479           Asm->EmitInt8(dwarf::DW_LNS_advance_line);
3480           Asm->EmitSLEB128(Offset, "Line Offset");
3481           Asm->OutStreamer.AddComment("DW_LNS_copy");
3482           Asm->EmitInt8(dwarf::DW_LNS_copy);
3483         }
3484       } else {
3485         // Copy the previous row (different address or source)
3486         Asm->OutStreamer.AddComment("DW_LNS_copy");
3487         Asm->EmitInt8(dwarf::DW_LNS_copy);
3488       }
3489     }
3490 
3491     emitEndOfLineMatrix(j + 1);
3492   }
3493 
3494   if (SecSrcLinesSize == 0)
3495     // Because we're emitting a debug_line section, we still need a line
3496     // table. The linker and friends expect it to exist. If there's nothing to
3497     // put into it, emit an empty table.
3498     emitEndOfLineMatrix(1);
3499 
3500   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3501 }
3502 
3503 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3504 ///
3505 void DwarfDebug::emitCommonDebugFrame() {
3506   if (!Asm->MAI->doesDwarfRequireFrameSection())
3507     return;
3508 
3509   int stackGrowth = Asm->getTargetData().getPointerSize();
3510   if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3511       TargetFrameInfo::StackGrowsDown)
3512     stackGrowth *= -1;
3513 
3514   // Start the dwarf frame section.
3515   Asm->OutStreamer.SwitchSection(
3516                               Asm->getObjFileLowering().getDwarfFrameSection());
3517 
3518   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3519   Asm->OutStreamer.AddComment("Length of Common Information Entry");
3520   Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3521                            Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3522 
3523   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3524   Asm->OutStreamer.AddComment("CIE Identifier Tag");
3525   Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3526   Asm->OutStreamer.AddComment("CIE Version");
3527   Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3528   Asm->OutStreamer.AddComment("CIE Augmentation");
3529   Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3530   Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3531   Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3532   Asm->OutStreamer.AddComment("CIE RA Column");
3533   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3534   Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3535 
3536   std::vector<MachineMove> Moves;
3537   RI->getInitialFrameState(Moves);
3538 
3539   Asm->EmitFrameMoves(Moves, 0, false);
3540 
3541   Asm->EmitAlignment(2);
3542   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3543 }
3544 
3545 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3546 /// section.
3547 void DwarfDebug::
3548 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3549   if (!Asm->MAI->doesDwarfRequireFrameSection())
3550     return;
3551 
3552   // Start the dwarf frame section.
3553   Asm->OutStreamer.SwitchSection(
3554                               Asm->getObjFileLowering().getDwarfFrameSection());
3555 
3556   Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3557   MCSymbol *DebugFrameBegin =
3558     Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3559   MCSymbol *DebugFrameEnd =
3560     Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3561   Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3562 
3563   Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3564 
3565   Asm->OutStreamer.AddComment("FDE CIE offset");
3566   Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3567                          DwarfFrameSectionSym);
3568 
3569   Asm->OutStreamer.AddComment("FDE initial location");
3570   MCSymbol *FuncBeginSym =
3571     Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3572   Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3573                                    Asm->getTargetData().getPointerSize(),
3574                                    0/*AddrSpace*/);
3575 
3576 
3577   Asm->OutStreamer.AddComment("FDE address range");
3578   Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3579                            FuncBeginSym, Asm->getTargetData().getPointerSize());
3580 
3581   Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3582 
3583   Asm->EmitAlignment(2);
3584   Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3585 }
3586 
3587 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3588 ///
3589 void DwarfDebug::emitDebugPubNames() {
3590   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3591          E = CUMap.end(); I != E; ++I) {
3592     CompileUnit *TheCU = I->second;
3593     // Start the dwarf pubnames section.
3594     Asm->OutStreamer.SwitchSection(
3595       Asm->getObjFileLowering().getDwarfPubNamesSection());
3596 
3597     Asm->OutStreamer.AddComment("Length of Public Names Info");
3598     Asm->EmitLabelDifference(
3599       Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
3600       Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
3601 
3602     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3603                                                   TheCU->getID()));
3604 
3605     Asm->OutStreamer.AddComment("DWARF Version");
3606     Asm->EmitInt16(dwarf::DWARF_VERSION);
3607 
3608     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3609     Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3610                            DwarfInfoSectionSym);
3611 
3612     Asm->OutStreamer.AddComment("Compilation Unit Length");
3613     Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3614                              Asm->GetTempSymbol("info_begin", TheCU->getID()),
3615                              4);
3616 
3617     const StringMap<DIE*> &Globals = TheCU->getGlobals();
3618     for (StringMap<DIE*>::const_iterator
3619            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3620       const char *Name = GI->getKeyData();
3621       DIE *Entity = GI->second;
3622 
3623       Asm->OutStreamer.AddComment("DIE offset");
3624       Asm->EmitInt32(Entity->getOffset());
3625 
3626       if (Asm->isVerbose())
3627         Asm->OutStreamer.AddComment("External Name");
3628       Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3629     }
3630 
3631     Asm->OutStreamer.AddComment("End Mark");
3632     Asm->EmitInt32(0);
3633     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3634                                                 TheCU->getID()));
3635   }
3636 }
3637 
3638 void DwarfDebug::emitDebugPubTypes() {
3639   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3640          E = CUMap.end(); I != E; ++I) {
3641     CompileUnit *TheCU = I->second;
3642     // Start the dwarf pubnames section.
3643     Asm->OutStreamer.SwitchSection(
3644       Asm->getObjFileLowering().getDwarfPubTypesSection());
3645     Asm->OutStreamer.AddComment("Length of Public Types Info");
3646     Asm->EmitLabelDifference(
3647       Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
3648       Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
3649 
3650     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3651                                                   TheCU->getID()));
3652 
3653     if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3654     Asm->EmitInt16(dwarf::DWARF_VERSION);
3655 
3656     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3657     Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3658                            DwarfInfoSectionSym);
3659 
3660     Asm->OutStreamer.AddComment("Compilation Unit Length");
3661     Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3662                              Asm->GetTempSymbol("info_begin", TheCU->getID()),
3663                              4);
3664 
3665     const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
3666     for (StringMap<DIE*>::const_iterator
3667            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3668       const char *Name = GI->getKeyData();
3669       DIE * Entity = GI->second;
3670 
3671       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3672       Asm->EmitInt32(Entity->getOffset());
3673 
3674       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3675       Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3676     }
3677 
3678     Asm->OutStreamer.AddComment("End Mark");
3679     Asm->EmitInt32(0);
3680     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3681                                                   TheCU->getID()));
3682   }
3683 }
3684 
3685 /// emitDebugStr - Emit visible names into a debug str section.
3686 ///
3687 void DwarfDebug::emitDebugStr() {
3688   // Check to see if it is worth the effort.
3689   if (StringPool.empty()) return;
3690 
3691   // Start the dwarf str section.
3692   Asm->OutStreamer.SwitchSection(
3693                                 Asm->getObjFileLowering().getDwarfStrSection());
3694 
3695   // Get all of the string pool entries and put them in an array by their ID so
3696   // we can sort them.
3697   SmallVector<std::pair<unsigned,
3698       StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3699 
3700   for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3701        I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3702     Entries.push_back(std::make_pair(I->second.second, &*I));
3703 
3704   array_pod_sort(Entries.begin(), Entries.end());
3705 
3706   for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3707     // Emit a label for reference from debug information entries.
3708     Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3709 
3710     // Emit the string itself.
3711     Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3712   }
3713 }
3714 
3715 /// emitDebugLoc - Emit visible names into a debug loc section.
3716 ///
3717 void DwarfDebug::emitDebugLoc() {
3718   if (DotDebugLocEntries.empty())
3719     return;
3720 
3721   // Start the dwarf loc section.
3722   Asm->OutStreamer.SwitchSection(
3723     Asm->getObjFileLowering().getDwarfLocSection());
3724   unsigned char Size = Asm->getTargetData().getPointerSize();
3725   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
3726   unsigned index = 1;
3727   for (SmallVector<DotDebugLocEntry, 4>::iterator
3728          I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
3729        I != E; ++I, ++index) {
3730     DotDebugLocEntry Entry = *I;
3731     if (Entry.isEmpty()) {
3732       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3733       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3734       Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
3735     } else {
3736       Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
3737       Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
3738       const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3739       unsigned Reg = RI->getDwarfRegNum(Entry.Loc.getReg(), false);
3740       if (int Offset =  Entry.Loc.getOffset()) {
3741         // If the value is at a certain offset from frame register then
3742         // use DW_OP_fbreg.
3743         unsigned OffsetSize = Offset ? MCAsmInfo::getSLEB128Size(Offset) : 1;
3744         Asm->OutStreamer.AddComment("Loc expr size");
3745         Asm->EmitInt16(1 + OffsetSize);
3746         Asm->OutStreamer.AddComment(
3747           dwarf::OperationEncodingString(dwarf::DW_OP_fbreg));
3748         Asm->EmitInt8(dwarf::DW_OP_fbreg);
3749         Asm->OutStreamer.AddComment("Offset");
3750         Asm->EmitSLEB128(Offset);
3751       } else {
3752         if (Reg < 32) {
3753           Asm->OutStreamer.AddComment("Loc expr size");
3754           Asm->EmitInt16(1);
3755           Asm->OutStreamer.AddComment(
3756             dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
3757           Asm->EmitInt8(dwarf::DW_OP_reg0 + Reg);
3758         } else {
3759           Asm->OutStreamer.AddComment("Loc expr size");
3760           Asm->EmitInt16(1 + MCAsmInfo::getULEB128Size(Reg));
3761           Asm->EmitInt8(dwarf::DW_OP_regx);
3762           Asm->EmitULEB128(Reg);
3763         }
3764       }
3765     }
3766   }
3767 }
3768 
3769 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3770 ///
3771 void DwarfDebug::EmitDebugARanges() {
3772   // Start the dwarf aranges section.
3773   Asm->OutStreamer.SwitchSection(
3774                           Asm->getObjFileLowering().getDwarfARangesSection());
3775 }
3776 
3777 /// emitDebugRanges - Emit visible names into a debug ranges section.
3778 ///
3779 void DwarfDebug::emitDebugRanges() {
3780   // Start the dwarf ranges section.
3781   Asm->OutStreamer.SwitchSection(
3782     Asm->getObjFileLowering().getDwarfRangesSection());
3783   unsigned char Size = Asm->getTargetData().getPointerSize();
3784   for (SmallVector<const MCSymbol *, 8>::iterator
3785          I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
3786        I != E; ++I) {
3787     if (*I)
3788       Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3789     else
3790       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3791   }
3792 }
3793 
3794 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3795 ///
3796 void DwarfDebug::emitDebugMacInfo() {
3797   if (const MCSection *LineInfo =
3798       Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3799     // Start the dwarf macinfo section.
3800     Asm->OutStreamer.SwitchSection(LineInfo);
3801   }
3802 }
3803 
3804 /// emitDebugInlineInfo - Emit inline info using following format.
3805 /// Section Header:
3806 /// 1. length of section
3807 /// 2. Dwarf version number
3808 /// 3. address size.
3809 ///
3810 /// Entries (one "entry" for each function that was inlined):
3811 ///
3812 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3813 ///   otherwise offset into __debug_str for regular function name.
3814 /// 2. offset into __debug_str section for regular function name.
3815 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3816 /// instances for the function.
3817 ///
3818 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3819 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3820 /// __debug_info section, and the low_pc is the starting address for the
3821 /// inlining instance.
3822 void DwarfDebug::emitDebugInlineInfo() {
3823   if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3824     return;
3825 
3826   if (!FirstCU)
3827     return;
3828 
3829   Asm->OutStreamer.SwitchSection(
3830                         Asm->getObjFileLowering().getDwarfDebugInlineSection());
3831 
3832   Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3833   Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3834                            Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3835 
3836   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3837 
3838   Asm->OutStreamer.AddComment("Dwarf Version");
3839   Asm->EmitInt16(dwarf::DWARF_VERSION);
3840   Asm->OutStreamer.AddComment("Address Size (in bytes)");
3841   Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3842 
3843   for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3844          E = InlinedSPNodes.end(); I != E; ++I) {
3845 
3846     const MDNode *Node = *I;
3847     DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3848       = InlineInfo.find(Node);
3849     SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3850     DISubprogram SP(Node);
3851     StringRef LName = SP.getLinkageName();
3852     StringRef Name = SP.getName();
3853 
3854     Asm->OutStreamer.AddComment("MIPS linkage name");
3855     if (LName.empty()) {
3856       Asm->OutStreamer.EmitBytes(Name, 0);
3857       Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3858     } else
3859       Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3860                              DwarfStrSectionSym);
3861 
3862     Asm->OutStreamer.AddComment("Function name");
3863     Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3864     Asm->EmitULEB128(Labels.size(), "Inline count");
3865 
3866     for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3867            LE = Labels.end(); LI != LE; ++LI) {
3868       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3869       Asm->EmitInt32(LI->second->getOffset());
3870 
3871       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3872       Asm->OutStreamer.EmitSymbolValue(LI->first,
3873                                        Asm->getTargetData().getPointerSize(),0);
3874     }
3875   }
3876 
3877   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
3878 }
3879