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