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