DwarfDebug.cpp revision b865d46d95a4c5073d0c006ccc1773641f88fc98
1//===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for writing dwarf debug info into asm files.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "dwarfdebug"
15#include "DwarfDebug.h"
16#include "DIE.h"
17#include "DwarfCompileUnit.h"
18#include "llvm/Constants.h"
19#include "llvm/Module.h"
20#include "llvm/Instructions.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineModuleInfo.h"
23#include "llvm/MC/MCAsmInfo.h"
24#include "llvm/MC/MCSection.h"
25#include "llvm/MC/MCStreamer.h"
26#include "llvm/MC/MCSymbol.h"
27#include "llvm/Target/Mangler.h"
28#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetFrameLowering.h"
30#include "llvm/Target/TargetLoweringObjectFile.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Target/TargetRegisterInfo.h"
33#include "llvm/Target/TargetOptions.h"
34#include "llvm/Analysis/DebugInfo.h"
35#include "llvm/Analysis/DIBuilder.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/ValueHandle.h"
43#include "llvm/Support/FormattedStream.h"
44#include "llvm/Support/Timer.h"
45#include "llvm/Support/Path.h"
46using namespace llvm;
47
48static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
49     cl::desc("Print DbgScope information for each machine instruction"));
50
51static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
52                                              cl::Hidden,
53     cl::desc("Disable debug info printing"));
54
55static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
56     cl::desc("Make an absence of debug location information explicit."),
57     cl::init(false));
58
59#ifndef NDEBUG
60STATISTIC(BlocksWithoutLineNo, "Number of blocks without any line number");
61#endif
62
63namespace {
64  const char *DWARFGroupName = "DWARF Emission";
65  const char *DbgTimerName = "DWARF Debug Writer";
66} // end anonymous namespace
67
68//===----------------------------------------------------------------------===//
69
70/// Configuration values for initial hash set sizes (log2).
71///
72static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
73
74namespace llvm {
75
76DIType DbgVariable::getType()               const {
77  DIType Ty = Var.getType();
78  // FIXME: isBlockByrefVariable should be reformulated in terms of complex
79  // addresses instead.
80  if (Var.isBlockByrefVariable()) {
81    /* Byref variables, in Blocks, are declared by the programmer as
82       "SomeType VarName;", but the compiler creates a
83       __Block_byref_x_VarName struct, and gives the variable VarName
84       either the struct, or a pointer to the struct, as its type.  This
85       is necessary for various behind-the-scenes things the compiler
86       needs to do with by-reference variables in blocks.
87
88       However, as far as the original *programmer* is concerned, the
89       variable should still have type 'SomeType', as originally declared.
90
91       The following function dives into the __Block_byref_x_VarName
92       struct to find the original type of the variable.  This will be
93       passed back to the code generating the type for the Debug
94       Information Entry for the variable 'VarName'.  'VarName' will then
95       have the original type 'SomeType' in its debug information.
96
97       The original type 'SomeType' will be the type of the field named
98       'VarName' inside the __Block_byref_x_VarName struct.
99
100       NOTE: In order for this to not completely fail on the debugger
101       side, the Debug Information Entry for the variable VarName needs to
102       have a DW_AT_location that tells the debugger how to unwind through
103       the pointers and __Block_byref_x_VarName struct to find the actual
104       value of the variable.  The function addBlockByrefType does this.  */
105    DIType subType = Ty;
106    unsigned tag = Ty.getTag();
107
108    if (tag == dwarf::DW_TAG_pointer_type) {
109      DIDerivedType DTy = DIDerivedType(Ty);
110      subType = DTy.getTypeDerivedFrom();
111    }
112
113    DICompositeType blockStruct = DICompositeType(subType);
114    DIArray Elements = blockStruct.getTypeArray();
115
116    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
117      DIDescriptor Element = Elements.getElement(i);
118      DIDerivedType DT = DIDerivedType(Element);
119      if (getName() == DT.getName())
120        return (DT.getTypeDerivedFrom());
121    }
122    return Ty;
123  }
124  return Ty;
125}
126
127//===----------------------------------------------------------------------===//
128/// DbgRange - This is used to track range of instructions with identical
129/// debug info scope.
130///
131typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
132
133//===----------------------------------------------------------------------===//
134/// DbgScope - This class is used to track scope information.
135///
136class DbgScope {
137  DbgScope *Parent;                   // Parent to this scope.
138  DIDescriptor Desc;                  // Debug info descriptor for scope.
139  // Location at which this scope is inlined.
140  AssertingVH<const MDNode> InlinedAtLocation;
141  bool AbstractScope;                 // Abstract Scope
142  const MachineInstr *LastInsn;       // Last instruction of this scope.
143  const MachineInstr *FirstInsn;      // First instruction of this scope.
144  unsigned DFSIn, DFSOut;
145  // Scopes defined in scope.  Contents not owned.
146  SmallVector<DbgScope *, 4> Scopes;
147  // Variables declared in scope.  Contents owned.
148  SmallVector<DbgVariable *, 8> Variables;
149  SmallVector<DbgRange, 4> Ranges;
150  // Private state for dump()
151  mutable unsigned IndentLevel;
152public:
153  DbgScope(DbgScope *P, DIDescriptor D, const MDNode *I = 0)
154    : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
155      LastInsn(0), FirstInsn(0),
156      DFSIn(0), DFSOut(0), IndentLevel(0) {}
157  virtual ~DbgScope();
158
159  // Accessors.
160  DbgScope *getParent()          const { return Parent; }
161  void setParent(DbgScope *P)          { Parent = P; }
162  DIDescriptor getDesc()         const { return Desc; }
163  const MDNode *getInlinedAt()         const { return InlinedAtLocation; }
164  const MDNode *getScopeNode()         const { return Desc; }
165  const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
166  const SmallVector<DbgVariable *, 8> &getDbgVariables() { return Variables; }
167  const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
168
169  /// openInsnRange - This scope covers instruction range starting from MI.
170  void openInsnRange(const MachineInstr *MI) {
171    if (!FirstInsn)
172      FirstInsn = MI;
173
174    if (Parent)
175      Parent->openInsnRange(MI);
176  }
177
178  /// extendInsnRange - Extend the current instruction range covered by
179  /// this scope.
180  void extendInsnRange(const MachineInstr *MI) {
181    assert (FirstInsn && "MI Range is not open!");
182    LastInsn = MI;
183    if (Parent)
184      Parent->extendInsnRange(MI);
185  }
186
187  /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
188  /// until now. This is used when a new scope is encountered while walking
189  /// machine instructions.
190  void closeInsnRange(DbgScope *NewScope = NULL) {
191    assert (LastInsn && "Last insn missing!");
192    Ranges.push_back(DbgRange(FirstInsn, LastInsn));
193    FirstInsn = NULL;
194    LastInsn = NULL;
195    // If Parent dominates NewScope then do not close Parent's instruction
196    // range.
197    if (Parent && (!NewScope || !Parent->dominates(NewScope)))
198      Parent->closeInsnRange(NewScope);
199  }
200
201  void setAbstractScope() { AbstractScope = true; }
202  bool isAbstractScope() const { return AbstractScope; }
203
204  // Depth First Search support to walk and mainpluate DbgScope hierarchy.
205  unsigned getDFSOut() const { return DFSOut; }
206  void setDFSOut(unsigned O) { DFSOut = O; }
207  unsigned getDFSIn() const  { return DFSIn; }
208  void setDFSIn(unsigned I)  { DFSIn = I; }
209  bool dominates(const DbgScope *S) {
210    if (S == this)
211      return true;
212    if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
213      return true;
214    return false;
215  }
216
217  /// addScope - Add a scope to the scope.
218  ///
219  void addScope(DbgScope *S) { Scopes.push_back(S); }
220
221  /// addVariable - Add a variable to the scope.
222  ///
223  void addVariable(DbgVariable *V) { Variables.push_back(V); }
224
225#ifndef NDEBUG
226  void dump() const;
227#endif
228};
229
230} // end llvm namespace
231
232#ifndef NDEBUG
233void DbgScope::dump() const {
234  raw_ostream &err = dbgs();
235  err.indent(IndentLevel);
236  const MDNode *N = Desc;
237  N->dump();
238  if (AbstractScope)
239    err << "Abstract Scope\n";
240
241  IndentLevel += 2;
242  if (!Scopes.empty())
243    err << "Children ...\n";
244  for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
245    if (Scopes[i] != this)
246      Scopes[i]->dump();
247
248  IndentLevel -= 2;
249}
250#endif
251
252DbgScope::~DbgScope() {
253  for (unsigned j = 0, M = Variables.size(); j < M; ++j)
254    delete Variables[j];
255}
256
257DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
258  : Asm(A), MMI(Asm->MMI), FirstCU(0),
259    AbbreviationsSet(InitAbbreviationsSetSize),
260    CurrentFnDbgScope(0), PrevLabel(NULL) {
261  NextStringPoolNumber = 0;
262
263  DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
264  DwarfStrSectionSym = TextSectionSym = 0;
265  DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
266  FunctionBeginSym = FunctionEndSym = 0;
267  {
268    NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
269    beginModule(M);
270  }
271}
272DwarfDebug::~DwarfDebug() {
273}
274
275MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
276  std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
277  if (Entry.first) return Entry.first;
278
279  Entry.second = NextStringPoolNumber++;
280  return Entry.first = Asm->GetTempSymbol("string", Entry.second);
281}
282
283
284/// assignAbbrevNumber - Define a unique number for the abbreviation.
285///
286void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
287  // Profile the node so that we can make it unique.
288  FoldingSetNodeID ID;
289  Abbrev.Profile(ID);
290
291  // Check the set for priors.
292  DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
293
294  // If it's newly added.
295  if (InSet == &Abbrev) {
296    // Add to abbreviation list.
297    Abbreviations.push_back(&Abbrev);
298
299    // Assign the vector position + 1 as its number.
300    Abbrev.setNumber(Abbreviations.size());
301  } else {
302    // Assign existing abbreviation number.
303    Abbrev.setNumber(InSet->getNumber());
304  }
305}
306
307/// getRealLinkageName - If special LLVM prefix that is used to inform the asm
308/// printer to not emit usual symbol prefix before the symbol name is used then
309/// return linkage name after skipping this special LLVM prefix.
310static StringRef getRealLinkageName(StringRef LinkageName) {
311  char One = '\1';
312  if (LinkageName.startswith(StringRef(&One, 1)))
313    return LinkageName.substr(1);
314  return LinkageName;
315}
316
317/// createSubprogramDIE - Create new DIE using SP.
318DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
319  CompileUnit *SPCU = getCompileUnit(SP);
320  DIE *SPDie = SPCU->getDIE(SP);
321  if (SPDie)
322    return SPDie;
323
324  SPDie = new DIE(dwarf::DW_TAG_subprogram);
325
326  // DW_TAG_inlined_subroutine may refer to this DIE.
327  SPCU->insertDIE(SP, SPDie);
328
329  // Add to context owner.
330  SPCU->addToContextOwner(SPDie, SP.getContext());
331
332  // Add function template parameters.
333  SPCU->addTemplateParams(*SPDie, SP.getTemplateParams());
334
335  // If this DIE is going to refer declaration info using AT_specification
336  // then there is no need to add other attributes.
337  if (SP.getFunctionDeclaration().isSubprogram())
338    return SPDie;
339
340  // Constructors and operators for anonymous aggregates do not have names.
341  if (!SP.getName().empty())
342    SPCU->addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
343                    SP.getName());
344
345  StringRef LinkageName = SP.getLinkageName();
346  if (!LinkageName.empty())
347    SPCU->addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
348                    getRealLinkageName(LinkageName));
349
350  SPCU->addSourceLine(SPDie, SP);
351
352  if (SP.isPrototyped())
353    SPCU->addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
354
355  // Add Return Type.
356  DICompositeType SPTy = SP.getType();
357  DIArray Args = SPTy.getTypeArray();
358  unsigned SPTag = SPTy.getTag();
359
360  if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
361    SPCU->addType(SPDie, SPTy);
362  else
363    SPCU->addType(SPDie, DIType(Args.getElement(0)));
364
365  unsigned VK = SP.getVirtuality();
366  if (VK) {
367    SPCU->addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
368    DIEBlock *Block = SPCU->getDIEBlock();
369    SPCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
370    SPCU->addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
371    SPCU->addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
372    ContainingTypeMap.insert(std::make_pair(SPDie,
373                                            SP.getContainingType()));
374  }
375
376  if (!SP.isDefinition()) {
377    SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
378
379    // Add arguments. Do not add arguments for subprogram definition. They will
380    // be handled while processing variables.
381    DICompositeType SPTy = SP.getType();
382    DIArray Args = SPTy.getTypeArray();
383    unsigned SPTag = SPTy.getTag();
384
385    if (SPTag == dwarf::DW_TAG_subroutine_type)
386      for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
387        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
388        DIType ATy = DIType(DIType(Args.getElement(i)));
389        SPCU->addType(Arg, ATy);
390        if (ATy.isArtificial())
391          SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
392        SPDie->addChild(Arg);
393      }
394  }
395
396  if (SP.isArtificial())
397    SPCU->addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
398
399  if (!SP.isLocalToUnit())
400    SPCU->addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
401
402  if (SP.isOptimized())
403    SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
404
405  if (unsigned isa = Asm->getISAEncoding()) {
406    SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
407  }
408
409  return SPDie;
410}
411
412DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
413  assert(N && "Invalid Scope encoding!");
414
415  DbgScope *AScope = AbstractScopes.lookup(N);
416  if (AScope)
417    return AScope;
418
419  DbgScope *Parent = NULL;
420
421  DIDescriptor Scope(N);
422  if (Scope.isLexicalBlock()) {
423    DILexicalBlock DB(N);
424    DIDescriptor ParentDesc = DB.getContext();
425    Parent = getOrCreateAbstractScope(ParentDesc);
426  }
427
428  AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
429
430  if (Parent)
431    Parent->addScope(AScope);
432  AScope->setAbstractScope();
433  AbstractScopes[N] = AScope;
434  if (DIDescriptor(N).isSubprogram())
435    AbstractScopesList.push_back(AScope);
436  return AScope;
437}
438
439/// isSubprogramContext - Return true if Context is either a subprogram
440/// or another context nested inside a subprogram.
441static bool isSubprogramContext(const MDNode *Context) {
442  if (!Context)
443    return false;
444  DIDescriptor D(Context);
445  if (D.isSubprogram())
446    return true;
447  if (D.isType())
448    return isSubprogramContext(DIType(Context).getContext());
449  return false;
450}
451
452/// updateSubprogramScopeDIE - Find DIE for the given subprogram and
453/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
454/// If there are global variables in this scope then create and insert
455/// DIEs for these variables.
456DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
457  CompileUnit *SPCU = getCompileUnit(SPNode);
458  DIE *SPDie = SPCU->getDIE(SPNode);
459
460  assert(SPDie && "Unable to find subprogram DIE!");
461  DISubprogram SP(SPNode);
462
463  DISubprogram SPDecl = SP.getFunctionDeclaration();
464  if (SPDecl.isSubprogram())
465    // Refer function declaration directly.
466    SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
467                      createSubprogramDIE(SPDecl));
468  else {
469    // There is not any need to generate specification DIE for a function
470    // defined at compile unit level. If a function is defined inside another
471    // function then gdb prefers the definition at top level and but does not
472    // expect specification DIE in parent function. So avoid creating
473    // specification DIE for a function defined inside a function.
474    if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
475        !SP.getContext().isFile() &&
476        !isSubprogramContext(SP.getContext())) {
477      SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
478
479      // Add arguments.
480      DICompositeType SPTy = SP.getType();
481      DIArray Args = SPTy.getTypeArray();
482      unsigned SPTag = SPTy.getTag();
483      if (SPTag == dwarf::DW_TAG_subroutine_type)
484        for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
485          DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
486          DIType ATy = DIType(DIType(Args.getElement(i)));
487          SPCU->addType(Arg, ATy);
488          if (ATy.isArtificial())
489            SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
490          SPDie->addChild(Arg);
491        }
492      DIE *SPDeclDie = SPDie;
493      SPDie = new DIE(dwarf::DW_TAG_subprogram);
494      SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
495                        SPDeclDie);
496      SPCU->addDie(SPDie);
497    }
498  }
499  // Pick up abstract subprogram DIE.
500  if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
501    SPDie = new DIE(dwarf::DW_TAG_subprogram);
502    SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
503                      dwarf::DW_FORM_ref4, AbsSPDIE);
504    SPCU->addDie(SPDie);
505  }
506
507  SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
508                 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
509  SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
510                 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
511  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
512  MachineLocation Location(RI->getFrameRegister(*Asm->MF));
513  SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
514
515  return SPDie;
516}
517
518/// constructLexicalScope - Construct new DW_TAG_lexical_block
519/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
520DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
521
522  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
523  if (Scope->isAbstractScope())
524    return ScopeDIE;
525
526  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
527  if (Ranges.empty())
528    return 0;
529
530  CompileUnit *TheCU = getCompileUnit(Scope->getScopeNode());
531  SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
532  if (Ranges.size() > 1) {
533    // .debug_range section has not been laid out yet. Emit offset in
534    // .debug_range as a uint, size 4, for now. emitDIE will handle
535    // DW_AT_ranges appropriately.
536    TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
537                   DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
538    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
539         RE = Ranges.end(); RI != RE; ++RI) {
540      DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
541      DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
542    }
543    DebugRangeSymbols.push_back(NULL);
544    DebugRangeSymbols.push_back(NULL);
545    return ScopeDIE;
546  }
547
548  const MCSymbol *Start = getLabelBeforeInsn(RI->first);
549  const MCSymbol *End = getLabelAfterInsn(RI->second);
550
551  if (End == 0) return 0;
552
553  assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
554  assert(End->isDefined() && "Invalid end label for an inlined scope!");
555
556  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
557  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
558
559  return ScopeDIE;
560}
561
562/// constructInlinedScopeDIE - This scope represents inlined body of
563/// a function. Construct DIE to represent this concrete inlined copy
564/// of the function.
565DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
566
567  const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
568  assert (Ranges.empty() == false
569          && "DbgScope does not have instruction markers!");
570
571  // FIXME : .debug_inlined section specification does not clearly state how
572  // to emit inlined scope that is split into multiple instruction ranges.
573  // For now, use first instruction range and emit low_pc/high_pc pair and
574  // corresponding .debug_inlined section entry for this pair.
575  SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
576  const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
577  const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
578
579  if (StartLabel == 0 || EndLabel == 0) {
580    assert (0 && "Unexpected Start and End  labels for a inlined scope!");
581    return 0;
582  }
583  assert(StartLabel->isDefined() &&
584         "Invalid starting label for an inlined scope!");
585  assert(EndLabel->isDefined() &&
586         "Invalid end label for an inlined scope!");
587
588  if (!Scope->getScopeNode())
589    return NULL;
590  DIScope DS(Scope->getScopeNode());
591  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
592
593  DISubprogram InlinedSP = getDISubprogram(DS);
594  CompileUnit *TheCU = getCompileUnit(InlinedSP);
595  DIE *OriginDIE = TheCU->getDIE(InlinedSP);
596  assert(OriginDIE && "Unable to find Origin DIE!");
597  TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
598                     dwarf::DW_FORM_ref4, OriginDIE);
599
600  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
601  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
602
603  InlinedSubprogramDIEs.insert(OriginDIE);
604
605  // Track the start label for this inlined function.
606  DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
607    I = InlineInfo.find(InlinedSP);
608
609  if (I == InlineInfo.end()) {
610    InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
611                                                             ScopeDIE));
612    InlinedSPNodes.push_back(InlinedSP);
613  } else
614    I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
615
616  DILocation DL(Scope->getInlinedAt());
617  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
618  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
619
620  return ScopeDIE;
621}
622
623
624/// constructVariableDIE - Construct a DIE for the given DbgVariable.
625DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
626  StringRef Name = DV->getName();
627  if (Name.empty())
628    return NULL;
629
630  // Translate tag to proper Dwarf tag.  The result variable is dropped for
631  // now.
632  unsigned Tag;
633  switch (DV->getTag()) {
634  case dwarf::DW_TAG_return_variable:
635    return NULL;
636  case dwarf::DW_TAG_arg_variable:
637    Tag = dwarf::DW_TAG_formal_parameter;
638    break;
639  case dwarf::DW_TAG_auto_variable:    // fall thru
640  default:
641    Tag = dwarf::DW_TAG_variable;
642    break;
643  }
644
645  // Define variable debug information entry.
646  DIE *VariableDie = new DIE(Tag);
647  CompileUnit *TheCU = getCompileUnit(DV->getVariable());
648  DIE *AbsDIE = NULL;
649  DenseMap<const DbgVariable *, const DbgVariable *>::iterator
650    V2AVI = VarToAbstractVarMap.find(DV);
651  if (V2AVI != VarToAbstractVarMap.end())
652    AbsDIE = V2AVI->second->getDIE();
653
654  if (AbsDIE)
655    TheCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
656                       dwarf::DW_FORM_ref4, AbsDIE);
657  else {
658    TheCU->addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
659    TheCU->addSourceLine(VariableDie, DV->getVariable());
660
661    // Add variable type.
662    TheCU->addType(VariableDie, DV->getType());
663  }
664
665  if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
666    TheCU->addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
667  else if (DIVariable(DV->getVariable()).isArtificial())
668    TheCU->addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
669
670  if (Scope->isAbstractScope()) {
671    DV->setDIE(VariableDie);
672    return VariableDie;
673  }
674
675  // Add variable address.
676
677  unsigned Offset = DV->getDotDebugLocOffset();
678  if (Offset != ~0U) {
679    TheCU->addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
680             Asm->GetTempSymbol("debug_loc", Offset));
681    DV->setDIE(VariableDie);
682    UseDotDebugLocEntry.insert(VariableDie);
683    return VariableDie;
684  }
685
686  // Check if variable is described by a  DBG_VALUE instruction.
687  DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
688    DbgVariableToDbgInstMap.find(DV);
689  if (DVI != DbgVariableToDbgInstMap.end()) {
690    const MachineInstr *DVInsn = DVI->second;
691    bool updated = false;
692    // FIXME : Handle getNumOperands != 3
693    if (DVInsn->getNumOperands() == 3) {
694      if (DVInsn->getOperand(0).isReg()) {
695        const MachineOperand RegOp = DVInsn->getOperand(0);
696        const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
697        if (DVInsn->getOperand(1).isImm() &&
698            TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
699          TheCU->addFrameVariableAddress(DV, VariableDie,
700                                         DVInsn->getOperand(1).getImm());
701          updated = true;
702        } else
703          updated = TheCU->addRegisterAddress(VariableDie, RegOp);
704      }
705      else if (DVInsn->getOperand(0).isImm())
706        updated = TheCU->addConstantValue(VariableDie, DVInsn->getOperand(0));
707      else if (DVInsn->getOperand(0).isFPImm())
708        updated =
709          TheCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
710    } else {
711      MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
712      if (Location.getReg()) {
713        if (DV->getVariable().hasComplexAddress())
714          TheCU->addComplexAddress(DV, VariableDie, dwarf::DW_AT_location,
715                                   Location);
716        else
717          TheCU->addAddress(VariableDie, dwarf::DW_AT_location, Location);
718        updated = true;
719      }
720    }
721    if (!updated) {
722      // If variableDie is not updated then DBG_VALUE instruction does not
723      // have valid variable info.
724      delete VariableDie;
725      return NULL;
726    }
727    DV->setDIE(VariableDie);
728    return VariableDie;
729  }
730
731  // .. else use frame index, if available.
732  int FI = 0;
733  if (findVariableFrameIndex(DV, &FI))
734    TheCU->addFrameVariableAddress(DV, VariableDie, FI);
735
736  DV->setDIE(VariableDie);
737  return VariableDie;
738
739}
740
741void CompileUnit::addPubTypes(DISubprogram SP) {
742  DICompositeType SPTy = SP.getType();
743  unsigned SPTag = SPTy.getTag();
744  if (SPTag != dwarf::DW_TAG_subroutine_type)
745    return;
746
747  DIArray Args = SPTy.getTypeArray();
748  for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
749    DIType ATy(Args.getElement(i));
750    if (!ATy.Verify())
751      continue;
752    DICompositeType CATy = getDICompositeType(ATy);
753    if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
754        && !CATy.isForwardDecl()) {
755      if (DIEEntry *Entry = getDIEEntry(CATy))
756        addGlobalType(CATy.getName(), Entry->getEntry());
757    }
758  }
759}
760
761/// constructScopeDIE - Construct a DIE for this scope.
762DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
763  if (!Scope || !Scope->getScopeNode())
764    return NULL;
765
766  SmallVector <DIE *, 8> Children;
767
768  // Collect arguments for current function.
769  if (Scope == CurrentFnDbgScope)
770    for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
771      if (DbgVariable *ArgDV = CurrentFnArguments[i])
772        if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
773          Children.push_back(Arg);
774
775  // Collect lexical scope childrens first.
776  const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
777  for (unsigned i = 0, N = Variables.size(); i < N; ++i)
778    if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
779      Children.push_back(Variable);
780  const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
781  for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
782    if (DIE *Nested = constructScopeDIE(Scopes[j]))
783      Children.push_back(Nested);
784  DIScope DS(Scope->getScopeNode());
785  DIE *ScopeDIE = NULL;
786  if (Scope->getInlinedAt())
787    ScopeDIE = constructInlinedScopeDIE(Scope);
788  else if (DS.isSubprogram()) {
789    ProcessedSPNodes.insert(DS);
790    if (Scope->isAbstractScope()) {
791      ScopeDIE = getCompileUnit(DS)->getDIE(DS);
792      // Note down abstract DIE.
793      if (ScopeDIE)
794        AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
795    }
796    else
797      ScopeDIE = updateSubprogramScopeDIE(DS);
798  }
799  else {
800    // There is no need to emit empty lexical block DIE.
801    if (Children.empty())
802      return NULL;
803    ScopeDIE = constructLexicalScopeDIE(Scope);
804  }
805
806  if (!ScopeDIE) return NULL;
807
808  // Add children
809  for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
810         E = Children.end(); I != E; ++I)
811    ScopeDIE->addChild(*I);
812
813  if (DS.isSubprogram())
814    getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
815
816 return ScopeDIE;
817}
818
819/// GetOrCreateSourceID - Look up the source id with the given directory and
820/// source file names. If none currently exists, create a new id and insert it
821/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
822/// maps as well.
823
824unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
825                                         StringRef DirName) {
826  // If FE did not provide a file name, then assume stdin.
827  if (FileName.empty())
828    return GetOrCreateSourceID("<stdin>", StringRef());
829
830  // MCStream expects full path name as filename.
831  if (!DirName.empty() && !FileName.startswith("/")) {
832    std::string FullPathName(DirName.data());
833    if (!DirName.endswith("/"))
834      FullPathName += "/";
835    FullPathName += FileName.data();
836    // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
837    return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
838  }
839
840  StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
841  if (Entry.getValue())
842    return Entry.getValue();
843
844  unsigned SrcId = SourceIdMap.size();
845  Entry.setValue(SrcId);
846
847  // Print out a .file directive to specify files for .loc directives.
848  Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
849
850  return SrcId;
851}
852
853/// getOrCreateNameSpace - Create a DIE for DINameSpace.
854DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
855  DIE *NDie = getDIE(NS);
856  if (NDie)
857    return NDie;
858  NDie = new DIE(dwarf::DW_TAG_namespace);
859  insertDIE(NS, NDie);
860  if (!NS.getName().empty())
861    addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
862  addSourceLine(NDie, NS);
863  addToContextOwner(NDie, NS.getContext());
864  return NDie;
865}
866
867/// constructCompileUnit - Create new CompileUnit for the given
868/// metadata node with tag DW_TAG_compile_unit.
869void DwarfDebug::constructCompileUnit(const MDNode *N) {
870  DICompileUnit DIUnit(N);
871  StringRef FN = DIUnit.getFilename();
872  StringRef Dir = DIUnit.getDirectory();
873  unsigned ID = GetOrCreateSourceID(FN, Dir);
874
875  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
876  CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
877  NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
878                   DIUnit.getProducer());
879  NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
880                 DIUnit.getLanguage());
881  NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
882  // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
883  // simplifies debug range entries.
884  NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
885  // DW_AT_stmt_list is a offset of line number information for this
886  // compile unit in debug_line section.
887  if (Asm->MAI->doesDwarfUsesAbsoluteLabelForStmtList())
888    NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_addr,
889                    Asm->GetTempSymbol("section_line"));
890  else
891    NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
892
893  if (!Dir.empty())
894    NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
895  if (DIUnit.isOptimized())
896    NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
897
898  StringRef Flags = DIUnit.getFlags();
899  if (!Flags.empty())
900    NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
901
902  unsigned RVer = DIUnit.getRunTimeVersion();
903  if (RVer)
904    NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
905            dwarf::DW_FORM_data1, RVer);
906
907  if (!FirstCU)
908    FirstCU = NewCU;
909  CUMap.insert(std::make_pair(N, NewCU));
910}
911
912/// getCompielUnit - Get CompileUnit DIE.
913CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
914  assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
915  DIDescriptor D(N);
916  const MDNode *CUNode = NULL;
917  if (D.isCompileUnit())
918    CUNode = N;
919  else if (D.isSubprogram())
920    CUNode = DISubprogram(N).getCompileUnit();
921  else if (D.isType())
922    CUNode = DIType(N).getCompileUnit();
923  else if (D.isGlobalVariable())
924    CUNode = DIGlobalVariable(N).getCompileUnit();
925  else if (D.isVariable())
926    CUNode = DIVariable(N).getCompileUnit();
927  else if (D.isNameSpace())
928    CUNode = DINameSpace(N).getCompileUnit();
929  else if (D.isFile())
930    CUNode = DIFile(N).getCompileUnit();
931  else
932    return FirstCU;
933
934  DenseMap<const MDNode *, CompileUnit *>::const_iterator I
935    = CUMap.find(CUNode);
936  if (I == CUMap.end())
937    return FirstCU;
938  return I->second;
939}
940
941/// isUnsignedDIType - Return true if type encoding is unsigned.
942static bool isUnsignedDIType(DIType Ty) {
943  DIDerivedType DTy(Ty);
944  if (DTy.Verify())
945    return isUnsignedDIType(DTy.getTypeDerivedFrom());
946
947  DIBasicType BTy(Ty);
948  if (BTy.Verify()) {
949    unsigned Encoding = BTy.getEncoding();
950    if (Encoding == dwarf::DW_ATE_unsigned ||
951        Encoding == dwarf::DW_ATE_unsigned_char)
952      return true;
953  }
954  return false;
955}
956
957// Return const exprssion if value is a GEP to access merged global
958// constant. e.g.
959// i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
960static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
961  const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
962  if (!CE || CE->getNumOperands() != 3 ||
963      CE->getOpcode() != Instruction::GetElementPtr)
964    return NULL;
965
966  // First operand points to a global value.
967  if (!isa<GlobalValue>(CE->getOperand(0)))
968    return NULL;
969
970  // Second operand is zero.
971  const ConstantInt *CI =
972    dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
973  if (!CI || !CI->isZero())
974    return NULL;
975
976  // Third operand is offset.
977  if (!isa<ConstantInt>(CE->getOperand(2)))
978    return NULL;
979
980  return CE;
981}
982
983/// constructGlobalVariableDIE - Construct global variable DIE.
984void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
985  DIGlobalVariable GV(N);
986
987  // If debug information is malformed then ignore it.
988  if (GV.Verify() == false)
989    return;
990
991  // Check for pre-existence.
992  CompileUnit *TheCU = getCompileUnit(N);
993  if (TheCU->getDIE(GV))
994    return;
995
996  DIType GTy = GV.getType();
997  DIE *VariableDIE = new DIE(GV.getTag());
998
999  bool isGlobalVariable = GV.getGlobal() != NULL;
1000
1001  // Add name.
1002  TheCU->addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1003                   GV.getDisplayName());
1004  StringRef LinkageName = GV.getLinkageName();
1005  if (!LinkageName.empty() && isGlobalVariable)
1006    TheCU->addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
1007                     dwarf::DW_FORM_string,
1008                     getRealLinkageName(LinkageName));
1009  // Add type.
1010  TheCU->addType(VariableDIE, GTy);
1011  if (GTy.isCompositeType() && !GTy.getName().empty()
1012      && !GTy.isForwardDecl()) {
1013    DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1014    assert(Entry && "Missing global type!");
1015    TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1016  }
1017  // Add scoping info.
1018  if (!GV.isLocalToUnit()) {
1019    TheCU->addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1020    // Expose as global.
1021    TheCU->addGlobal(GV.getName(), VariableDIE);
1022  }
1023  // Add line number info.
1024  TheCU->addSourceLine(VariableDIE, GV);
1025  // Add to map.
1026  TheCU->insertDIE(N, VariableDIE);
1027  // Add to context owner.
1028  DIDescriptor GVContext = GV.getContext();
1029  TheCU->addToContextOwner(VariableDIE, GVContext);
1030  // Add location.
1031  if (isGlobalVariable) {
1032    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1033    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1034    TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1035             Asm->Mang->getSymbol(GV.getGlobal()));
1036    // Do not create specification DIE if context is either compile unit
1037    // or a subprogram.
1038    if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1039        !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1040      // Create specification DIE.
1041      DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1042      TheCU->addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1043                  dwarf::DW_FORM_ref4, VariableDIE);
1044      TheCU->addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1045      TheCU->addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1046      TheCU->addDie(VariableSpecDIE);
1047    } else {
1048      TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1049    }
1050  } else if (ConstantInt *CI =
1051             dyn_cast_or_null<ConstantInt>(GV.getConstant()))
1052    TheCU->addConstantValue(VariableDIE, CI, isUnsignedDIType(GTy));
1053  else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1054    // GV is a merged global.
1055    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1056    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1057    TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1058                    Asm->Mang->getSymbol(cast<GlobalValue>(CE->getOperand(0))));
1059    ConstantInt *CII = cast<ConstantInt>(CE->getOperand(2));
1060    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1061    TheCU->addUInt(Block, 0, dwarf::DW_FORM_udata, CII->getZExtValue());
1062    TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1063    TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1064  }
1065
1066  return;
1067}
1068
1069/// construct SubprogramDIE - Construct subprogram DIE.
1070void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1071  DISubprogram SP(N);
1072
1073  // Check for pre-existence.
1074  CompileUnit *TheCU = getCompileUnit(N);
1075  if (TheCU->getDIE(N))
1076    return;
1077
1078  if (!SP.isDefinition())
1079    // This is a method declaration which will be handled while constructing
1080    // class type.
1081    return;
1082
1083  DIE *SubprogramDie = createSubprogramDIE(SP);
1084
1085  // Add to map.
1086  TheCU->insertDIE(N, SubprogramDie);
1087
1088  // Add to context owner.
1089  TheCU->addToContextOwner(SubprogramDie, SP.getContext());
1090
1091  // Expose as global.
1092  TheCU->addGlobal(SP.getName(), SubprogramDie);
1093
1094  return;
1095}
1096
1097/// beginModule - Emit all Dwarf sections that should come prior to the
1098/// content. Create global DIEs and emit initial debug info sections.
1099/// This is inovked by the target AsmPrinter.
1100void DwarfDebug::beginModule(Module *M) {
1101  if (DisableDebugInfoPrinting)
1102    return;
1103
1104  DebugInfoFinder DbgFinder;
1105  DbgFinder.processModule(*M);
1106
1107  bool HasDebugInfo = false;
1108
1109  // Scan all the compile-units to see if there are any marked as the main unit.
1110  // if not, we do not generate debug info.
1111  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1112       E = DbgFinder.compile_unit_end(); I != E; ++I) {
1113    if (DICompileUnit(*I).isMain()) {
1114      HasDebugInfo = true;
1115      break;
1116    }
1117  }
1118
1119  if (!HasDebugInfo) return;
1120
1121  // Tell MMI that we have debug info.
1122  MMI->setDebugInfoAvailability(true);
1123
1124  // Emit initial sections.
1125  EmitSectionLabels();
1126
1127  // Create all the compile unit DIEs.
1128  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1129         E = DbgFinder.compile_unit_end(); I != E; ++I)
1130    constructCompileUnit(*I);
1131
1132  // Create DIEs for each subprogram.
1133  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1134         E = DbgFinder.subprogram_end(); I != E; ++I)
1135    constructSubprogramDIE(*I);
1136
1137  // Create DIEs for each global variable.
1138  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1139         E = DbgFinder.global_variable_end(); I != E; ++I)
1140    constructGlobalVariableDIE(*I);
1141
1142  //getOrCreateTypeDIE
1143  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
1144    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1145      DIType Ty(NMD->getOperand(i));
1146      getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1147    }
1148
1149  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
1150    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1151      DIType Ty(NMD->getOperand(i));
1152      getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1153    }
1154
1155  // Prime section data.
1156  SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1157}
1158
1159/// endModule - Emit all Dwarf sections that should come after the content.
1160///
1161void DwarfDebug::endModule() {
1162  if (!FirstCU) return;
1163  const Module *M = MMI->getModule();
1164  DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
1165  if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
1166    for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
1167      if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
1168      DISubprogram SP(AllSPs->getOperand(SI));
1169      if (!SP.Verify()) continue;
1170
1171      // Collect info for variables that were optimized out.
1172      if (!SP.isDefinition()) continue;
1173      StringRef FName = SP.getLinkageName();
1174      if (FName.empty())
1175        FName = SP.getName();
1176      NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
1177      if (!NMD) continue;
1178      unsigned E = NMD->getNumOperands();
1179      if (!E) continue;
1180      DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
1181      DeadFnScopeMap[SP] = Scope;
1182      for (unsigned I = 0; I != E; ++I) {
1183        DIVariable DV(NMD->getOperand(I));
1184        if (!DV.Verify()) continue;
1185        Scope->addVariable(new DbgVariable(DV));
1186      }
1187
1188      // Construct subprogram DIE and add variables DIEs.
1189      constructSubprogramDIE(SP);
1190      DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
1191      const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1192      for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1193        DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1194        if (VariableDIE)
1195          ScopeDIE->addChild(VariableDIE);
1196      }
1197    }
1198  }
1199
1200  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1201  for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1202         AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1203    DIE *ISP = *AI;
1204    FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1205  }
1206
1207  for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1208         CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1209    DIE *SPDie = CI->first;
1210    const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1211    if (!N) continue;
1212    DIE *NDie = getCompileUnit(N)->getDIE(N);
1213    if (!NDie) continue;
1214    getCompileUnit(N)->addDIEEntry(SPDie, dwarf::DW_AT_containing_type,
1215                                   dwarf::DW_FORM_ref4, NDie);
1216  }
1217
1218  // Standard sections final addresses.
1219  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1220  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1221  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1222  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1223
1224  // End text sections.
1225  for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1226    Asm->OutStreamer.SwitchSection(SectionMap[i]);
1227    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1228  }
1229
1230  // Emit common frame information.
1231  emitCommonDebugFrame();
1232
1233  // Emit function debug frame information
1234  for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1235         E = DebugFrames.end(); I != E; ++I)
1236    emitFunctionDebugFrame(*I);
1237
1238  // Compute DIE offsets and sizes.
1239  computeSizeAndOffsets();
1240
1241  // Emit all the DIEs into a debug info section
1242  emitDebugInfo();
1243
1244  // Corresponding abbreviations into a abbrev section.
1245  emitAbbreviations();
1246
1247  // Emit info into a debug pubnames section.
1248  emitDebugPubNames();
1249
1250  // Emit info into a debug pubtypes section.
1251  emitDebugPubTypes();
1252
1253  // Emit info into a debug loc section.
1254  emitDebugLoc();
1255
1256  // Emit info into a debug aranges section.
1257  EmitDebugARanges();
1258
1259  // Emit info into a debug ranges section.
1260  emitDebugRanges();
1261
1262  // Emit info into a debug macinfo section.
1263  emitDebugMacInfo();
1264
1265  // Emit inline info.
1266  emitDebugInlineInfo();
1267
1268  // Emit info into a debug str section.
1269  emitDebugStr();
1270
1271  // clean up.
1272  DeleteContainerSeconds(DeadFnScopeMap);
1273  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1274         E = CUMap.end(); I != E; ++I)
1275    delete I->second;
1276  FirstCU = NULL;  // Reset for the next Module, if any.
1277}
1278
1279/// findAbstractVariable - Find abstract variable, if any, associated with Var.
1280DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1281                                              DebugLoc ScopeLoc) {
1282
1283  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1284  if (AbsDbgVariable)
1285    return AbsDbgVariable;
1286
1287  LLVMContext &Ctx = Var->getContext();
1288  DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
1289  if (!Scope)
1290    return NULL;
1291
1292  AbsDbgVariable = new DbgVariable(Var);
1293  Scope->addVariable(AbsDbgVariable);
1294  AbstractVariables[Var] = AbsDbgVariable;
1295  return AbsDbgVariable;
1296}
1297
1298/// addCurrentFnArgument - If Var is an current function argument that add
1299/// it in CurrentFnArguments list.
1300bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1301                                      DbgVariable *Var, DbgScope *Scope) {
1302  if (Scope != CurrentFnDbgScope)
1303    return false;
1304  DIVariable DV = Var->getVariable();
1305  if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1306    return false;
1307  unsigned ArgNo = DV.getArgNumber();
1308  if (ArgNo == 0)
1309    return false;
1310
1311  size_t Size = CurrentFnArguments.size();
1312  if (Size == 0)
1313    CurrentFnArguments.resize(MF->getFunction()->arg_size());
1314  // llvm::Function argument size is not good indicator of how many
1315  // arguments does the function have at source level.
1316  if (ArgNo > Size)
1317    CurrentFnArguments.resize(ArgNo * 2);
1318  CurrentFnArguments[ArgNo - 1] = Var;
1319  return true;
1320}
1321
1322/// collectVariableInfoFromMMITable - Collect variable information from
1323/// side table maintained by MMI.
1324void
1325DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
1326                                   SmallPtrSet<const MDNode *, 16> &Processed) {
1327  const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
1328  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1329  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1330         VE = VMap.end(); VI != VE; ++VI) {
1331    const MDNode *Var = VI->first;
1332    if (!Var) continue;
1333    Processed.insert(Var);
1334    DIVariable DV(Var);
1335    const std::pair<unsigned, DebugLoc> &VP = VI->second;
1336
1337    DbgScope *Scope = 0;
1338    if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
1339      Scope = ConcreteScopes.lookup(IA);
1340    if (Scope == 0)
1341      Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
1342
1343    // If variable scope is not found then skip this variable.
1344    if (Scope == 0)
1345      continue;
1346
1347    DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1348    DbgVariable *RegVar = new DbgVariable(DV);
1349    recordVariableFrameIndex(RegVar, VP.first);
1350    if (!addCurrentFnArgument(MF, RegVar, Scope))
1351      Scope->addVariable(RegVar);
1352    if (AbsDbgVariable) {
1353      recordVariableFrameIndex(AbsDbgVariable, VP.first);
1354      VarToAbstractVarMap[RegVar] = AbsDbgVariable;
1355    }
1356  }
1357}
1358
1359/// isDbgValueInDefinedReg - Return true if debug value, encoded by
1360/// DBG_VALUE instruction, is in a defined reg.
1361static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1362  assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1363  return MI->getNumOperands() == 3 &&
1364         MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1365         MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1366}
1367
1368/// collectVariableInfo - Populate DbgScope entries with variables' info.
1369void
1370DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1371                                SmallPtrSet<const MDNode *, 16> &Processed) {
1372
1373  /// collection info from MMI table.
1374  collectVariableInfoFromMMITable(MF, Processed);
1375
1376  for (SmallVectorImpl<const MDNode*>::const_iterator
1377         UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1378         ++UVI) {
1379    const MDNode *Var = *UVI;
1380    if (Processed.count(Var))
1381      continue;
1382
1383    // History contains relevant DBG_VALUE instructions for Var and instructions
1384    // clobbering it.
1385    SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1386    if (History.empty())
1387      continue;
1388    const MachineInstr *MInsn = History.front();
1389
1390    DIVariable DV(Var);
1391    DbgScope *Scope = NULL;
1392    if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1393        DISubprogram(DV.getContext()).describes(MF->getFunction()))
1394      Scope = CurrentFnDbgScope;
1395    else
1396      Scope = findDbgScope(MInsn);
1397    // If variable scope is not found then skip this variable.
1398    if (!Scope)
1399      continue;
1400
1401    Processed.insert(DV);
1402    assert(MInsn->isDebugValue() && "History must begin with debug value");
1403    DbgVariable *RegVar = new DbgVariable(DV);
1404    if (!addCurrentFnArgument(MF, RegVar, Scope))
1405      Scope->addVariable(RegVar);
1406    if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
1407      DbgVariableToDbgInstMap[AbsVar] = MInsn;
1408      VarToAbstractVarMap[RegVar] = AbsVar;
1409    }
1410
1411    // Simple ranges that are fully coalesced.
1412    if (History.size() <= 1 || (History.size() == 2 &&
1413                                MInsn->isIdenticalTo(History.back()))) {
1414      DbgVariableToDbgInstMap[RegVar] = MInsn;
1415      continue;
1416    }
1417
1418    // handle multiple DBG_VALUE instructions describing one variable.
1419    RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1420
1421    for (SmallVectorImpl<const MachineInstr*>::const_iterator
1422           HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1423      const MachineInstr *Begin = *HI;
1424      assert(Begin->isDebugValue() && "Invalid History entry");
1425      MachineLocation MLoc;
1426      if (Begin->getNumOperands() == 3) {
1427        if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
1428          MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
1429      } else
1430        MLoc = Asm->getDebugValueLocation(Begin);
1431
1432      // FIXME: emitDebugLoc only understands registers.
1433      if (!MLoc.getReg())
1434        continue;
1435
1436      // Compute the range for a register location.
1437      const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1438      const MCSymbol *SLabel = 0;
1439
1440      if (HI + 1 == HE)
1441        // If Begin is the last instruction in History then its value is valid
1442        // until the end of the function.
1443        SLabel = FunctionEndSym;
1444      else {
1445        const MachineInstr *End = HI[1];
1446        if (End->isDebugValue())
1447          SLabel = getLabelBeforeInsn(End);
1448        else {
1449          // End is a normal instruction clobbering the range.
1450          SLabel = getLabelAfterInsn(End);
1451          assert(SLabel && "Forgot label after clobber instruction");
1452          ++HI;
1453        }
1454      }
1455
1456      // The value is valid until the next DBG_VALUE or clobber.
1457      DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc));
1458    }
1459    DotDebugLocEntries.push_back(DotDebugLocEntry());
1460  }
1461
1462  // Collect info for variables that were optimized out.
1463  const Function *F = MF->getFunction();
1464  if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1465    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1466      DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1467      if (!DV || !Processed.insert(DV))
1468        continue;
1469      DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
1470      if (Scope)
1471        Scope->addVariable(new DbgVariable(DV));
1472    }
1473  }
1474}
1475
1476/// getLabelBeforeInsn - Return Label preceding the instruction.
1477const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1478  MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1479  assert(Label && "Didn't insert label before instruction");
1480  return Label;
1481}
1482
1483/// getLabelAfterInsn - Return Label immediately following the instruction.
1484const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1485  return LabelsAfterInsn.lookup(MI);
1486}
1487
1488/// beginInstruction - Process beginning of an instruction.
1489void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1490  // Check if source location changes, but ignore DBG_VALUE locations.
1491  if (!MI->isDebugValue()) {
1492    DebugLoc DL = MI->getDebugLoc();
1493    if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1494      PrevInstLoc = DL;
1495      if (!DL.isUnknown()) {
1496        const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1497        recordSourceLine(DL.getLine(), DL.getCol(), Scope);
1498      } else
1499        recordSourceLine(0, 0, 0);
1500    }
1501  }
1502
1503  // Insert labels where requested.
1504  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1505    LabelsBeforeInsn.find(MI);
1506
1507  // No label needed.
1508  if (I == LabelsBeforeInsn.end())
1509    return;
1510
1511  // Label already assigned.
1512  if (I->second)
1513    return;
1514
1515  if (!PrevLabel) {
1516    PrevLabel = MMI->getContext().CreateTempSymbol();
1517    Asm->OutStreamer.EmitLabel(PrevLabel);
1518  }
1519  I->second = PrevLabel;
1520}
1521
1522/// endInstruction - Process end of an instruction.
1523void DwarfDebug::endInstruction(const MachineInstr *MI) {
1524  // Don't create a new label after DBG_VALUE instructions.
1525  // They don't generate code.
1526  if (!MI->isDebugValue())
1527    PrevLabel = 0;
1528
1529  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1530    LabelsAfterInsn.find(MI);
1531
1532  // No label needed.
1533  if (I == LabelsAfterInsn.end())
1534    return;
1535
1536  // Label already assigned.
1537  if (I->second)
1538    return;
1539
1540  // We need a label after this instruction.
1541  if (!PrevLabel) {
1542    PrevLabel = MMI->getContext().CreateTempSymbol();
1543    Asm->OutStreamer.EmitLabel(PrevLabel);
1544  }
1545  I->second = PrevLabel;
1546}
1547
1548/// getOrCreateDbgScope - Create DbgScope for the scope.
1549DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
1550                                          const MDNode *InlinedAt) {
1551  if (!InlinedAt) {
1552    DbgScope *WScope = DbgScopeMap.lookup(Scope);
1553    if (WScope)
1554      return WScope;
1555    WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1556    DbgScopeMap.insert(std::make_pair(Scope, WScope));
1557    if (DIDescriptor(Scope).isLexicalBlock()) {
1558      DbgScope *Parent =
1559        getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
1560      WScope->setParent(Parent);
1561      Parent->addScope(WScope);
1562    }
1563
1564    if (!WScope->getParent()) {
1565      StringRef SPName = DISubprogram(Scope).getLinkageName();
1566      // We used to check only for a linkage name, but that fails
1567      // since we began omitting the linkage name for private
1568      // functions.  The new way is to check for the name in metadata,
1569      // but that's not supported in old .ll test cases.  Ergo, we
1570      // check both.
1571      if (SPName == Asm->MF->getFunction()->getName() ||
1572          DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
1573        CurrentFnDbgScope = WScope;
1574    }
1575
1576    return WScope;
1577  }
1578
1579  getOrCreateAbstractScope(Scope);
1580  DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1581  if (WScope)
1582    return WScope;
1583
1584  WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
1585  DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
1586  DILocation DL(InlinedAt);
1587  DbgScope *Parent =
1588    getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
1589  WScope->setParent(Parent);
1590  Parent->addScope(WScope);
1591
1592  ConcreteScopes[InlinedAt] = WScope;
1593
1594  return WScope;
1595}
1596
1597/// hasValidLocation - Return true if debug location entry attached with
1598/// machine instruction encodes valid location info.
1599static bool hasValidLocation(LLVMContext &Ctx,
1600                             const MachineInstr *MInsn,
1601                             const MDNode *&Scope, const MDNode *&InlinedAt) {
1602  DebugLoc DL = MInsn->getDebugLoc();
1603  if (DL.isUnknown()) return false;
1604
1605  const MDNode *S = DL.getScope(Ctx);
1606
1607  // There is no need to create another DIE for compile unit. For all
1608  // other scopes, create one DbgScope now. This will be translated
1609  // into a scope DIE at the end.
1610  if (DIScope(S).isCompileUnit()) return false;
1611
1612  Scope = S;
1613  InlinedAt = DL.getInlinedAt(Ctx);
1614  return true;
1615}
1616
1617/// calculateDominanceGraph - Calculate dominance graph for DbgScope
1618/// hierarchy.
1619static void calculateDominanceGraph(DbgScope *Scope) {
1620  assert (Scope && "Unable to calculate scop edominance graph!");
1621  SmallVector<DbgScope *, 4> WorkStack;
1622  WorkStack.push_back(Scope);
1623  unsigned Counter = 0;
1624  while (!WorkStack.empty()) {
1625    DbgScope *WS = WorkStack.back();
1626    const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
1627    bool visitedChildren = false;
1628    for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1629           SE = Children.end(); SI != SE; ++SI) {
1630      DbgScope *ChildScope = *SI;
1631      if (!ChildScope->getDFSOut()) {
1632        WorkStack.push_back(ChildScope);
1633        visitedChildren = true;
1634        ChildScope->setDFSIn(++Counter);
1635        break;
1636      }
1637    }
1638    if (!visitedChildren) {
1639      WorkStack.pop_back();
1640      WS->setDFSOut(++Counter);
1641    }
1642  }
1643}
1644
1645/// printDbgScopeInfo - Print DbgScope info for each machine instruction.
1646static
1647void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
1648                       DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
1649{
1650#ifndef NDEBUG
1651  unsigned PrevDFSIn = 0;
1652  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1653       I != E; ++I) {
1654    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1655         II != IE; ++II) {
1656      const MachineInstr *MInsn = II;
1657      const MDNode *Scope = NULL;
1658      const MDNode *InlinedAt = NULL;
1659
1660      // Check if instruction has valid location information.
1661      if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
1662        dbgs() << " [ ";
1663        if (InlinedAt)
1664          dbgs() << "*";
1665        DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
1666          MI2ScopeMap.find(MInsn);
1667        if (DI != MI2ScopeMap.end()) {
1668          DbgScope *S = DI->second;
1669          dbgs() << S->getDFSIn();
1670          PrevDFSIn = S->getDFSIn();
1671        } else
1672          dbgs() << PrevDFSIn;
1673      } else
1674        dbgs() << " [ x" << PrevDFSIn;
1675      dbgs() << " ]";
1676      MInsn->dump();
1677    }
1678    dbgs() << "\n";
1679  }
1680#endif
1681}
1682/// extractScopeInformation - Scan machine instructions in this function
1683/// and collect DbgScopes. Return true, if at least one scope was found.
1684bool DwarfDebug::extractScopeInformation() {
1685  // If scope information was extracted using .dbg intrinsics then there is not
1686  // any need to extract these information by scanning each instruction.
1687  if (!DbgScopeMap.empty())
1688    return false;
1689
1690  // Scan each instruction and create scopes. First build working set of scopes.
1691  LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
1692  SmallVector<DbgRange, 4> MIRanges;
1693  DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
1694  const MDNode *PrevScope = NULL;
1695  const MDNode *PrevInlinedAt = NULL;
1696  const MachineInstr *RangeBeginMI = NULL;
1697  const MachineInstr *PrevMI = NULL;
1698  for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
1699       I != E; ++I) {
1700    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1701         II != IE; ++II) {
1702      const MachineInstr *MInsn = II;
1703      const MDNode *Scope = NULL;
1704      const MDNode *InlinedAt = NULL;
1705
1706      // Check if instruction has valid location information.
1707      if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
1708        PrevMI = MInsn;
1709        continue;
1710      }
1711
1712      // If scope has not changed then skip this instruction.
1713      if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
1714        PrevMI = MInsn;
1715        continue;
1716      }
1717
1718      // Ignore DBG_VALUE. It does not contribute any instruction in output.
1719      if (MInsn->isDebugValue())
1720        continue;
1721
1722      if (RangeBeginMI) {
1723        // If we have alread seen a beginning of a instruction range and
1724        // current instruction scope does not match scope of first instruction
1725        // in this range then create a new instruction range.
1726        DbgRange R(RangeBeginMI, PrevMI);
1727        MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
1728                                                        PrevInlinedAt);
1729        MIRanges.push_back(R);
1730      }
1731
1732      // This is a beginning of a new instruction range.
1733      RangeBeginMI = MInsn;
1734
1735      // Reset previous markers.
1736      PrevMI = MInsn;
1737      PrevScope = Scope;
1738      PrevInlinedAt = InlinedAt;
1739    }
1740  }
1741
1742  // Create last instruction range.
1743  if (RangeBeginMI && PrevMI && PrevScope) {
1744    DbgRange R(RangeBeginMI, PrevMI);
1745    MIRanges.push_back(R);
1746    MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
1747  }
1748
1749  if (!CurrentFnDbgScope)
1750    return false;
1751
1752  calculateDominanceGraph(CurrentFnDbgScope);
1753  if (PrintDbgScope)
1754    printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
1755
1756  // Find ranges of instructions covered by each DbgScope;
1757  DbgScope *PrevDbgScope = NULL;
1758  for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
1759         RE = MIRanges.end(); RI != RE; ++RI) {
1760    const DbgRange &R = *RI;
1761    DbgScope *S = MI2ScopeMap.lookup(R.first);
1762    assert (S && "Lost DbgScope for a machine instruction!");
1763    if (PrevDbgScope && !PrevDbgScope->dominates(S))
1764      PrevDbgScope->closeInsnRange(S);
1765    S->openInsnRange(R.first);
1766    S->extendInsnRange(R.second);
1767    PrevDbgScope = S;
1768  }
1769
1770  if (PrevDbgScope)
1771    PrevDbgScope->closeInsnRange();
1772
1773  identifyScopeMarkers();
1774
1775  return !DbgScopeMap.empty();
1776}
1777
1778/// identifyScopeMarkers() -
1779/// Each DbgScope has first instruction and last instruction to mark beginning
1780/// and end of a scope respectively. Create an inverse map that list scopes
1781/// starts (and ends) with an instruction. One instruction may start (or end)
1782/// multiple scopes. Ignore scopes that are not reachable.
1783void DwarfDebug::identifyScopeMarkers() {
1784  SmallVector<DbgScope *, 4> WorkList;
1785  WorkList.push_back(CurrentFnDbgScope);
1786  while (!WorkList.empty()) {
1787    DbgScope *S = WorkList.pop_back_val();
1788
1789    const SmallVector<DbgScope *, 4> &Children = S->getScopes();
1790    if (!Children.empty())
1791      for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1792             SE = Children.end(); SI != SE; ++SI)
1793        WorkList.push_back(*SI);
1794
1795    if (S->isAbstractScope())
1796      continue;
1797
1798    const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
1799    if (Ranges.empty())
1800      continue;
1801    for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1802           RE = Ranges.end(); RI != RE; ++RI) {
1803      assert(RI->first && "DbgRange does not have first instruction!");
1804      assert(RI->second && "DbgRange does not have second instruction!");
1805      requestLabelBeforeInsn(RI->first);
1806      requestLabelAfterInsn(RI->second);
1807    }
1808  }
1809}
1810
1811/// FindFirstDebugLoc - Find the first debug location in the function. This
1812/// is intended to be an approximation for the source position of the
1813/// beginning of the function.
1814static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
1815  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1816       I != E; ++I)
1817    for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
1818         MBBI != MBBE; ++MBBI) {
1819      DebugLoc DL = MBBI->getDebugLoc();
1820      if (!DL.isUnknown())
1821        return DL;
1822    }
1823  return DebugLoc();
1824}
1825
1826#ifndef NDEBUG
1827/// CheckLineNumbers - Count basicblocks whose instructions do not have any
1828/// line number information.
1829static void CheckLineNumbers(const MachineFunction *MF) {
1830  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1831       I != E; ++I) {
1832    bool FoundLineNo = false;
1833    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1834         II != IE; ++II) {
1835      const MachineInstr *MI = II;
1836      if (!MI->getDebugLoc().isUnknown()) {
1837        FoundLineNo = true;
1838        break;
1839      }
1840    }
1841    if (!FoundLineNo && I->size())
1842      ++BlocksWithoutLineNo;
1843  }
1844}
1845#endif
1846
1847/// beginFunction - Gather pre-function debug information.  Assumes being
1848/// emitted immediately after the function entry point.
1849void DwarfDebug::beginFunction(const MachineFunction *MF) {
1850  if (!MMI->hasDebugInfo()) return;
1851  if (!extractScopeInformation()) return;
1852
1853#ifndef NDEBUG
1854  CheckLineNumbers(MF);
1855#endif
1856
1857  FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1858                                        Asm->getFunctionNumber());
1859  // Assumes in correct section after the entry point.
1860  Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1861
1862  // Emit label for the implicitly defined dbg.stoppoint at the start of the
1863  // function.
1864  DebugLoc FDL = FindFirstDebugLoc(MF);
1865  if (FDL.isUnknown()) return;
1866
1867  const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
1868  const MDNode *TheScope = 0;
1869
1870  DISubprogram SP = getDISubprogram(Scope);
1871  unsigned Line, Col;
1872  if (SP.Verify()) {
1873    Line = SP.getLineNumber();
1874    Col = 0;
1875    TheScope = SP;
1876  } else {
1877    Line = FDL.getLine();
1878    Col = FDL.getCol();
1879    TheScope = Scope;
1880  }
1881
1882  recordSourceLine(Line, Col, TheScope);
1883
1884  assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1885
1886  /// ProcessedArgs - Collection of arguments already processed.
1887  SmallPtrSet<const MDNode *, 8> ProcessedArgs;
1888
1889  const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1890
1891  /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1892  std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1893
1894  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1895       I != E; ++I) {
1896    bool AtBlockEntry = true;
1897    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1898         II != IE; ++II) {
1899      const MachineInstr *MI = II;
1900
1901      if (MI->isDebugValue()) {
1902        assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1903
1904        // Keep track of user variables.
1905        const MDNode *Var =
1906          MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1907
1908        // Variable is in a register, we need to check for clobbers.
1909        if (isDbgValueInDefinedReg(MI))
1910          LiveUserVar[MI->getOperand(0).getReg()] = Var;
1911
1912        // Check the history of this variable.
1913        SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1914        if (History.empty()) {
1915          UserVariables.push_back(Var);
1916          // The first mention of a function argument gets the FunctionBeginSym
1917          // label, so arguments are visible when breaking at function entry.
1918          DIVariable DV(Var);
1919          if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1920              DISubprogram(getDISubprogram(DV.getContext()))
1921                .describes(MF->getFunction()))
1922            LabelsBeforeInsn[MI] = FunctionBeginSym;
1923        } else {
1924          // We have seen this variable before. Try to coalesce DBG_VALUEs.
1925          const MachineInstr *Prev = History.back();
1926          if (Prev->isDebugValue()) {
1927            // Coalesce identical entries at the end of History.
1928            if (History.size() >= 2 &&
1929                Prev->isIdenticalTo(History[History.size() - 2]))
1930              History.pop_back();
1931
1932            // Terminate old register assignments that don't reach MI;
1933            MachineFunction::const_iterator PrevMBB = Prev->getParent();
1934            if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1935                isDbgValueInDefinedReg(Prev)) {
1936              // Previous register assignment needs to terminate at the end of
1937              // its basic block.
1938              MachineBasicBlock::const_iterator LastMI =
1939                PrevMBB->getLastNonDebugInstr();
1940              if (LastMI == PrevMBB->end())
1941                // Drop DBG_VALUE for empty range.
1942                History.pop_back();
1943              else {
1944                // Terminate after LastMI.
1945                History.push_back(LastMI);
1946              }
1947            }
1948          }
1949        }
1950        History.push_back(MI);
1951      } else {
1952        // Not a DBG_VALUE instruction.
1953        if (!MI->isLabel())
1954          AtBlockEntry = false;
1955
1956        // Check if the instruction clobbers any registers with debug vars.
1957        for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1958               MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1959          if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1960            continue;
1961          for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1962               unsigned Reg = *AI; ++AI) {
1963            const MDNode *Var = LiveUserVar[Reg];
1964            if (!Var)
1965              continue;
1966            // Reg is now clobbered.
1967            LiveUserVar[Reg] = 0;
1968
1969            // Was MD last defined by a DBG_VALUE referring to Reg?
1970            DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1971            if (HistI == DbgValues.end())
1972              continue;
1973            SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1974            if (History.empty())
1975              continue;
1976            const MachineInstr *Prev = History.back();
1977            // Sanity-check: Register assignments are terminated at the end of
1978            // their block.
1979            if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1980              continue;
1981            // Is the variable still in Reg?
1982            if (!isDbgValueInDefinedReg(Prev) ||
1983                Prev->getOperand(0).getReg() != Reg)
1984              continue;
1985            // Var is clobbered. Make sure the next instruction gets a label.
1986            History.push_back(MI);
1987          }
1988        }
1989      }
1990    }
1991  }
1992
1993  for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1994       I != E; ++I) {
1995    SmallVectorImpl<const MachineInstr*> &History = I->second;
1996    if (History.empty())
1997      continue;
1998
1999    // Make sure the final register assignments are terminated.
2000    const MachineInstr *Prev = History.back();
2001    if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
2002      const MachineBasicBlock *PrevMBB = Prev->getParent();
2003      MachineBasicBlock::const_iterator LastMI = PrevMBB->getLastNonDebugInstr();
2004      if (LastMI == PrevMBB->end())
2005        // Drop DBG_VALUE for empty range.
2006        History.pop_back();
2007      else {
2008        // Terminate after LastMI.
2009        History.push_back(LastMI);
2010      }
2011    }
2012    // Request labels for the full history.
2013    for (unsigned i = 0, e = History.size(); i != e; ++i) {
2014      const MachineInstr *MI = History[i];
2015      if (MI->isDebugValue())
2016        requestLabelBeforeInsn(MI);
2017      else
2018        requestLabelAfterInsn(MI);
2019    }
2020  }
2021
2022  PrevInstLoc = DebugLoc();
2023  PrevLabel = FunctionBeginSym;
2024}
2025
2026/// endFunction - Gather and emit post-function debug information.
2027///
2028void DwarfDebug::endFunction(const MachineFunction *MF) {
2029  if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2030
2031  if (CurrentFnDbgScope) {
2032
2033    // Define end label for subprogram.
2034    FunctionEndSym = Asm->GetTempSymbol("func_end",
2035                                        Asm->getFunctionNumber());
2036    // Assumes in correct section after the entry point.
2037    Asm->OutStreamer.EmitLabel(FunctionEndSym);
2038
2039    SmallPtrSet<const MDNode *, 16> ProcessedVars;
2040    collectVariableInfo(MF, ProcessedVars);
2041
2042    // Construct abstract scopes.
2043    for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2044           AE = AbstractScopesList.end(); AI != AE; ++AI) {
2045      DISubprogram SP((*AI)->getScopeNode());
2046      if (SP.Verify()) {
2047        // Collect info for variables that were optimized out.
2048        StringRef FName = SP.getLinkageName();
2049        if (FName.empty())
2050          FName = SP.getName();
2051        if (NamedMDNode *NMD =
2052            getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
2053          for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2054          DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2055          if (!DV || !ProcessedVars.insert(DV))
2056            continue;
2057          DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2058          if (Scope)
2059            Scope->addVariable(new DbgVariable(DV));
2060          }
2061        }
2062      }
2063      if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2064        constructScopeDIE(*AI);
2065    }
2066
2067    DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2068
2069    if (!DisableFramePointerElim(*MF))
2070      getCompileUnit(CurrentFnDbgScope->getScopeNode())->addUInt(CurFnDIE,
2071                                                                 dwarf::DW_AT_APPLE_omit_frame_ptr,
2072                                                                 dwarf::DW_FORM_flag, 1);
2073
2074
2075    DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2076                                                 MMI->getFrameMoves()));
2077  }
2078
2079  // Clear debug info
2080  CurrentFnDbgScope = NULL;
2081  DeleteContainerPointers(CurrentFnArguments);
2082  DbgVariableToFrameIndexMap.clear();
2083  VarToAbstractVarMap.clear();
2084  DbgVariableToDbgInstMap.clear();
2085  DeleteContainerSeconds(DbgScopeMap);
2086  UserVariables.clear();
2087  DbgValues.clear();
2088  ConcreteScopes.clear();
2089  DeleteContainerSeconds(AbstractScopes);
2090  AbstractScopesList.clear();
2091  AbstractVariables.clear();
2092  LabelsBeforeInsn.clear();
2093  LabelsAfterInsn.clear();
2094  PrevLabel = NULL;
2095}
2096
2097/// recordVariableFrameIndex - Record a variable's index.
2098void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2099  assert (V && "Invalid DbgVariable!");
2100  DbgVariableToFrameIndexMap[V] = Index;
2101}
2102
2103/// findVariableFrameIndex - Return true if frame index for the variable
2104/// is found. Update FI to hold value of the index.
2105bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2106  assert (V && "Invalid DbgVariable!");
2107  DenseMap<const DbgVariable *, int>::iterator I =
2108    DbgVariableToFrameIndexMap.find(V);
2109  if (I == DbgVariableToFrameIndexMap.end())
2110    return false;
2111  *FI = I->second;
2112  return true;
2113}
2114
2115/// findDbgScope - Find DbgScope for the debug loc attached with an
2116/// instruction.
2117DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
2118  DbgScope *Scope = NULL;
2119  LLVMContext &Ctx =
2120    MInsn->getParent()->getParent()->getFunction()->getContext();
2121  DebugLoc DL = MInsn->getDebugLoc();
2122
2123  if (DL.isUnknown())
2124    return Scope;
2125
2126  if (const MDNode *IA = DL.getInlinedAt(Ctx))
2127    Scope = ConcreteScopes.lookup(IA);
2128  if (Scope == 0)
2129    Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2130
2131  return Scope;
2132}
2133
2134
2135/// recordSourceLine - Register a source line with debug info. Returns the
2136/// unique label that was emitted and which provides correspondence to
2137/// the source line list.
2138void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S){
2139  StringRef Fn;
2140  StringRef Dir;
2141  unsigned Src = 1;
2142  if (S) {
2143    DIDescriptor Scope(S);
2144
2145    if (Scope.isCompileUnit()) {
2146      DICompileUnit CU(S);
2147      Fn = CU.getFilename();
2148      Dir = CU.getDirectory();
2149    } else if (Scope.isFile()) {
2150      DIFile F(S);
2151      Fn = F.getFilename();
2152      Dir = F.getDirectory();
2153    } else if (Scope.isSubprogram()) {
2154      DISubprogram SP(S);
2155      Fn = SP.getFilename();
2156      Dir = SP.getDirectory();
2157    } else if (Scope.isLexicalBlock()) {
2158      DILexicalBlock DB(S);
2159      Fn = DB.getFilename();
2160      Dir = DB.getDirectory();
2161    } else
2162      assert(0 && "Unexpected scope info");
2163
2164    Src = GetOrCreateSourceID(Fn, Dir);
2165  }
2166  Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, DWARF2_FLAG_IS_STMT,
2167                                         0, 0, Fn);
2168}
2169
2170//===----------------------------------------------------------------------===//
2171// Emit Methods
2172//===----------------------------------------------------------------------===//
2173
2174/// computeSizeAndOffset - Compute the size and offset of a DIE.
2175///
2176unsigned
2177DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2178  // Get the children.
2179  const std::vector<DIE *> &Children = Die->getChildren();
2180
2181  // If not last sibling and has children then add sibling offset attribute.
2182  if (!Last && !Children.empty())
2183    Die->addSiblingOffset(DIEValueAllocator);
2184
2185  // Record the abbreviation.
2186  assignAbbrevNumber(Die->getAbbrev());
2187
2188  // Get the abbreviation for this DIE.
2189  unsigned AbbrevNumber = Die->getAbbrevNumber();
2190  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2191
2192  // Set DIE offset
2193  Die->setOffset(Offset);
2194
2195  // Start the size with the size of abbreviation code.
2196  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2197
2198  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2199  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2200
2201  // Size the DIE attribute values.
2202  for (unsigned i = 0, N = Values.size(); i < N; ++i)
2203    // Size attribute value.
2204    Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2205
2206  // Size the DIE children if any.
2207  if (!Children.empty()) {
2208    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2209           "Children flag not set");
2210
2211    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2212      Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2213
2214    // End of children marker.
2215    Offset += sizeof(int8_t);
2216  }
2217
2218  Die->setSize(Offset - Die->getOffset());
2219  return Offset;
2220}
2221
2222/// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2223///
2224void DwarfDebug::computeSizeAndOffsets() {
2225  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2226         E = CUMap.end(); I != E; ++I) {
2227    // Compute size of compile unit header.
2228    unsigned Offset =
2229      sizeof(int32_t) + // Length of Compilation Unit Info
2230      sizeof(int16_t) + // DWARF version number
2231      sizeof(int32_t) + // Offset Into Abbrev. Section
2232      sizeof(int8_t);   // Pointer Size (in bytes)
2233    computeSizeAndOffset(I->second->getCUDie(), Offset, true);
2234  }
2235}
2236
2237/// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2238/// temporary label to it if SymbolStem is specified.
2239static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2240                                const char *SymbolStem = 0) {
2241  Asm->OutStreamer.SwitchSection(Section);
2242  if (!SymbolStem) return 0;
2243
2244  MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2245  Asm->OutStreamer.EmitLabel(TmpSym);
2246  return TmpSym;
2247}
2248
2249/// EmitSectionLabels - Emit initial Dwarf sections with a label at
2250/// the start of each one.
2251void DwarfDebug::EmitSectionLabels() {
2252  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2253
2254  // Dwarf sections base addresses.
2255  if (Asm->MAI->doesDwarfRequireFrameSection()) {
2256    DwarfFrameSectionSym =
2257      EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2258   }
2259
2260  DwarfInfoSectionSym =
2261    EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2262  DwarfAbbrevSectionSym =
2263    EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2264  EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2265
2266  if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2267    EmitSectionSym(Asm, MacroInfo);
2268
2269  EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2270  EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2271  EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2272  EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2273  DwarfStrSectionSym =
2274    EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2275  DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2276                                             "debug_range");
2277
2278  DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
2279                                           "section_debug_loc");
2280
2281  TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2282  EmitSectionSym(Asm, TLOF.getDataSection());
2283}
2284
2285/// emitDIE - Recusively Emits a debug information entry.
2286///
2287void DwarfDebug::emitDIE(DIE *Die) {
2288  // Get the abbreviation for this DIE.
2289  unsigned AbbrevNumber = Die->getAbbrevNumber();
2290  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2291
2292  // Emit the code (index) for the abbreviation.
2293  if (Asm->isVerbose())
2294    Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2295                                Twine::utohexstr(Die->getOffset()) + ":0x" +
2296                                Twine::utohexstr(Die->getSize()) + " " +
2297                                dwarf::TagString(Abbrev->getTag()));
2298  Asm->EmitULEB128(AbbrevNumber);
2299
2300  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2301  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2302
2303  // Emit the DIE attribute values.
2304  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2305    unsigned Attr = AbbrevData[i].getAttribute();
2306    unsigned Form = AbbrevData[i].getForm();
2307    assert(Form && "Too many attributes for DIE (check abbreviation)");
2308
2309    if (Asm->isVerbose())
2310      Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2311
2312    switch (Attr) {
2313    case dwarf::DW_AT_sibling:
2314      Asm->EmitInt32(Die->getSiblingOffset());
2315      break;
2316    case dwarf::DW_AT_abstract_origin: {
2317      DIEEntry *E = cast<DIEEntry>(Values[i]);
2318      DIE *Origin = E->getEntry();
2319      unsigned Addr = Origin->getOffset();
2320      Asm->EmitInt32(Addr);
2321      break;
2322    }
2323    case dwarf::DW_AT_ranges: {
2324      // DW_AT_range Value encodes offset in debug_range section.
2325      DIEInteger *V = cast<DIEInteger>(Values[i]);
2326
2327      if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
2328        Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2329                                 V->getValue(),
2330                                 4);
2331      } else {
2332        Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2333                                       V->getValue(),
2334                                       DwarfDebugRangeSectionSym,
2335                                       4);
2336      }
2337      break;
2338    }
2339    case dwarf::DW_AT_location: {
2340      if (UseDotDebugLocEntry.count(Die) != 0) {
2341        DIELabel *L = cast<DIELabel>(Values[i]);
2342        Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2343      } else
2344        Values[i]->EmitValue(Asm, Form);
2345      break;
2346    }
2347    case dwarf::DW_AT_accessibility: {
2348      if (Asm->isVerbose()) {
2349        DIEInteger *V = cast<DIEInteger>(Values[i]);
2350        Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2351      }
2352      Values[i]->EmitValue(Asm, Form);
2353      break;
2354    }
2355    default:
2356      // Emit an attribute using the defined form.
2357      Values[i]->EmitValue(Asm, Form);
2358      break;
2359    }
2360  }
2361
2362  // Emit the DIE children if any.
2363  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2364    const std::vector<DIE *> &Children = Die->getChildren();
2365
2366    for (unsigned j = 0, M = Children.size(); j < M; ++j)
2367      emitDIE(Children[j]);
2368
2369    if (Asm->isVerbose())
2370      Asm->OutStreamer.AddComment("End Of Children Mark");
2371    Asm->EmitInt8(0);
2372  }
2373}
2374
2375/// emitDebugInfo - Emit the debug info section.
2376///
2377void DwarfDebug::emitDebugInfo() {
2378  // Start debug info section.
2379  Asm->OutStreamer.SwitchSection(
2380                            Asm->getObjFileLowering().getDwarfInfoSection());
2381  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2382         E = CUMap.end(); I != E; ++I) {
2383    CompileUnit *TheCU = I->second;
2384    DIE *Die = TheCU->getCUDie();
2385
2386    // Emit the compile units header.
2387    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2388                                                  TheCU->getID()));
2389
2390    // Emit size of content not including length itself
2391    unsigned ContentSize = Die->getSize() +
2392      sizeof(int16_t) + // DWARF version number
2393      sizeof(int32_t) + // Offset Into Abbrev. Section
2394      sizeof(int8_t);   // Pointer Size (in bytes)
2395
2396    Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2397    Asm->EmitInt32(ContentSize);
2398    Asm->OutStreamer.AddComment("DWARF version number");
2399    Asm->EmitInt16(dwarf::DWARF_VERSION);
2400    Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2401    Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2402                           DwarfAbbrevSectionSym);
2403    Asm->OutStreamer.AddComment("Address Size (in bytes)");
2404    Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2405
2406    emitDIE(Die);
2407    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
2408  }
2409}
2410
2411/// emitAbbreviations - Emit the abbreviation section.
2412///
2413void DwarfDebug::emitAbbreviations() const {
2414  // Check to see if it is worth the effort.
2415  if (!Abbreviations.empty()) {
2416    // Start the debug abbrev section.
2417    Asm->OutStreamer.SwitchSection(
2418                            Asm->getObjFileLowering().getDwarfAbbrevSection());
2419
2420    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2421
2422    // For each abbrevation.
2423    for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2424      // Get abbreviation data
2425      const DIEAbbrev *Abbrev = Abbreviations[i];
2426
2427      // Emit the abbrevations code (base 1 index.)
2428      Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2429
2430      // Emit the abbreviations data.
2431      Abbrev->Emit(Asm);
2432    }
2433
2434    // Mark end of abbreviations.
2435    Asm->EmitULEB128(0, "EOM(3)");
2436
2437    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2438  }
2439}
2440
2441/// emitEndOfLineMatrix - Emit the last address of the section and the end of
2442/// the line matrix.
2443///
2444void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2445  // Define last address of section.
2446  Asm->OutStreamer.AddComment("Extended Op");
2447  Asm->EmitInt8(0);
2448
2449  Asm->OutStreamer.AddComment("Op size");
2450  Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2451  Asm->OutStreamer.AddComment("DW_LNE_set_address");
2452  Asm->EmitInt8(dwarf::DW_LNE_set_address);
2453
2454  Asm->OutStreamer.AddComment("Section end label");
2455
2456  Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2457                                   Asm->getTargetData().getPointerSize(),
2458                                   0/*AddrSpace*/);
2459
2460  // Mark end of matrix.
2461  Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2462  Asm->EmitInt8(0);
2463  Asm->EmitInt8(1);
2464  Asm->EmitInt8(1);
2465}
2466
2467/// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2468///
2469void DwarfDebug::emitCommonDebugFrame() {
2470  if (!Asm->MAI->doesDwarfRequireFrameSection())
2471    return;
2472
2473  int stackGrowth = Asm->getTargetData().getPointerSize();
2474  if (Asm->TM.getFrameLowering()->getStackGrowthDirection() ==
2475      TargetFrameLowering::StackGrowsDown)
2476    stackGrowth *= -1;
2477
2478  // Start the dwarf frame section.
2479  Asm->OutStreamer.SwitchSection(
2480                              Asm->getObjFileLowering().getDwarfFrameSection());
2481
2482  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
2483  Asm->OutStreamer.AddComment("Length of Common Information Entry");
2484  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
2485                           Asm->GetTempSymbol("debug_frame_common_begin"), 4);
2486
2487  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
2488  Asm->OutStreamer.AddComment("CIE Identifier Tag");
2489  Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2490  Asm->OutStreamer.AddComment("CIE Version");
2491  Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2492  Asm->OutStreamer.AddComment("CIE Augmentation");
2493  Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
2494  Asm->EmitULEB128(1, "CIE Code Alignment Factor");
2495  Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
2496  Asm->OutStreamer.AddComment("CIE RA Column");
2497  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
2498  const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
2499  Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2500
2501  std::vector<MachineMove> Moves;
2502  TFI->getInitialFrameState(Moves);
2503
2504  Asm->EmitFrameMoves(Moves, 0, false);
2505
2506  Asm->EmitAlignment(2);
2507  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
2508}
2509
2510/// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2511/// section.
2512void DwarfDebug::
2513emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2514  if (!Asm->MAI->doesDwarfRequireFrameSection())
2515    return;
2516
2517  // Start the dwarf frame section.
2518  Asm->OutStreamer.SwitchSection(
2519                              Asm->getObjFileLowering().getDwarfFrameSection());
2520
2521  Asm->OutStreamer.AddComment("Length of Frame Information Entry");
2522  MCSymbol *DebugFrameBegin =
2523    Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
2524  MCSymbol *DebugFrameEnd =
2525    Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
2526  Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
2527
2528  Asm->OutStreamer.EmitLabel(DebugFrameBegin);
2529
2530  Asm->OutStreamer.AddComment("FDE CIE offset");
2531  Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
2532                         DwarfFrameSectionSym);
2533
2534  Asm->OutStreamer.AddComment("FDE initial location");
2535  MCSymbol *FuncBeginSym =
2536    Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
2537  Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
2538                                   Asm->getTargetData().getPointerSize(),
2539                                   0/*AddrSpace*/);
2540
2541
2542  Asm->OutStreamer.AddComment("FDE address range");
2543  Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
2544                           FuncBeginSym, Asm->getTargetData().getPointerSize());
2545
2546  Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
2547
2548  Asm->EmitAlignment(2);
2549  Asm->OutStreamer.EmitLabel(DebugFrameEnd);
2550}
2551
2552/// emitDebugPubNames - Emit visible names into a debug pubnames section.
2553///
2554void DwarfDebug::emitDebugPubNames() {
2555  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2556         E = CUMap.end(); I != E; ++I) {
2557    CompileUnit *TheCU = I->second;
2558    // Start the dwarf pubnames section.
2559    Asm->OutStreamer.SwitchSection(
2560      Asm->getObjFileLowering().getDwarfPubNamesSection());
2561
2562    Asm->OutStreamer.AddComment("Length of Public Names Info");
2563    Asm->EmitLabelDifference(
2564      Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
2565      Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
2566
2567    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
2568                                                  TheCU->getID()));
2569
2570    Asm->OutStreamer.AddComment("DWARF Version");
2571    Asm->EmitInt16(dwarf::DWARF_VERSION);
2572
2573    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2574    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2575                           DwarfInfoSectionSym);
2576
2577    Asm->OutStreamer.AddComment("Compilation Unit Length");
2578    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2579                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
2580                             4);
2581
2582    const StringMap<DIE*> &Globals = TheCU->getGlobals();
2583    for (StringMap<DIE*>::const_iterator
2584           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2585      const char *Name = GI->getKeyData();
2586      DIE *Entity = GI->second;
2587
2588      Asm->OutStreamer.AddComment("DIE offset");
2589      Asm->EmitInt32(Entity->getOffset());
2590
2591      if (Asm->isVerbose())
2592        Asm->OutStreamer.AddComment("External Name");
2593      Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2594    }
2595
2596    Asm->OutStreamer.AddComment("End Mark");
2597    Asm->EmitInt32(0);
2598    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
2599                                                TheCU->getID()));
2600  }
2601}
2602
2603void DwarfDebug::emitDebugPubTypes() {
2604  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2605         E = CUMap.end(); I != E; ++I) {
2606    CompileUnit *TheCU = I->second;
2607    // Start the dwarf pubnames section.
2608    Asm->OutStreamer.SwitchSection(
2609      Asm->getObjFileLowering().getDwarfPubTypesSection());
2610    Asm->OutStreamer.AddComment("Length of Public Types Info");
2611    Asm->EmitLabelDifference(
2612      Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
2613      Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
2614
2615    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2616                                                  TheCU->getID()));
2617
2618    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2619    Asm->EmitInt16(dwarf::DWARF_VERSION);
2620
2621    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2622    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2623                           DwarfInfoSectionSym);
2624
2625    Asm->OutStreamer.AddComment("Compilation Unit Length");
2626    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2627                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
2628                             4);
2629
2630    const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2631    for (StringMap<DIE*>::const_iterator
2632           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2633      const char *Name = GI->getKeyData();
2634      DIE * Entity = GI->second;
2635
2636      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2637      Asm->EmitInt32(Entity->getOffset());
2638
2639      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2640      Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2641    }
2642
2643    Asm->OutStreamer.AddComment("End Mark");
2644    Asm->EmitInt32(0);
2645    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2646                                                  TheCU->getID()));
2647  }
2648}
2649
2650/// emitDebugStr - Emit visible names into a debug str section.
2651///
2652void DwarfDebug::emitDebugStr() {
2653  // Check to see if it is worth the effort.
2654  if (StringPool.empty()) return;
2655
2656  // Start the dwarf str section.
2657  Asm->OutStreamer.SwitchSection(
2658                                Asm->getObjFileLowering().getDwarfStrSection());
2659
2660  // Get all of the string pool entries and put them in an array by their ID so
2661  // we can sort them.
2662  SmallVector<std::pair<unsigned,
2663      StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2664
2665  for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2666       I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2667    Entries.push_back(std::make_pair(I->second.second, &*I));
2668
2669  array_pod_sort(Entries.begin(), Entries.end());
2670
2671  for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2672    // Emit a label for reference from debug information entries.
2673    Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2674
2675    // Emit the string itself.
2676    Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
2677  }
2678}
2679
2680/// emitDebugLoc - Emit visible names into a debug loc section.
2681///
2682void DwarfDebug::emitDebugLoc() {
2683  if (DotDebugLocEntries.empty())
2684    return;
2685
2686  for (SmallVector<DotDebugLocEntry, 4>::iterator
2687         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2688       I != E; ++I) {
2689    DotDebugLocEntry &Entry = *I;
2690    if (I + 1 != DotDebugLocEntries.end())
2691      Entry.Merge(I+1);
2692  }
2693
2694  // Start the dwarf loc section.
2695  Asm->OutStreamer.SwitchSection(
2696    Asm->getObjFileLowering().getDwarfLocSection());
2697  unsigned char Size = Asm->getTargetData().getPointerSize();
2698  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2699  unsigned index = 1;
2700  for (SmallVector<DotDebugLocEntry, 4>::iterator
2701         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2702       I != E; ++I, ++index) {
2703    DotDebugLocEntry &Entry = *I;
2704    if (Entry.isMerged()) continue;
2705    if (Entry.isEmpty()) {
2706      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2707      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2708      Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2709    } else {
2710      Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2711      Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2712      Asm->EmitDwarfRegOp(Entry.Loc);
2713    }
2714  }
2715}
2716
2717/// EmitDebugARanges - Emit visible names into a debug aranges section.
2718///
2719void DwarfDebug::EmitDebugARanges() {
2720  // Start the dwarf aranges section.
2721  Asm->OutStreamer.SwitchSection(
2722                          Asm->getObjFileLowering().getDwarfARangesSection());
2723}
2724
2725/// emitDebugRanges - Emit visible names into a debug ranges section.
2726///
2727void DwarfDebug::emitDebugRanges() {
2728  // Start the dwarf ranges section.
2729  Asm->OutStreamer.SwitchSection(
2730    Asm->getObjFileLowering().getDwarfRangesSection());
2731  unsigned char Size = Asm->getTargetData().getPointerSize();
2732  for (SmallVector<const MCSymbol *, 8>::iterator
2733         I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2734       I != E; ++I) {
2735    if (*I)
2736      Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2737    else
2738      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2739  }
2740}
2741
2742/// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2743///
2744void DwarfDebug::emitDebugMacInfo() {
2745  if (const MCSection *LineInfo =
2746      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2747    // Start the dwarf macinfo section.
2748    Asm->OutStreamer.SwitchSection(LineInfo);
2749  }
2750}
2751
2752/// emitDebugInlineInfo - Emit inline info using following format.
2753/// Section Header:
2754/// 1. length of section
2755/// 2. Dwarf version number
2756/// 3. address size.
2757///
2758/// Entries (one "entry" for each function that was inlined):
2759///
2760/// 1. offset into __debug_str section for MIPS linkage name, if exists;
2761///   otherwise offset into __debug_str for regular function name.
2762/// 2. offset into __debug_str section for regular function name.
2763/// 3. an unsigned LEB128 number indicating the number of distinct inlining
2764/// instances for the function.
2765///
2766/// The rest of the entry consists of a {die_offset, low_pc} pair for each
2767/// inlined instance; the die_offset points to the inlined_subroutine die in the
2768/// __debug_info section, and the low_pc is the starting address for the
2769/// inlining instance.
2770void DwarfDebug::emitDebugInlineInfo() {
2771  if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2772    return;
2773
2774  if (!FirstCU)
2775    return;
2776
2777  Asm->OutStreamer.SwitchSection(
2778                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
2779
2780  Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2781  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2782                           Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2783
2784  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2785
2786  Asm->OutStreamer.AddComment("Dwarf Version");
2787  Asm->EmitInt16(dwarf::DWARF_VERSION);
2788  Asm->OutStreamer.AddComment("Address Size (in bytes)");
2789  Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2790
2791  for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2792         E = InlinedSPNodes.end(); I != E; ++I) {
2793
2794    const MDNode *Node = *I;
2795    DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2796      = InlineInfo.find(Node);
2797    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2798    DISubprogram SP(Node);
2799    StringRef LName = SP.getLinkageName();
2800    StringRef Name = SP.getName();
2801
2802    Asm->OutStreamer.AddComment("MIPS linkage name");
2803    if (LName.empty()) {
2804      Asm->OutStreamer.EmitBytes(Name, 0);
2805      Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2806    } else
2807      Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2808                             DwarfStrSectionSym);
2809
2810    Asm->OutStreamer.AddComment("Function name");
2811    Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2812    Asm->EmitULEB128(Labels.size(), "Inline count");
2813
2814    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2815           LE = Labels.end(); LI != LE; ++LI) {
2816      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2817      Asm->EmitInt32(LI->second->getOffset());
2818
2819      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2820      Asm->OutStreamer.EmitSymbolValue(LI->first,
2821                                       Asm->getTargetData().getPointerSize(),0);
2822    }
2823  }
2824
2825  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2826}
2827