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