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