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