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