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