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