DwarfDebug.cpp revision 8b2139f5e988cd975f74dec8238aa74541a7658d
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 "DwarfAccelTable.h"
18#include "DwarfCompileUnit.h"
19#include "llvm/Constants.h"
20#include "llvm/Module.h"
21#include "llvm/Instructions.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineModuleInfo.h"
24#include "llvm/MC/MCAsmInfo.h"
25#include "llvm/MC/MCSection.h"
26#include "llvm/MC/MCStreamer.h"
27#include "llvm/MC/MCSymbol.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> DisableDebugInfoPrinting("disable-debug-info-print",
49                                              cl::Hidden,
50     cl::desc("Disable debug info printing"));
51
52static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
53     cl::desc("Make an absence of debug location information explicit."),
54     cl::init(false));
55
56static cl::opt<bool> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
57     cl::desc("Output prototype dwarf accelerator tables."),
58     cl::init(false));
59
60namespace {
61  const char *DWARFGroupName = "DWARF Emission";
62  const char *DbgTimerName = "DWARF Debug Writer";
63} // end anonymous namespace
64
65//===----------------------------------------------------------------------===//
66
67/// Configuration values for initial hash set sizes (log2).
68///
69static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
70
71namespace llvm {
72
73DIType DbgVariable::getType() const {
74  DIType Ty = Var.getType();
75  // FIXME: isBlockByrefVariable should be reformulated in terms of complex
76  // addresses instead.
77  if (Var.isBlockByrefVariable()) {
78    /* Byref variables, in Blocks, are declared by the programmer as
79       "SomeType VarName;", but the compiler creates a
80       __Block_byref_x_VarName struct, and gives the variable VarName
81       either the struct, or a pointer to the struct, as its type.  This
82       is necessary for various behind-the-scenes things the compiler
83       needs to do with by-reference variables in blocks.
84
85       However, as far as the original *programmer* is concerned, the
86       variable should still have type 'SomeType', as originally declared.
87
88       The following function dives into the __Block_byref_x_VarName
89       struct to find the original type of the variable.  This will be
90       passed back to the code generating the type for the Debug
91       Information Entry for the variable 'VarName'.  'VarName' will then
92       have the original type 'SomeType' in its debug information.
93
94       The original type 'SomeType' will be the type of the field named
95       'VarName' inside the __Block_byref_x_VarName struct.
96
97       NOTE: In order for this to not completely fail on the debugger
98       side, the Debug Information Entry for the variable VarName needs to
99       have a DW_AT_location that tells the debugger how to unwind through
100       the pointers and __Block_byref_x_VarName struct to find the actual
101       value of the variable.  The function addBlockByrefType does this.  */
102    DIType subType = Ty;
103    unsigned tag = Ty.getTag();
104
105    if (tag == dwarf::DW_TAG_pointer_type) {
106      DIDerivedType DTy = DIDerivedType(Ty);
107      subType = DTy.getTypeDerivedFrom();
108    }
109
110    DICompositeType blockStruct = DICompositeType(subType);
111    DIArray Elements = blockStruct.getTypeArray();
112
113    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
114      DIDescriptor Element = Elements.getElement(i);
115      DIDerivedType DT = DIDerivedType(Element);
116      if (getName() == DT.getName())
117        return (DT.getTypeDerivedFrom());
118    }
119    return Ty;
120  }
121  return Ty;
122}
123
124} // end llvm namespace
125
126DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
127  : Asm(A), MMI(Asm->MMI), FirstCU(0),
128    AbbreviationsSet(InitAbbreviationsSetSize),
129    PrevLabel(NULL) {
130  NextStringPoolNumber = 0;
131
132  DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
133  DwarfStrSectionSym = TextSectionSym = 0;
134  DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
135  FunctionBeginSym = FunctionEndSym = 0;
136  {
137    NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
138    beginModule(M);
139  }
140}
141DwarfDebug::~DwarfDebug() {
142}
143
144/// EmitSectionSym - Switch to the specified MCSection and emit an assembler
145/// temporary label to it if SymbolStem is specified.
146static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
147                                const char *SymbolStem = 0) {
148  Asm->OutStreamer.SwitchSection(Section);
149  if (!SymbolStem) return 0;
150
151  MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
152  Asm->OutStreamer.EmitLabel(TmpSym);
153  return TmpSym;
154}
155
156MCSymbol *DwarfDebug::getStringPool() {
157  return Asm->GetTempSymbol("section_str");
158}
159
160MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
161  std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
162  if (Entry.first) return Entry.first;
163
164  Entry.second = NextStringPoolNumber++;
165  return Entry.first = Asm->GetTempSymbol("string", Entry.second);
166}
167
168/// assignAbbrevNumber - Define a unique number for the abbreviation.
169///
170void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
171  // Profile the node so that we can make it unique.
172  FoldingSetNodeID ID;
173  Abbrev.Profile(ID);
174
175  // Check the set for priors.
176  DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
177
178  // If it's newly added.
179  if (InSet == &Abbrev) {
180    // Add to abbreviation list.
181    Abbreviations.push_back(&Abbrev);
182
183    // Assign the vector position + 1 as its number.
184    Abbrev.setNumber(Abbreviations.size());
185  } else {
186    // Assign existing abbreviation number.
187    Abbrev.setNumber(InSet->getNumber());
188  }
189}
190
191/// getRealLinkageName - If special LLVM prefix that is used to inform the asm
192/// printer to not emit usual symbol prefix before the symbol name is used then
193/// return linkage name after skipping this special LLVM prefix.
194static StringRef getRealLinkageName(StringRef LinkageName) {
195  char One = '\1';
196  if (LinkageName.startswith(StringRef(&One, 1)))
197    return LinkageName.substr(1);
198  return LinkageName;
199}
200
201/// updateSubprogramScopeDIE - Find DIE for the given subprogram and
202/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
203/// If there are global variables in this scope then create and insert
204/// DIEs for these variables.
205DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
206                                          const MDNode *SPNode) {
207  DIE *SPDie = SPCU->getDIE(SPNode);
208
209  assert(SPDie && "Unable to find subprogram DIE!");
210  DISubprogram SP(SPNode);
211
212  DISubprogram SPDecl = SP.getFunctionDeclaration();
213  if (!SPDecl.isSubprogram()) {
214    // There is not any need to generate specification DIE for a function
215    // defined at compile unit level. If a function is defined inside another
216    // function then gdb prefers the definition at top level and but does not
217    // expect specification DIE in parent function. So avoid creating
218    // specification DIE for a function defined inside a function.
219    if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
220        !SP.getContext().isFile() &&
221        !isSubprogramContext(SP.getContext())) {
222      SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
223
224      // Add arguments.
225      DICompositeType SPTy = SP.getType();
226      DIArray Args = SPTy.getTypeArray();
227      unsigned SPTag = SPTy.getTag();
228      if (SPTag == dwarf::DW_TAG_subroutine_type)
229        for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
230          DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
231          DIType ATy = DIType(DIType(Args.getElement(i)));
232          SPCU->addType(Arg, ATy);
233          if (ATy.isArtificial())
234            SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
235          SPDie->addChild(Arg);
236        }
237      DIE *SPDeclDie = SPDie;
238      SPDie = new DIE(dwarf::DW_TAG_subprogram);
239      SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
240                        SPDeclDie);
241      SPCU->addDie(SPDie);
242    }
243  }
244  // Pick up abstract subprogram DIE.
245  if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
246    SPDie = new DIE(dwarf::DW_TAG_subprogram);
247    SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
248                      dwarf::DW_FORM_ref4, AbsSPDIE);
249    SPCU->addDie(SPDie);
250  }
251
252  SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
253                 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
254  SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
255                 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
256  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
257  MachineLocation Location(RI->getFrameRegister(*Asm->MF));
258  SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
259
260  return SPDie;
261}
262
263/// constructLexicalScope - Construct new DW_TAG_lexical_block
264/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
265DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
266                                          LexicalScope *Scope) {
267  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
268  if (Scope->isAbstractScope())
269    return ScopeDIE;
270
271  const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
272  if (Ranges.empty())
273    return 0;
274
275  SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
276  if (Ranges.size() > 1) {
277    // .debug_range section has not been laid out yet. Emit offset in
278    // .debug_range as a uint, size 4, for now. emitDIE will handle
279    // DW_AT_ranges appropriately.
280    TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
281                   DebugRangeSymbols.size()
282                   * Asm->getTargetData().getPointerSize());
283    for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
284         RE = Ranges.end(); RI != RE; ++RI) {
285      DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
286      DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
287    }
288    DebugRangeSymbols.push_back(NULL);
289    DebugRangeSymbols.push_back(NULL);
290    return ScopeDIE;
291  }
292
293  const MCSymbol *Start = getLabelBeforeInsn(RI->first);
294  const MCSymbol *End = getLabelAfterInsn(RI->second);
295
296  if (End == 0) return 0;
297
298  assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
299  assert(End->isDefined() && "Invalid end label for an inlined scope!");
300
301  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
302  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
303
304  return ScopeDIE;
305}
306
307/// constructInlinedScopeDIE - This scope represents inlined body of
308/// a function. Construct DIE to represent this concrete inlined copy
309/// of the function.
310DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
311                                          LexicalScope *Scope) {
312  const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
313  assert(Ranges.empty() == false &&
314         "LexicalScope does not have instruction markers!");
315
316  if (!Scope->getScopeNode())
317    return NULL;
318  DIScope DS(Scope->getScopeNode());
319  DISubprogram InlinedSP = getDISubprogram(DS);
320  DIE *OriginDIE = TheCU->getDIE(InlinedSP);
321  if (!OriginDIE) {
322    DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
323    return NULL;
324  }
325
326  SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
327  const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
328  const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
329
330  if (StartLabel == 0 || EndLabel == 0) {
331    assert(0 && "Unexpected Start and End labels for a inlined scope!");
332    return 0;
333  }
334  assert(StartLabel->isDefined() &&
335         "Invalid starting label for an inlined scope!");
336  assert(EndLabel->isDefined() &&
337         "Invalid end label for an inlined scope!");
338
339  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
340  TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
341                     dwarf::DW_FORM_ref4, OriginDIE);
342
343  if (Ranges.size() > 1) {
344    // .debug_range section has not been laid out yet. Emit offset in
345    // .debug_range as a uint, size 4, for now. emitDIE will handle
346    // DW_AT_ranges appropriately.
347    TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
348                   DebugRangeSymbols.size()
349                   * Asm->getTargetData().getPointerSize());
350    for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
351         RE = Ranges.end(); RI != RE; ++RI) {
352      DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
353      DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
354    }
355    DebugRangeSymbols.push_back(NULL);
356    DebugRangeSymbols.push_back(NULL);
357  } else {
358    TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
359                    StartLabel);
360    TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
361                    EndLabel);
362  }
363
364  InlinedSubprogramDIEs.insert(OriginDIE);
365
366  // Track the start label for this inlined function.
367  //.debug_inlined section specification does not clearly state how
368  // to emit inlined scope that is split into multiple instruction ranges.
369  // For now, use first instruction range and emit low_pc/high_pc pair and
370  // corresponding .debug_inlined section entry for this pair.
371  DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
372    I = InlineInfo.find(InlinedSP);
373
374  if (I == InlineInfo.end()) {
375    InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
376    InlinedSPNodes.push_back(InlinedSP);
377  } else
378    I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
379
380  DILocation DL(Scope->getInlinedAt());
381  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
382  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
383
384  return ScopeDIE;
385}
386
387/// constructScopeDIE - Construct a DIE for this scope.
388DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
389  if (!Scope || !Scope->getScopeNode())
390    return NULL;
391
392  SmallVector<DIE *, 8> Children;
393
394  // Collect arguments for current function.
395  if (LScopes.isCurrentFunctionScope(Scope))
396    for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
397      if (DbgVariable *ArgDV = CurrentFnArguments[i])
398        if (DIE *Arg =
399            TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
400          Children.push_back(Arg);
401
402  // Collect lexical scope children first.
403  const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
404  for (unsigned i = 0, N = Variables.size(); i < N; ++i)
405    if (DIE *Variable =
406        TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
407      Children.push_back(Variable);
408  const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
409  for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
410    if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
411      Children.push_back(Nested);
412  DIScope DS(Scope->getScopeNode());
413  DIE *ScopeDIE = NULL;
414  if (Scope->getInlinedAt())
415    ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
416  else if (DS.isSubprogram()) {
417    ProcessedSPNodes.insert(DS);
418    if (Scope->isAbstractScope()) {
419      ScopeDIE = TheCU->getDIE(DS);
420      // Note down abstract DIE.
421      if (ScopeDIE)
422        AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
423    }
424    else
425      ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
426  }
427  else {
428    // There is no need to emit empty lexical block DIE.
429    if (Children.empty())
430      return NULL;
431    ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
432  }
433
434  if (!ScopeDIE) return NULL;
435
436  // Add children
437  for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
438         E = Children.end(); I != E; ++I)
439    ScopeDIE->addChild(*I);
440
441  if (DS.isSubprogram())
442   TheCU->addPubTypes(DISubprogram(DS));
443
444  if (DS.isSubprogram() && !Scope->isAbstractScope())
445    TheCU->addAccelName(DISubprogram(DS).getName(), ScopeDIE);
446
447 return ScopeDIE;
448}
449
450/// GetOrCreateSourceID - Look up the source id with the given directory and
451/// source file names. If none currently exists, create a new id and insert it
452/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
453/// maps as well.
454unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
455                                         StringRef DirName) {
456  // If FE did not provide a file name, then assume stdin.
457  if (FileName.empty())
458    return GetOrCreateSourceID("<stdin>", StringRef());
459
460  // TODO: this might not belong here. See if we can factor this better.
461  if (DirName == CompilationDir)
462    DirName = "";
463
464  unsigned SrcId = SourceIdMap.size()+1;
465  std::pair<std::string, std::string> SourceName =
466      std::make_pair(FileName, DirName);
467  std::pair<std::pair<std::string, std::string>, unsigned> Entry =
468      make_pair(SourceName, SrcId);
469
470  std::map<std::pair<std::string, std::string>, unsigned>::iterator I;
471  bool NewlyInserted;
472  tie(I, NewlyInserted) = SourceIdMap.insert(Entry);
473  if (!NewlyInserted)
474    return I->second;
475
476  // Print out a .file directive to specify files for .loc directives.
477  Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.first.second,
478                                          Entry.first.first);
479
480  return SrcId;
481}
482
483/// constructCompileUnit - Create new CompileUnit for the given
484/// metadata node with tag DW_TAG_compile_unit.
485CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
486  DICompileUnit DIUnit(N);
487  StringRef FN = DIUnit.getFilename();
488  CompilationDir = DIUnit.getDirectory();
489  unsigned ID = GetOrCreateSourceID(FN, CompilationDir);
490
491  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
492  CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
493  NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
494  NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
495                 DIUnit.getLanguage());
496  NewCU->addString(Die, dwarf::DW_AT_name, FN);
497  // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
498  // simplifies debug range entries.
499  NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
500  // DW_AT_stmt_list is a offset of line number information for this
501  // compile unit in debug_line section.
502  if (Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
503    NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
504                    Asm->GetTempSymbol("section_line"));
505  else
506    NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
507
508  if (!CompilationDir.empty())
509    NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
510  if (DIUnit.isOptimized())
511    NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
512
513  StringRef Flags = DIUnit.getFlags();
514  if (!Flags.empty())
515    NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
516
517  if (unsigned RVer = DIUnit.getRunTimeVersion())
518    NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
519            dwarf::DW_FORM_data1, RVer);
520
521  if (!FirstCU)
522    FirstCU = NewCU;
523  CUMap.insert(std::make_pair(N, NewCU));
524  return NewCU;
525}
526
527static bool isObjCClass(StringRef Name) {
528  return Name.startswith("+") || Name.startswith("-");
529}
530
531static bool hasObjCCategory(StringRef Name) {
532  if (!isObjCClass(Name)) return false;
533
534  size_t pos = Name.find(')');
535  if (pos != std::string::npos) {
536    if (Name[pos+1] != ' ') return false;
537    return true;
538  }
539  return false;
540}
541
542static void getObjCClassCategory(StringRef In, StringRef &Class,
543                                 StringRef &Category) {
544  if (!hasObjCCategory(In)) {
545    Class = In.slice(In.find('[') + 1, In.find(' '));
546    Category = "";
547    return;
548  }
549
550  Class = In.slice(In.find('[') + 1, In.find('('));
551  Category = In.slice(In.find('[') + 1, In.find(' '));
552  return;
553}
554
555/// construct SubprogramDIE - Construct subprogram DIE.
556void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
557                                        const MDNode *N) {
558  CompileUnit *&CURef = SPMap[N];
559  if (CURef)
560    return;
561  CURef = TheCU;
562
563  DISubprogram SP(N);
564  if (!SP.isDefinition())
565    // This is a method declaration which will be handled while constructing
566    // class type.
567    return;
568
569  DISubprogram SPDecl = SP.getFunctionDeclaration();
570  DIE *DeclDie = NULL;
571  if (SPDecl.isSubprogram()) {
572    DeclDie = TheCU->getOrCreateSubprogramDIE(SPDecl);
573  }
574
575  DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
576
577  if (DeclDie) {
578    // Refer function declaration directly.
579    TheCU->addDIEEntry(SubprogramDie, dwarf::DW_AT_specification,
580                       dwarf::DW_FORM_ref4, DeclDie);
581  }
582
583  // Add to map.
584  TheCU->insertDIE(N, SubprogramDie);
585
586  // Add to context owner.
587  TheCU->addToContextOwner(SubprogramDie, SP.getContext());
588
589  // Expose as global.
590  TheCU->addGlobal(SP.getName(), SubprogramDie);
591
592  // Add to Accel Names
593  TheCU->addAccelName(SP.getName(), SubprogramDie);
594
595  // If this is an Objective-C selector name add it to the ObjC accelerator too.
596  if (isObjCClass(SP.getName())) {
597    StringRef Class, Category;
598    getObjCClassCategory(SP.getName(), Class, Category);
599    TheCU->addAccelObjC(Class, SubprogramDie);
600    if (Category != "")
601      TheCU->addAccelObjC(Category, SubprogramDie);
602  }
603
604  return;
605}
606
607/// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
608/// as llvm.dbg.enum and llvm.dbg.ty
609void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
610  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
611    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
612      const MDNode *N = NMD->getOperand(i);
613      if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
614        constructSubprogramDIE(CU, N);
615    }
616
617  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
618    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
619      const MDNode *N = NMD->getOperand(i);
620      if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
621        CU->createGlobalVariableDIE(N);
622    }
623
624  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
625    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
626      DIType Ty(NMD->getOperand(i));
627      if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
628        CU->getOrCreateTypeDIE(Ty);
629    }
630
631  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
632    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
633      DIType Ty(NMD->getOperand(i));
634      if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
635        CU->getOrCreateTypeDIE(Ty);
636    }
637}
638
639/// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
640/// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
641bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
642  DebugInfoFinder DbgFinder;
643  DbgFinder.processModule(*M);
644
645  bool HasDebugInfo = false;
646  // Scan all the compile-units to see if there are any marked as the main
647  // unit. If not, we do not generate debug info.
648  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
649         E = DbgFinder.compile_unit_end(); I != E; ++I) {
650    if (DICompileUnit(*I).isMain()) {
651      HasDebugInfo = true;
652      break;
653    }
654  }
655  if (!HasDebugInfo) return false;
656
657  // Create all the compile unit DIEs.
658  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
659         E = DbgFinder.compile_unit_end(); I != E; ++I)
660    constructCompileUnit(*I);
661
662  // Create DIEs for each global variable.
663  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
664         E = DbgFinder.global_variable_end(); I != E; ++I) {
665    const MDNode *N = *I;
666    if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
667      CU->createGlobalVariableDIE(N);
668  }
669
670  // Create DIEs for each subprogram.
671  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
672         E = DbgFinder.subprogram_end(); I != E; ++I) {
673    const MDNode *N = *I;
674    if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
675      constructSubprogramDIE(CU, N);
676  }
677
678  return HasDebugInfo;
679}
680
681/// beginModule - Emit all Dwarf sections that should come prior to the
682/// content. Create global DIEs and emit initial debug info sections.
683/// This is invoked by the target AsmPrinter.
684void DwarfDebug::beginModule(Module *M) {
685  if (DisableDebugInfoPrinting)
686    return;
687
688  // If module has named metadata anchors then use them, otherwise scan the
689  // module using debug info finder to collect debug info.
690  NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
691  if (CU_Nodes) {
692    for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
693      DICompileUnit CUNode(CU_Nodes->getOperand(i));
694      CompileUnit *CU = constructCompileUnit(CUNode);
695      DIArray GVs = CUNode.getGlobalVariables();
696      for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
697        CU->createGlobalVariableDIE(GVs.getElement(i));
698      DIArray SPs = CUNode.getSubprograms();
699      for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
700        constructSubprogramDIE(CU, SPs.getElement(i));
701      DIArray EnumTypes = CUNode.getEnumTypes();
702      for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
703        CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
704      DIArray RetainedTypes = CUNode.getRetainedTypes();
705      for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
706        CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
707    }
708  } else if (!collectLegacyDebugInfo(M))
709    return;
710
711  collectInfoFromNamedMDNodes(M);
712
713  // Tell MMI that we have debug info.
714  MMI->setDebugInfoAvailability(true);
715
716  // Emit initial sections.
717  EmitSectionLabels();
718
719  // Prime section data.
720  SectionMap.insert(Asm->getObjFileLowering().getTextSection());
721}
722
723/// endModule - Emit all Dwarf sections that should come after the content.
724///
725void DwarfDebug::endModule() {
726  if (!FirstCU) return;
727  const Module *M = MMI->getModule();
728  DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
729
730  // Collect info for variables that were optimized out.
731  if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
732    for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
733      DICompileUnit TheCU(CU_Nodes->getOperand(i));
734      DIArray Subprograms = TheCU.getSubprograms();
735      for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
736        DISubprogram SP(Subprograms.getElement(i));
737        if (ProcessedSPNodes.count(SP) != 0) continue;
738        if (!SP.Verify()) continue;
739        if (!SP.isDefinition()) continue;
740        DIArray Variables = SP.getVariables();
741        if (Variables.getNumElements() == 0) continue;
742
743        LexicalScope *Scope =
744          new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
745        DeadFnScopeMap[SP] = Scope;
746
747        // Construct subprogram DIE and add variables DIEs.
748        CompileUnit *SPCU = CUMap.lookup(TheCU);
749        assert(SPCU && "Unable to find Compile Unit!");
750        constructSubprogramDIE(SPCU, SP);
751        DIE *ScopeDIE = SPCU->getDIE(SP);
752        for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
753          DIVariable DV(Variables.getElement(vi));
754          if (!DV.Verify()) continue;
755          DbgVariable *NewVar = new DbgVariable(DV, NULL);
756          if (DIE *VariableDIE =
757              SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
758            ScopeDIE->addChild(VariableDIE);
759        }
760      }
761    }
762  }
763
764  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
765  for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
766         AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
767    DIE *ISP = *AI;
768    FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
769  }
770
771  // Emit DW_AT_containing_type attribute to connect types with their
772  // vtable holding type.
773  for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
774         CUE = CUMap.end(); CUI != CUE; ++CUI) {
775    CompileUnit *TheCU = CUI->second;
776    TheCU->constructContainingTypeDIEs();
777  }
778
779  // Standard sections final addresses.
780  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
781  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
782  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
783  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
784
785  // End text sections.
786  for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
787    Asm->OutStreamer.SwitchSection(SectionMap[i]);
788    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
789  }
790
791  // Compute DIE offsets and sizes.
792  computeSizeAndOffsets();
793
794  // Emit all the DIEs into a debug info section
795  emitDebugInfo();
796
797  // Corresponding abbreviations into a abbrev section.
798  emitAbbreviations();
799
800  // Emit info into a dwarf accelerator table sections.
801  if (DwarfAccelTables) {
802    emitAccelNames();
803    emitAccelObjC();
804    emitAccelNamespaces();
805    emitAccelTypes();
806  }
807
808  // Emit info into a debug pubnames section.
809  emitDebugPubNames();
810
811  // Emit info into a debug pubtypes section.
812  emitDebugPubTypes();
813
814  // Emit info into a debug loc section.
815  emitDebugLoc();
816
817  // Emit info into a debug aranges section.
818  EmitDebugARanges();
819
820  // Emit info into a debug ranges section.
821  emitDebugRanges();
822
823  // Emit info into a debug macinfo section.
824  emitDebugMacInfo();
825
826  // Emit inline info.
827  emitDebugInlineInfo();
828
829  // Emit info into a debug str section.
830  emitDebugStr();
831
832  // clean up.
833  DeleteContainerSeconds(DeadFnScopeMap);
834  SPMap.clear();
835  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
836         E = CUMap.end(); I != E; ++I)
837    delete I->second;
838  FirstCU = NULL;  // Reset for the next Module, if any.
839}
840
841/// findAbstractVariable - Find abstract variable, if any, associated with Var.
842DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
843                                              DebugLoc ScopeLoc) {
844  LLVMContext &Ctx = DV->getContext();
845  // More then one inlined variable corresponds to one abstract variable.
846  DIVariable Var = cleanseInlinedVariable(DV, Ctx);
847  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
848  if (AbsDbgVariable)
849    return AbsDbgVariable;
850
851  LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
852  if (!Scope)
853    return NULL;
854
855  AbsDbgVariable = new DbgVariable(Var, NULL);
856  addScopeVariable(Scope, AbsDbgVariable);
857  AbstractVariables[Var] = AbsDbgVariable;
858  return AbsDbgVariable;
859}
860
861/// addCurrentFnArgument - If Var is a current function argument then add
862/// it to CurrentFnArguments list.
863bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
864                                      DbgVariable *Var, LexicalScope *Scope) {
865  if (!LScopes.isCurrentFunctionScope(Scope))
866    return false;
867  DIVariable DV = Var->getVariable();
868  if (DV.getTag() != dwarf::DW_TAG_arg_variable)
869    return false;
870  unsigned ArgNo = DV.getArgNumber();
871  if (ArgNo == 0)
872    return false;
873
874  size_t Size = CurrentFnArguments.size();
875  if (Size == 0)
876    CurrentFnArguments.resize(MF->getFunction()->arg_size());
877  // llvm::Function argument size is not good indicator of how many
878  // arguments does the function have at source level.
879  if (ArgNo > Size)
880    CurrentFnArguments.resize(ArgNo * 2);
881  CurrentFnArguments[ArgNo - 1] = Var;
882  return true;
883}
884
885/// collectVariableInfoFromMMITable - Collect variable information from
886/// side table maintained by MMI.
887void
888DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
889                                   SmallPtrSet<const MDNode *, 16> &Processed) {
890  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
891  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
892         VE = VMap.end(); VI != VE; ++VI) {
893    const MDNode *Var = VI->first;
894    if (!Var) continue;
895    Processed.insert(Var);
896    DIVariable DV(Var);
897    const std::pair<unsigned, DebugLoc> &VP = VI->second;
898
899    LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
900
901    // If variable scope is not found then skip this variable.
902    if (Scope == 0)
903      continue;
904
905    DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
906    DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
907    RegVar->setFrameIndex(VP.first);
908    if (!addCurrentFnArgument(MF, RegVar, Scope))
909      addScopeVariable(Scope, RegVar);
910    if (AbsDbgVariable)
911      AbsDbgVariable->setFrameIndex(VP.first);
912  }
913}
914
915/// isDbgValueInDefinedReg - Return true if debug value, encoded by
916/// DBG_VALUE instruction, is in a defined reg.
917static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
918  assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
919  return MI->getNumOperands() == 3 &&
920         MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
921         MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
922}
923
924/// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
925/// at MI.
926static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
927                                         const MCSymbol *FLabel,
928                                         const MCSymbol *SLabel,
929                                         const MachineInstr *MI) {
930  const MDNode *Var =  MI->getOperand(MI->getNumOperands() - 1).getMetadata();
931
932  if (MI->getNumOperands() != 3) {
933    MachineLocation MLoc = Asm->getDebugValueLocation(MI);
934    return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
935  }
936  if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
937    MachineLocation MLoc;
938    MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
939    return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
940  }
941  if (MI->getOperand(0).isImm())
942    return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
943  if (MI->getOperand(0).isFPImm())
944    return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
945  if (MI->getOperand(0).isCImm())
946    return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
947
948  assert(0 && "Unexpected 3 operand DBG_VALUE instruction!");
949  return DotDebugLocEntry();
950}
951
952/// collectVariableInfo - Find variables for each lexical scope.
953void
954DwarfDebug::collectVariableInfo(const MachineFunction *MF,
955                                SmallPtrSet<const MDNode *, 16> &Processed) {
956
957  /// collection info from MMI table.
958  collectVariableInfoFromMMITable(MF, Processed);
959
960  for (SmallVectorImpl<const MDNode*>::const_iterator
961         UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
962         ++UVI) {
963    const MDNode *Var = *UVI;
964    if (Processed.count(Var))
965      continue;
966
967    // History contains relevant DBG_VALUE instructions for Var and instructions
968    // clobbering it.
969    SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
970    if (History.empty())
971      continue;
972    const MachineInstr *MInsn = History.front();
973
974    DIVariable DV(Var);
975    LexicalScope *Scope = NULL;
976    if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
977        DISubprogram(DV.getContext()).describes(MF->getFunction()))
978      Scope = LScopes.getCurrentFunctionScope();
979    else {
980      if (DV.getVersion() <= LLVMDebugVersion9)
981        Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
982      else {
983        if (MDNode *IA = DV.getInlinedAt())
984          Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
985        else
986          Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
987      }
988    }
989    // If variable scope is not found then skip this variable.
990    if (!Scope)
991      continue;
992
993    Processed.insert(DV);
994    assert(MInsn->isDebugValue() && "History must begin with debug value");
995    DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
996    DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
997    if (!addCurrentFnArgument(MF, RegVar, Scope))
998      addScopeVariable(Scope, RegVar);
999    if (AbsVar)
1000      AbsVar->setMInsn(MInsn);
1001
1002    // Simple ranges that are fully coalesced.
1003    if (History.size() <= 1 || (History.size() == 2 &&
1004                                MInsn->isIdenticalTo(History.back()))) {
1005      RegVar->setMInsn(MInsn);
1006      continue;
1007    }
1008
1009    // handle multiple DBG_VALUE instructions describing one variable.
1010    RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1011
1012    for (SmallVectorImpl<const MachineInstr*>::const_iterator
1013           HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1014      const MachineInstr *Begin = *HI;
1015      assert(Begin->isDebugValue() && "Invalid History entry");
1016
1017      // Check if DBG_VALUE is truncating a range.
1018      if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1019          && !Begin->getOperand(0).getReg())
1020        continue;
1021
1022      // Compute the range for a register location.
1023      const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1024      const MCSymbol *SLabel = 0;
1025
1026      if (HI + 1 == HE)
1027        // If Begin is the last instruction in History then its value is valid
1028        // until the end of the function.
1029        SLabel = FunctionEndSym;
1030      else {
1031        const MachineInstr *End = HI[1];
1032        DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1033              << "\t" << *Begin << "\t" << *End << "\n");
1034        if (End->isDebugValue())
1035          SLabel = getLabelBeforeInsn(End);
1036        else {
1037          // End is a normal instruction clobbering the range.
1038          SLabel = getLabelAfterInsn(End);
1039          assert(SLabel && "Forgot label after clobber instruction");
1040          ++HI;
1041        }
1042      }
1043
1044      // The value is valid until the next DBG_VALUE or clobber.
1045      DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1046    }
1047    DotDebugLocEntries.push_back(DotDebugLocEntry());
1048  }
1049
1050  // Collect info for variables that were optimized out.
1051  LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1052  DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1053  for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1054    DIVariable DV(Variables.getElement(i));
1055    if (!DV || !DV.Verify() || !Processed.insert(DV))
1056      continue;
1057    if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1058      addScopeVariable(Scope, new DbgVariable(DV, NULL));
1059  }
1060}
1061
1062/// getLabelBeforeInsn - Return Label preceding the instruction.
1063const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1064  MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1065  assert(Label && "Didn't insert label before instruction");
1066  return Label;
1067}
1068
1069/// getLabelAfterInsn - Return Label immediately following the instruction.
1070const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1071  return LabelsAfterInsn.lookup(MI);
1072}
1073
1074/// beginInstruction - Process beginning of an instruction.
1075void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1076  // Check if source location changes, but ignore DBG_VALUE locations.
1077  if (!MI->isDebugValue()) {
1078    DebugLoc DL = MI->getDebugLoc();
1079    if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1080      unsigned Flags = DWARF2_FLAG_IS_STMT;
1081      PrevInstLoc = DL;
1082      if (DL == PrologEndLoc) {
1083        Flags |= DWARF2_FLAG_PROLOGUE_END;
1084        PrologEndLoc = DebugLoc();
1085      }
1086      if (!DL.isUnknown()) {
1087        const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1088        recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1089      } else
1090        recordSourceLine(0, 0, 0, 0);
1091    }
1092  }
1093
1094  // Insert labels where requested.
1095  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1096    LabelsBeforeInsn.find(MI);
1097
1098  // No label needed.
1099  if (I == LabelsBeforeInsn.end())
1100    return;
1101
1102  // Label already assigned.
1103  if (I->second)
1104    return;
1105
1106  if (!PrevLabel) {
1107    PrevLabel = MMI->getContext().CreateTempSymbol();
1108    Asm->OutStreamer.EmitLabel(PrevLabel);
1109  }
1110  I->second = PrevLabel;
1111}
1112
1113/// endInstruction - Process end of an instruction.
1114void DwarfDebug::endInstruction(const MachineInstr *MI) {
1115  // Don't create a new label after DBG_VALUE instructions.
1116  // They don't generate code.
1117  if (!MI->isDebugValue())
1118    PrevLabel = 0;
1119
1120  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1121    LabelsAfterInsn.find(MI);
1122
1123  // No label needed.
1124  if (I == LabelsAfterInsn.end())
1125    return;
1126
1127  // Label already assigned.
1128  if (I->second)
1129    return;
1130
1131  // We need a label after this instruction.
1132  if (!PrevLabel) {
1133    PrevLabel = MMI->getContext().CreateTempSymbol();
1134    Asm->OutStreamer.EmitLabel(PrevLabel);
1135  }
1136  I->second = PrevLabel;
1137}
1138
1139/// identifyScopeMarkers() -
1140/// Each LexicalScope has first instruction and last instruction to mark
1141/// beginning and end of a scope respectively. Create an inverse map that list
1142/// scopes starts (and ends) with an instruction. One instruction may start (or
1143/// end) multiple scopes. Ignore scopes that are not reachable.
1144void DwarfDebug::identifyScopeMarkers() {
1145  SmallVector<LexicalScope *, 4> WorkList;
1146  WorkList.push_back(LScopes.getCurrentFunctionScope());
1147  while (!WorkList.empty()) {
1148    LexicalScope *S = WorkList.pop_back_val();
1149
1150    const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1151    if (!Children.empty())
1152      for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1153             SE = Children.end(); SI != SE; ++SI)
1154        WorkList.push_back(*SI);
1155
1156    if (S->isAbstractScope())
1157      continue;
1158
1159    const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1160    if (Ranges.empty())
1161      continue;
1162    for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1163           RE = Ranges.end(); RI != RE; ++RI) {
1164      assert(RI->first && "InsnRange does not have first instruction!");
1165      assert(RI->second && "InsnRange does not have second instruction!");
1166      requestLabelBeforeInsn(RI->first);
1167      requestLabelAfterInsn(RI->second);
1168    }
1169  }
1170}
1171
1172/// getScopeNode - Get MDNode for DebugLoc's scope.
1173static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1174  if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1175    return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1176  return DL.getScope(Ctx);
1177}
1178
1179/// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1180/// line number  info for the function.
1181static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1182  const MDNode *Scope = getScopeNode(DL, Ctx);
1183  DISubprogram SP = getDISubprogram(Scope);
1184  if (SP.Verify())
1185    return DebugLoc::get(SP.getLineNumber(), 0, SP);
1186  return DebugLoc();
1187}
1188
1189/// beginFunction - Gather pre-function debug information.  Assumes being
1190/// emitted immediately after the function entry point.
1191void DwarfDebug::beginFunction(const MachineFunction *MF) {
1192  if (!MMI->hasDebugInfo()) return;
1193  LScopes.initialize(*MF);
1194  if (LScopes.empty()) return;
1195  identifyScopeMarkers();
1196
1197  FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1198                                        Asm->getFunctionNumber());
1199  // Assumes in correct section after the entry point.
1200  Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1201
1202  assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1203
1204  const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1205  /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1206  std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1207
1208  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1209       I != E; ++I) {
1210    bool AtBlockEntry = true;
1211    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1212         II != IE; ++II) {
1213      const MachineInstr *MI = II;
1214
1215      if (MI->isDebugValue()) {
1216        assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1217
1218        // Keep track of user variables.
1219        const MDNode *Var =
1220          MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1221
1222        // Variable is in a register, we need to check for clobbers.
1223        if (isDbgValueInDefinedReg(MI))
1224          LiveUserVar[MI->getOperand(0).getReg()] = Var;
1225
1226        // Check the history of this variable.
1227        SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1228        if (History.empty()) {
1229          UserVariables.push_back(Var);
1230          // The first mention of a function argument gets the FunctionBeginSym
1231          // label, so arguments are visible when breaking at function entry.
1232          DIVariable DV(Var);
1233          if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1234              DISubprogram(getDISubprogram(DV.getContext()))
1235                .describes(MF->getFunction()))
1236            LabelsBeforeInsn[MI] = FunctionBeginSym;
1237        } else {
1238          // We have seen this variable before. Try to coalesce DBG_VALUEs.
1239          const MachineInstr *Prev = History.back();
1240          if (Prev->isDebugValue()) {
1241            // Coalesce identical entries at the end of History.
1242            if (History.size() >= 2 &&
1243                Prev->isIdenticalTo(History[History.size() - 2])) {
1244              DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1245                    << "\t" << *Prev
1246                    << "\t" << *History[History.size() - 2] << "\n");
1247              History.pop_back();
1248            }
1249
1250            // Terminate old register assignments that don't reach MI;
1251            MachineFunction::const_iterator PrevMBB = Prev->getParent();
1252            if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1253                isDbgValueInDefinedReg(Prev)) {
1254              // Previous register assignment needs to terminate at the end of
1255              // its basic block.
1256              MachineBasicBlock::const_iterator LastMI =
1257                PrevMBB->getLastNonDebugInstr();
1258              if (LastMI == PrevMBB->end()) {
1259                // Drop DBG_VALUE for empty range.
1260                DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1261                      << "\t" << *Prev << "\n");
1262                History.pop_back();
1263              }
1264              else {
1265                // Terminate after LastMI.
1266                History.push_back(LastMI);
1267              }
1268            }
1269          }
1270        }
1271        History.push_back(MI);
1272      } else {
1273        // Not a DBG_VALUE instruction.
1274        if (!MI->isLabel())
1275          AtBlockEntry = false;
1276
1277        // First known non DBG_VALUE location marks beginning of function
1278        // body.
1279        if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1280          PrologEndLoc = MI->getDebugLoc();
1281
1282        // Check if the instruction clobbers any registers with debug vars.
1283        for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1284               MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1285          if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1286            continue;
1287          for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1288               unsigned Reg = *AI; ++AI) {
1289            const MDNode *Var = LiveUserVar[Reg];
1290            if (!Var)
1291              continue;
1292            // Reg is now clobbered.
1293            LiveUserVar[Reg] = 0;
1294
1295            // Was MD last defined by a DBG_VALUE referring to Reg?
1296            DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1297            if (HistI == DbgValues.end())
1298              continue;
1299            SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1300            if (History.empty())
1301              continue;
1302            const MachineInstr *Prev = History.back();
1303            // Sanity-check: Register assignments are terminated at the end of
1304            // their block.
1305            if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1306              continue;
1307            // Is the variable still in Reg?
1308            if (!isDbgValueInDefinedReg(Prev) ||
1309                Prev->getOperand(0).getReg() != Reg)
1310              continue;
1311            // Var is clobbered. Make sure the next instruction gets a label.
1312            History.push_back(MI);
1313          }
1314        }
1315      }
1316    }
1317  }
1318
1319  for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1320       I != E; ++I) {
1321    SmallVectorImpl<const MachineInstr*> &History = I->second;
1322    if (History.empty())
1323      continue;
1324
1325    // Make sure the final register assignments are terminated.
1326    const MachineInstr *Prev = History.back();
1327    if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1328      const MachineBasicBlock *PrevMBB = Prev->getParent();
1329      MachineBasicBlock::const_iterator LastMI =
1330        PrevMBB->getLastNonDebugInstr();
1331      if (LastMI == PrevMBB->end())
1332        // Drop DBG_VALUE for empty range.
1333        History.pop_back();
1334      else {
1335        // Terminate after LastMI.
1336        History.push_back(LastMI);
1337      }
1338    }
1339    // Request labels for the full history.
1340    for (unsigned i = 0, e = History.size(); i != e; ++i) {
1341      const MachineInstr *MI = History[i];
1342      if (MI->isDebugValue())
1343        requestLabelBeforeInsn(MI);
1344      else
1345        requestLabelAfterInsn(MI);
1346    }
1347  }
1348
1349  PrevInstLoc = DebugLoc();
1350  PrevLabel = FunctionBeginSym;
1351
1352  // Record beginning of function.
1353  if (!PrologEndLoc.isUnknown()) {
1354    DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1355                                       MF->getFunction()->getContext());
1356    recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1357                     FnStartDL.getScope(MF->getFunction()->getContext()),
1358                     DWARF2_FLAG_IS_STMT);
1359  }
1360}
1361
1362void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1363//  SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1364  ScopeVariables[LS].push_back(Var);
1365//  Vars.push_back(Var);
1366}
1367
1368/// endFunction - Gather and emit post-function debug information.
1369///
1370void DwarfDebug::endFunction(const MachineFunction *MF) {
1371  if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1372
1373  // Define end label for subprogram.
1374  FunctionEndSym = Asm->GetTempSymbol("func_end",
1375                                      Asm->getFunctionNumber());
1376  // Assumes in correct section after the entry point.
1377  Asm->OutStreamer.EmitLabel(FunctionEndSym);
1378
1379  SmallPtrSet<const MDNode *, 16> ProcessedVars;
1380  collectVariableInfo(MF, ProcessedVars);
1381
1382  LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1383  CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1384  assert(TheCU && "Unable to find compile unit!");
1385
1386  // Construct abstract scopes.
1387  ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1388  for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1389    LexicalScope *AScope = AList[i];
1390    DISubprogram SP(AScope->getScopeNode());
1391    if (SP.Verify()) {
1392      // Collect info for variables that were optimized out.
1393      DIArray Variables = SP.getVariables();
1394      for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1395        DIVariable DV(Variables.getElement(i));
1396        if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1397          continue;
1398        if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1399          addScopeVariable(Scope, new DbgVariable(DV, NULL));
1400      }
1401    }
1402    if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1403      constructScopeDIE(TheCU, AScope);
1404  }
1405
1406  DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1407
1408  if (!DisableFramePointerElim(*MF))
1409    TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1410                   dwarf::DW_FORM_flag, 1);
1411
1412  DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1413                                               MMI->getFrameMoves()));
1414
1415  // Clear debug info
1416  for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1417         I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1418    DeleteContainerPointers(I->second);
1419  ScopeVariables.clear();
1420  DeleteContainerPointers(CurrentFnArguments);
1421  UserVariables.clear();
1422  DbgValues.clear();
1423  AbstractVariables.clear();
1424  LabelsBeforeInsn.clear();
1425  LabelsAfterInsn.clear();
1426  PrevLabel = NULL;
1427}
1428
1429/// recordSourceLine - Register a source line with debug info. Returns the
1430/// unique label that was emitted and which provides correspondence to
1431/// the source line list.
1432void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1433                                  unsigned Flags) {
1434  StringRef Fn;
1435  StringRef Dir;
1436  unsigned Src = 1;
1437  if (S) {
1438    DIDescriptor Scope(S);
1439
1440    if (Scope.isCompileUnit()) {
1441      DICompileUnit CU(S);
1442      Fn = CU.getFilename();
1443      Dir = CU.getDirectory();
1444    } else if (Scope.isFile()) {
1445      DIFile F(S);
1446      Fn = F.getFilename();
1447      Dir = F.getDirectory();
1448    } else if (Scope.isSubprogram()) {
1449      DISubprogram SP(S);
1450      Fn = SP.getFilename();
1451      Dir = SP.getDirectory();
1452    } else if (Scope.isLexicalBlockFile()) {
1453      DILexicalBlockFile DBF(S);
1454      Fn = DBF.getFilename();
1455      Dir = DBF.getDirectory();
1456    } else if (Scope.isLexicalBlock()) {
1457      DILexicalBlock DB(S);
1458      Fn = DB.getFilename();
1459      Dir = DB.getDirectory();
1460    } else
1461      assert(0 && "Unexpected scope info");
1462
1463    Src = GetOrCreateSourceID(Fn, Dir);
1464  }
1465  Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1466}
1467
1468//===----------------------------------------------------------------------===//
1469// Emit Methods
1470//===----------------------------------------------------------------------===//
1471
1472/// computeSizeAndOffset - Compute the size and offset of a DIE.
1473///
1474unsigned
1475DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1476  // Get the children.
1477  const std::vector<DIE *> &Children = Die->getChildren();
1478
1479  // If not last sibling and has children then add sibling offset attribute.
1480  if (!Last && !Children.empty())
1481    Die->addSiblingOffset(DIEValueAllocator);
1482
1483  // Record the abbreviation.
1484  assignAbbrevNumber(Die->getAbbrev());
1485
1486  // Get the abbreviation for this DIE.
1487  unsigned AbbrevNumber = Die->getAbbrevNumber();
1488  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1489
1490  // Set DIE offset
1491  Die->setOffset(Offset);
1492
1493  // Start the size with the size of abbreviation code.
1494  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1495
1496  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1497  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1498
1499  // Size the DIE attribute values.
1500  for (unsigned i = 0, N = Values.size(); i < N; ++i)
1501    // Size attribute value.
1502    Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1503
1504  // Size the DIE children if any.
1505  if (!Children.empty()) {
1506    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1507           "Children flag not set");
1508
1509    for (unsigned j = 0, M = Children.size(); j < M; ++j)
1510      Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1511
1512    // End of children marker.
1513    Offset += sizeof(int8_t);
1514  }
1515
1516  Die->setSize(Offset - Die->getOffset());
1517  return Offset;
1518}
1519
1520/// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1521///
1522void DwarfDebug::computeSizeAndOffsets() {
1523  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1524         E = CUMap.end(); I != E; ++I) {
1525    // Compute size of compile unit header.
1526    unsigned Offset =
1527      sizeof(int32_t) + // Length of Compilation Unit Info
1528      sizeof(int16_t) + // DWARF version number
1529      sizeof(int32_t) + // Offset Into Abbrev. Section
1530      sizeof(int8_t);   // Pointer Size (in bytes)
1531    computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1532  }
1533}
1534
1535/// EmitSectionLabels - Emit initial Dwarf sections with a label at
1536/// the start of each one.
1537void DwarfDebug::EmitSectionLabels() {
1538  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1539
1540  // Dwarf sections base addresses.
1541  DwarfInfoSectionSym =
1542    EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1543  DwarfAbbrevSectionSym =
1544    EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1545  EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1546
1547  if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1548    EmitSectionSym(Asm, MacroInfo);
1549
1550  EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1551  EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1552  EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1553  EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1554  DwarfStrSectionSym =
1555    EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1556  DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1557                                             "debug_range");
1558
1559  DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1560                                           "section_debug_loc");
1561
1562  TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1563  EmitSectionSym(Asm, TLOF.getDataSection());
1564}
1565
1566/// emitDIE - Recursively emits a debug information entry.
1567///
1568void DwarfDebug::emitDIE(DIE *Die) {
1569  // Get the abbreviation for this DIE.
1570  unsigned AbbrevNumber = Die->getAbbrevNumber();
1571  const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1572
1573  // Emit the code (index) for the abbreviation.
1574  if (Asm->isVerbose())
1575    Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1576                                Twine::utohexstr(Die->getOffset()) + ":0x" +
1577                                Twine::utohexstr(Die->getSize()) + " " +
1578                                dwarf::TagString(Abbrev->getTag()));
1579  Asm->EmitULEB128(AbbrevNumber);
1580
1581  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1582  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1583
1584  // Emit the DIE attribute values.
1585  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1586    unsigned Attr = AbbrevData[i].getAttribute();
1587    unsigned Form = AbbrevData[i].getForm();
1588    assert(Form && "Too many attributes for DIE (check abbreviation)");
1589
1590    if (Asm->isVerbose())
1591      Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1592
1593    switch (Attr) {
1594    case dwarf::DW_AT_sibling:
1595      Asm->EmitInt32(Die->getSiblingOffset());
1596      break;
1597    case dwarf::DW_AT_abstract_origin: {
1598      DIEEntry *E = cast<DIEEntry>(Values[i]);
1599      DIE *Origin = E->getEntry();
1600      unsigned Addr = Origin->getOffset();
1601      Asm->EmitInt32(Addr);
1602      break;
1603    }
1604    case dwarf::DW_AT_ranges: {
1605      // DW_AT_range Value encodes offset in debug_range section.
1606      DIEInteger *V = cast<DIEInteger>(Values[i]);
1607
1608      if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1609        Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1610                                 V->getValue(),
1611                                 4);
1612      } else {
1613        Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1614                                       V->getValue(),
1615                                       DwarfDebugRangeSectionSym,
1616                                       4);
1617      }
1618      break;
1619    }
1620    case dwarf::DW_AT_location: {
1621      if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1622        Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1623      else
1624        Values[i]->EmitValue(Asm, Form);
1625      break;
1626    }
1627    case dwarf::DW_AT_accessibility: {
1628      if (Asm->isVerbose()) {
1629        DIEInteger *V = cast<DIEInteger>(Values[i]);
1630        Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1631      }
1632      Values[i]->EmitValue(Asm, Form);
1633      break;
1634    }
1635    default:
1636      // Emit an attribute using the defined form.
1637      Values[i]->EmitValue(Asm, Form);
1638      break;
1639    }
1640  }
1641
1642  // Emit the DIE children if any.
1643  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1644    const std::vector<DIE *> &Children = Die->getChildren();
1645
1646    for (unsigned j = 0, M = Children.size(); j < M; ++j)
1647      emitDIE(Children[j]);
1648
1649    if (Asm->isVerbose())
1650      Asm->OutStreamer.AddComment("End Of Children Mark");
1651    Asm->EmitInt8(0);
1652  }
1653}
1654
1655/// emitDebugInfo - Emit the debug info section.
1656///
1657void DwarfDebug::emitDebugInfo() {
1658  // Start debug info section.
1659  Asm->OutStreamer.SwitchSection(
1660                            Asm->getObjFileLowering().getDwarfInfoSection());
1661  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1662         E = CUMap.end(); I != E; ++I) {
1663    CompileUnit *TheCU = I->second;
1664    DIE *Die = TheCU->getCUDie();
1665
1666    // Emit the compile units header.
1667    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1668                                                  TheCU->getID()));
1669
1670    // Emit size of content not including length itself
1671    unsigned ContentSize = Die->getSize() +
1672      sizeof(int16_t) + // DWARF version number
1673      sizeof(int32_t) + // Offset Into Abbrev. Section
1674      sizeof(int8_t);   // Pointer Size (in bytes)
1675
1676    Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1677    Asm->EmitInt32(ContentSize);
1678    Asm->OutStreamer.AddComment("DWARF version number");
1679    Asm->EmitInt16(dwarf::DWARF_VERSION);
1680    Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1681    Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1682                           DwarfAbbrevSectionSym);
1683    Asm->OutStreamer.AddComment("Address Size (in bytes)");
1684    Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1685
1686    emitDIE(Die);
1687    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1688  }
1689}
1690
1691/// emitAbbreviations - Emit the abbreviation section.
1692///
1693void DwarfDebug::emitAbbreviations() const {
1694  // Check to see if it is worth the effort.
1695  if (!Abbreviations.empty()) {
1696    // Start the debug abbrev section.
1697    Asm->OutStreamer.SwitchSection(
1698                            Asm->getObjFileLowering().getDwarfAbbrevSection());
1699
1700    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1701
1702    // For each abbrevation.
1703    for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1704      // Get abbreviation data
1705      const DIEAbbrev *Abbrev = Abbreviations[i];
1706
1707      // Emit the abbrevations code (base 1 index.)
1708      Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1709
1710      // Emit the abbreviations data.
1711      Abbrev->Emit(Asm);
1712    }
1713
1714    // Mark end of abbreviations.
1715    Asm->EmitULEB128(0, "EOM(3)");
1716
1717    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1718  }
1719}
1720
1721/// emitEndOfLineMatrix - Emit the last address of the section and the end of
1722/// the line matrix.
1723///
1724void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1725  // Define last address of section.
1726  Asm->OutStreamer.AddComment("Extended Op");
1727  Asm->EmitInt8(0);
1728
1729  Asm->OutStreamer.AddComment("Op size");
1730  Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1731  Asm->OutStreamer.AddComment("DW_LNE_set_address");
1732  Asm->EmitInt8(dwarf::DW_LNE_set_address);
1733
1734  Asm->OutStreamer.AddComment("Section end label");
1735
1736  Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1737                                   Asm->getTargetData().getPointerSize(),
1738                                   0/*AddrSpace*/);
1739
1740  // Mark end of matrix.
1741  Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1742  Asm->EmitInt8(0);
1743  Asm->EmitInt8(1);
1744  Asm->EmitInt8(1);
1745}
1746
1747/// emitAccelNames - Emit visible names into a hashed accelerator table
1748/// section.
1749void DwarfDebug::emitAccelNames() {
1750  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1751                                           dwarf::DW_FORM_data4));
1752  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1753         E = CUMap.end(); I != E; ++I) {
1754    CompileUnit *TheCU = I->second;
1755    const StringMap<DIE*> &Names = TheCU->getAccelNames();
1756    for (StringMap<DIE*>::const_iterator
1757           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1758      const char *Name = GI->getKeyData();
1759      DIE *Entity = GI->second;
1760      AT.AddName(Name, Entity);
1761    }
1762  }
1763
1764  AT.FinalizeTable(Asm, "Names");
1765  Asm->OutStreamer.SwitchSection(
1766    Asm->getObjFileLowering().getDwarfAccelNamesSection());
1767  MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1768  Asm->OutStreamer.EmitLabel(SectionBegin);
1769
1770  // Emit the full data.
1771  AT.Emit(Asm, SectionBegin, this);
1772}
1773
1774/// emitAccelObjC - Emit objective C classes and categories into a hashed
1775/// accelerator table section.
1776void DwarfDebug::emitAccelObjC() {
1777  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1778                                           dwarf::DW_FORM_data4));
1779  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1780         E = CUMap.end(); I != E; ++I) {
1781    CompileUnit *TheCU = I->second;
1782    const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1783    for (StringMap<std::vector<DIE*> >::const_iterator
1784           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1785      const char *Name = GI->getKeyData();
1786      std::vector<DIE *> Entities = GI->second;
1787      for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1788             DE = Entities.end(); DI != DE; ++DI)
1789        AT.AddName(Name, (*DI));
1790    }
1791  }
1792
1793  AT.FinalizeTable(Asm, "ObjC");
1794  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1795                                 .getDwarfAccelObjCSection());
1796  MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1797  Asm->OutStreamer.EmitLabel(SectionBegin);
1798
1799  // Emit the full data.
1800  AT.Emit(Asm, SectionBegin, this);
1801}
1802
1803/// emitAccelNamespace - Emit namespace dies into a hashed accelerator
1804/// table.
1805void DwarfDebug::emitAccelNamespaces() {
1806  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1807                                           dwarf::DW_FORM_data4));
1808  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1809         E = CUMap.end(); I != E; ++I) {
1810    CompileUnit *TheCU = I->second;
1811    const StringMap<DIE*> &Names = TheCU->getAccelNamespace();
1812    for (StringMap<DIE*>::const_iterator
1813           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1814      const char *Name = GI->getKeyData();
1815      DIE *Entity = GI->second;
1816      AT.AddName(Name, Entity);
1817    }
1818  }
1819
1820  AT.FinalizeTable(Asm, "namespac");
1821  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1822                                 .getDwarfAccelNamespaceSection());
1823  MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1824  Asm->OutStreamer.EmitLabel(SectionBegin);
1825
1826  // Emit the full data.
1827  AT.Emit(Asm, SectionBegin, this);
1828}
1829
1830/// emitAccelTypes() - Emit type dies into a hashed accelerator table.
1831void DwarfDebug::emitAccelTypes() {
1832  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1833                                           dwarf::DW_FORM_data4));
1834  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1835         E = CUMap.end(); I != E; ++I) {
1836    CompileUnit *TheCU = I->second;
1837    const StringMap<DIE*> &Names = TheCU->getAccelTypes();
1838    for (StringMap<DIE*>::const_iterator
1839           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1840      const char *Name = GI->getKeyData();
1841      DIE *Entity = GI->second;
1842      AT.AddName(Name, Entity);
1843    }
1844  }
1845
1846  AT.FinalizeTable(Asm, "types");
1847  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1848                                 .getDwarfAccelTypesSection());
1849  MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1850  Asm->OutStreamer.EmitLabel(SectionBegin);
1851
1852  // Emit the full data.
1853  AT.Emit(Asm, SectionBegin, this);
1854}
1855
1856/// emitDebugPubNames - Emit visible names into a debug pubnames section.
1857///
1858void DwarfDebug::emitDebugPubNames() {
1859  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1860         E = CUMap.end(); I != E; ++I) {
1861    CompileUnit *TheCU = I->second;
1862    // Start the dwarf pubnames section.
1863    Asm->OutStreamer.SwitchSection(
1864      Asm->getObjFileLowering().getDwarfPubNamesSection());
1865
1866    Asm->OutStreamer.AddComment("Length of Public Names Info");
1867    Asm->EmitLabelDifference(
1868      Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1869      Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1870
1871    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1872                                                  TheCU->getID()));
1873
1874    Asm->OutStreamer.AddComment("DWARF Version");
1875    Asm->EmitInt16(dwarf::DWARF_VERSION);
1876
1877    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1878    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1879                           DwarfInfoSectionSym);
1880
1881    Asm->OutStreamer.AddComment("Compilation Unit Length");
1882    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1883                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
1884                             4);
1885
1886    const StringMap<DIE*> &Globals = TheCU->getGlobals();
1887    for (StringMap<DIE*>::const_iterator
1888           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1889      const char *Name = GI->getKeyData();
1890      DIE *Entity = GI->second;
1891
1892      Asm->OutStreamer.AddComment("DIE offset");
1893      Asm->EmitInt32(Entity->getOffset());
1894
1895      if (Asm->isVerbose())
1896        Asm->OutStreamer.AddComment("External Name");
1897      Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1898    }
1899
1900    Asm->OutStreamer.AddComment("End Mark");
1901    Asm->EmitInt32(0);
1902    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1903                                                  TheCU->getID()));
1904  }
1905}
1906
1907void DwarfDebug::emitDebugPubTypes() {
1908  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1909         E = CUMap.end(); I != E; ++I) {
1910    CompileUnit *TheCU = I->second;
1911    // Start the dwarf pubtypes section.
1912    Asm->OutStreamer.SwitchSection(
1913      Asm->getObjFileLowering().getDwarfPubTypesSection());
1914    Asm->OutStreamer.AddComment("Length of Public Types Info");
1915    Asm->EmitLabelDifference(
1916      Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1917      Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1918
1919    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1920                                                  TheCU->getID()));
1921
1922    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1923    Asm->EmitInt16(dwarf::DWARF_VERSION);
1924
1925    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1926    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1927                           DwarfInfoSectionSym);
1928
1929    Asm->OutStreamer.AddComment("Compilation Unit Length");
1930    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1931                             Asm->GetTempSymbol("info_begin", TheCU->getID()),
1932                             4);
1933
1934    const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1935    for (StringMap<DIE*>::const_iterator
1936           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1937      const char *Name = GI->getKeyData();
1938      DIE *Entity = GI->second;
1939
1940      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1941      Asm->EmitInt32(Entity->getOffset());
1942
1943      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1944      Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1945    }
1946
1947    Asm->OutStreamer.AddComment("End Mark");
1948    Asm->EmitInt32(0);
1949    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1950                                                  TheCU->getID()));
1951  }
1952}
1953
1954/// emitDebugStr - Emit visible names into a debug str section.
1955///
1956void DwarfDebug::emitDebugStr() {
1957  // Check to see if it is worth the effort.
1958  if (StringPool.empty()) return;
1959
1960  // Start the dwarf str section.
1961  Asm->OutStreamer.SwitchSection(
1962                                Asm->getObjFileLowering().getDwarfStrSection());
1963
1964  // Get all of the string pool entries and put them in an array by their ID so
1965  // we can sort them.
1966  SmallVector<std::pair<unsigned,
1967      StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1968
1969  for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1970       I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1971    Entries.push_back(std::make_pair(I->second.second, &*I));
1972
1973  array_pod_sort(Entries.begin(), Entries.end());
1974
1975  for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1976    // Emit a label for reference from debug information entries.
1977    Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1978
1979    // Emit the string itself.
1980    Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1981    Asm->OutStreamer.EmitZeros(1, 0);
1982  }
1983}
1984
1985/// emitDebugLoc - Emit visible names into a debug loc section.
1986///
1987void DwarfDebug::emitDebugLoc() {
1988  if (DotDebugLocEntries.empty())
1989    return;
1990
1991  for (SmallVector<DotDebugLocEntry, 4>::iterator
1992         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1993       I != E; ++I) {
1994    DotDebugLocEntry &Entry = *I;
1995    if (I + 1 != DotDebugLocEntries.end())
1996      Entry.Merge(I+1);
1997  }
1998
1999  // Start the dwarf loc section.
2000  Asm->OutStreamer.SwitchSection(
2001    Asm->getObjFileLowering().getDwarfLocSection());
2002  unsigned char Size = Asm->getTargetData().getPointerSize();
2003  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2004  unsigned index = 1;
2005  for (SmallVector<DotDebugLocEntry, 4>::iterator
2006         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2007       I != E; ++I, ++index) {
2008    DotDebugLocEntry &Entry = *I;
2009    if (Entry.isMerged()) continue;
2010    if (Entry.isEmpty()) {
2011      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2012      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2013      Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2014    } else {
2015      Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2016      Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2017      DIVariable DV(Entry.Variable);
2018      Asm->OutStreamer.AddComment("Loc expr size");
2019      MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2020      MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2021      Asm->EmitLabelDifference(end, begin, 2);
2022      Asm->OutStreamer.EmitLabel(begin);
2023      if (Entry.isInt()) {
2024        DIBasicType BTy(DV.getType());
2025        if (BTy.Verify() &&
2026            (BTy.getEncoding()  == dwarf::DW_ATE_signed
2027             || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2028          Asm->OutStreamer.AddComment("DW_OP_consts");
2029          Asm->EmitInt8(dwarf::DW_OP_consts);
2030          Asm->EmitSLEB128(Entry.getInt());
2031        } else {
2032          Asm->OutStreamer.AddComment("DW_OP_constu");
2033          Asm->EmitInt8(dwarf::DW_OP_constu);
2034          Asm->EmitULEB128(Entry.getInt());
2035        }
2036      } else if (Entry.isLocation()) {
2037        if (!DV.hasComplexAddress())
2038          // Regular entry.
2039          Asm->EmitDwarfRegOp(Entry.Loc);
2040        else {
2041          // Complex address entry.
2042          unsigned N = DV.getNumAddrElements();
2043          unsigned i = 0;
2044          if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2045            if (Entry.Loc.getOffset()) {
2046              i = 2;
2047              Asm->EmitDwarfRegOp(Entry.Loc);
2048              Asm->OutStreamer.AddComment("DW_OP_deref");
2049              Asm->EmitInt8(dwarf::DW_OP_deref);
2050              Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2051              Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2052              Asm->EmitSLEB128(DV.getAddrElement(1));
2053            } else {
2054              // If first address element is OpPlus then emit
2055              // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2056              MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2057              Asm->EmitDwarfRegOp(Loc);
2058              i = 2;
2059            }
2060          } else {
2061            Asm->EmitDwarfRegOp(Entry.Loc);
2062          }
2063
2064          // Emit remaining complex address elements.
2065          for (; i < N; ++i) {
2066            uint64_t Element = DV.getAddrElement(i);
2067            if (Element == DIBuilder::OpPlus) {
2068              Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2069              Asm->EmitULEB128(DV.getAddrElement(++i));
2070            } else if (Element == DIBuilder::OpDeref)
2071              Asm->EmitInt8(dwarf::DW_OP_deref);
2072            else llvm_unreachable("unknown Opcode found in complex address");
2073          }
2074        }
2075      }
2076      // else ... ignore constant fp. There is not any good way to
2077      // to represent them here in dwarf.
2078      Asm->OutStreamer.EmitLabel(end);
2079    }
2080  }
2081}
2082
2083/// EmitDebugARanges - Emit visible names into a debug aranges section.
2084///
2085void DwarfDebug::EmitDebugARanges() {
2086  // Start the dwarf aranges section.
2087  Asm->OutStreamer.SwitchSection(
2088                          Asm->getObjFileLowering().getDwarfARangesSection());
2089}
2090
2091/// emitDebugRanges - Emit visible names into a debug ranges section.
2092///
2093void DwarfDebug::emitDebugRanges() {
2094  // Start the dwarf ranges section.
2095  Asm->OutStreamer.SwitchSection(
2096    Asm->getObjFileLowering().getDwarfRangesSection());
2097  unsigned char Size = Asm->getTargetData().getPointerSize();
2098  for (SmallVector<const MCSymbol *, 8>::iterator
2099         I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2100       I != E; ++I) {
2101    if (*I)
2102      Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2103    else
2104      Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2105  }
2106}
2107
2108/// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2109///
2110void DwarfDebug::emitDebugMacInfo() {
2111  if (const MCSection *LineInfo =
2112      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2113    // Start the dwarf macinfo section.
2114    Asm->OutStreamer.SwitchSection(LineInfo);
2115  }
2116}
2117
2118/// emitDebugInlineInfo - Emit inline info using following format.
2119/// Section Header:
2120/// 1. length of section
2121/// 2. Dwarf version number
2122/// 3. address size.
2123///
2124/// Entries (one "entry" for each function that was inlined):
2125///
2126/// 1. offset into __debug_str section for MIPS linkage name, if exists;
2127///   otherwise offset into __debug_str for regular function name.
2128/// 2. offset into __debug_str section for regular function name.
2129/// 3. an unsigned LEB128 number indicating the number of distinct inlining
2130/// instances for the function.
2131///
2132/// The rest of the entry consists of a {die_offset, low_pc} pair for each
2133/// inlined instance; the die_offset points to the inlined_subroutine die in the
2134/// __debug_info section, and the low_pc is the starting address for the
2135/// inlining instance.
2136void DwarfDebug::emitDebugInlineInfo() {
2137  if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2138    return;
2139
2140  if (!FirstCU)
2141    return;
2142
2143  Asm->OutStreamer.SwitchSection(
2144                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
2145
2146  Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2147  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2148                           Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2149
2150  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2151
2152  Asm->OutStreamer.AddComment("Dwarf Version");
2153  Asm->EmitInt16(dwarf::DWARF_VERSION);
2154  Asm->OutStreamer.AddComment("Address Size (in bytes)");
2155  Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2156
2157  for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2158         E = InlinedSPNodes.end(); I != E; ++I) {
2159
2160    const MDNode *Node = *I;
2161    DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2162      = InlineInfo.find(Node);
2163    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2164    DISubprogram SP(Node);
2165    StringRef LName = SP.getLinkageName();
2166    StringRef Name = SP.getName();
2167
2168    Asm->OutStreamer.AddComment("MIPS linkage name");
2169    if (LName.empty()) {
2170      Asm->OutStreamer.EmitBytes(Name, 0);
2171      Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2172    } else
2173      Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2174                             DwarfStrSectionSym);
2175
2176    Asm->OutStreamer.AddComment("Function name");
2177    Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2178    Asm->EmitULEB128(Labels.size(), "Inline count");
2179
2180    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2181           LE = Labels.end(); LI != LE; ++LI) {
2182      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2183      Asm->EmitInt32(LI->second->getOffset());
2184
2185      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2186      Asm->OutStreamer.EmitSymbolValue(LI->first,
2187                                       Asm->getTargetData().getPointerSize(),0);
2188    }
2189  }
2190
2191  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2192}
2193