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