Add '*' to auto variable that is a pointer, as per the coding conventions.
[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 #include "DwarfDebug.h"
15
16 #include "ByteStreamer.h"
17 #include "DwarfCompileUnit.h"
18 #include "DIE.h"
19 #include "DIEHash.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MD5.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
54 using namespace llvm;
55
56 #define DEBUG_TYPE "dwarfdebug"
57
58 static cl::opt<bool>
59 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
60                          cl::desc("Disable debug info printing"));
61
62 static cl::opt<bool> UnknownLocations(
63     "use-unknown-locations", cl::Hidden,
64     cl::desc("Make an absence of debug location information explicit."),
65     cl::init(false));
66
67 static cl::opt<bool>
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69                        cl::desc("Generate GNU-style pubnames and pubtypes"),
70                        cl::init(false));
71
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
73                                            cl::Hidden,
74                                            cl::desc("Generate dwarf aranges"),
75                                            cl::init(false));
76
77 namespace {
78 enum DefaultOnOff { Default, Enable, Disable };
79 }
80
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83                  cl::desc("Output prototype dwarf accelerator tables."),
84                  cl::values(clEnumVal(Default, "Default for platform"),
85                             clEnumVal(Enable, "Enabled"),
86                             clEnumVal(Disable, "Disabled"), clEnumValEnd),
87                  cl::init(Default));
88
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91            cl::desc("Output DWARF5 split debug info."),
92            cl::values(clEnumVal(Default, "Default for platform"),
93                       clEnumVal(Enable, "Enabled"),
94                       clEnumVal(Disable, "Disabled"), clEnumValEnd),
95            cl::init(Default));
96
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99                  cl::desc("Generate DWARF pubnames and pubtypes sections"),
100                  cl::values(clEnumVal(Default, "Default for platform"),
101                             clEnumVal(Enable, "Enabled"),
102                             clEnumVal(Disable, "Disabled"), clEnumValEnd),
103                  cl::init(Default));
104
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
107
108 //===----------------------------------------------------------------------===//
109
110 /// resolve - Look in the DwarfDebug map for the MDNode that
111 /// corresponds to the reference.
112 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
113   return DD->resolve(Ref);
114 }
115
116 bool DbgVariable::isBlockByrefVariable() const {
117   assert(Var.isVariable() && "Invalid complex DbgVariable!");
118   return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
119 }
120
121 DIType DbgVariable::getType() const {
122   DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
123   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
124   // addresses instead.
125   if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
126     /* Byref variables, in Blocks, are declared by the programmer as
127        "SomeType VarName;", but the compiler creates a
128        __Block_byref_x_VarName struct, and gives the variable VarName
129        either the struct, or a pointer to the struct, as its type.  This
130        is necessary for various behind-the-scenes things the compiler
131        needs to do with by-reference variables in blocks.
132
133        However, as far as the original *programmer* is concerned, the
134        variable should still have type 'SomeType', as originally declared.
135
136        The following function dives into the __Block_byref_x_VarName
137        struct to find the original type of the variable.  This will be
138        passed back to the code generating the type for the Debug
139        Information Entry for the variable 'VarName'.  'VarName' will then
140        have the original type 'SomeType' in its debug information.
141
142        The original type 'SomeType' will be the type of the field named
143        'VarName' inside the __Block_byref_x_VarName struct.
144
145        NOTE: In order for this to not completely fail on the debugger
146        side, the Debug Information Entry for the variable VarName needs to
147        have a DW_AT_location that tells the debugger how to unwind through
148        the pointers and __Block_byref_x_VarName struct to find the actual
149        value of the variable.  The function addBlockByrefType does this.  */
150     DIType subType = Ty;
151     uint16_t tag = Ty.getTag();
152
153     if (tag == dwarf::DW_TAG_pointer_type)
154       subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
155
156     DIArray Elements = DICompositeType(subType).getElements();
157     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
158       DIDerivedType DT(Elements.getElement(i));
159       if (getName() == DT.getName())
160         return (resolve(DT.getTypeDerivedFrom()));
161     }
162   }
163   return Ty;
164 }
165
166 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
167     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
168     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
169     DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
170
171 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
172     : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr), GlobalRangeCount(0),
173       InfoHolder(A, *this, "info_string", DIEValueAllocator),
174       UsedNonDefaultText(false),
175       SkeletonHolder(A, *this, "skel_string", DIEValueAllocator),
176       IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
177       AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
178                                        dwarf::DW_FORM_data4)),
179       AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
180                                       dwarf::DW_FORM_data4)),
181       AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
182                                            dwarf::DW_FORM_data4)),
183       AccelTypes(TypeAtoms) {
184
185   DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
186   DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
187   DwarfLineSectionSym = nullptr;
188   DwarfAddrSectionSym = nullptr;
189   DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
190   FunctionBeginSym = FunctionEndSym = nullptr;
191   CurFn = nullptr;
192   CurMI = nullptr;
193
194   // Turn on accelerator tables for Darwin by default, pubnames by
195   // default for non-Darwin, and handle split dwarf.
196   if (DwarfAccelTables == Default)
197     HasDwarfAccelTables = IsDarwin;
198   else
199     HasDwarfAccelTables = DwarfAccelTables == Enable;
200
201   if (SplitDwarf == Default)
202     HasSplitDwarf = false;
203   else
204     HasSplitDwarf = SplitDwarf == Enable;
205
206   if (DwarfPubSections == Default)
207     HasDwarfPubSections = !IsDarwin;
208   else
209     HasDwarfPubSections = DwarfPubSections == Enable;
210
211   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
212   DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213                                     : MMI->getModule()->getDwarfVersion();
214
215   Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
216
217   {
218     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
219     beginModule();
220   }
221 }
222
223 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
224 DwarfDebug::~DwarfDebug() { }
225
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229                                 const char *SymbolStem = nullptr) {
230   Asm->OutStreamer.SwitchSection(Section);
231   if (!SymbolStem)
232     return nullptr;
233
234   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235   Asm->OutStreamer.EmitLabel(TmpSym);
236   return TmpSym;
237 }
238
239 static bool isObjCClass(StringRef Name) {
240   return Name.startswith("+") || Name.startswith("-");
241 }
242
243 static bool hasObjCCategory(StringRef Name) {
244   if (!isObjCClass(Name))
245     return false;
246
247   return Name.find(") ") != StringRef::npos;
248 }
249
250 static void getObjCClassCategory(StringRef In, StringRef &Class,
251                                  StringRef &Category) {
252   if (!hasObjCCategory(In)) {
253     Class = In.slice(In.find('[') + 1, In.find(' '));
254     Category = "";
255     return;
256   }
257
258   Class = In.slice(In.find('[') + 1, In.find('('));
259   Category = In.slice(In.find('[') + 1, In.find(' '));
260   return;
261 }
262
263 static StringRef getObjCMethodName(StringRef In) {
264   return In.slice(In.find(' ') + 1, In.find(']'));
265 }
266
267 // Helper for sorting sections into a stable output order.
268 static bool SectionSort(const MCSection *A, const MCSection *B) {
269   std::string LA = (A ? A->getLabelBeginName() : "");
270   std::string LB = (B ? B->getLabelBeginName() : "");
271   return LA < LB;
272 }
273
274 // Add the various names to the Dwarf accelerator table names.
275 // TODO: Determine whether or not we should add names for programs
276 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
277 // is only slightly different than the lookup of non-standard ObjC names.
278 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
279   if (!SP.isDefinition())
280     return;
281   addAccelName(SP.getName(), Die);
282
283   // If the linkage name is different than the name, go ahead and output
284   // that as well into the name table.
285   if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
286     addAccelName(SP.getLinkageName(), Die);
287
288   // If this is an Objective-C selector name add it to the ObjC accelerator
289   // too.
290   if (isObjCClass(SP.getName())) {
291     StringRef Class, Category;
292     getObjCClassCategory(SP.getName(), Class, Category);
293     addAccelObjC(Class, Die);
294     if (Category != "")
295       addAccelObjC(Category, Die);
296     // Also add the base method name to the name table.
297     addAccelName(getObjCMethodName(SP.getName()), Die);
298   }
299 }
300
301 /// isSubprogramContext - Return true if Context is either a subprogram
302 /// or another context nested inside a subprogram.
303 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
304   if (!Context)
305     return false;
306   DIDescriptor D(Context);
307   if (D.isSubprogram())
308     return true;
309   if (D.isType())
310     return isSubprogramContext(resolve(DIType(Context).getContext()));
311   return false;
312 }
313
314 /// Check whether we should create a DIE for the given Scope, return true
315 /// if we don't create a DIE (the corresponding DIE is null).
316 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
317   if (Scope->isAbstractScope())
318     return false;
319
320   // We don't create a DIE if there is no Range.
321   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
322   if (Ranges.empty())
323     return true;
324
325   if (Ranges.size() > 1)
326     return false;
327
328   // We don't create a DIE if we have a single Range and the end label
329   // is null.
330   return !getLabelAfterInsn(Ranges.front().second);
331 }
332
333 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
334   assert(Scope && Scope->getScopeNode());
335   assert(Scope->isAbstractScope());
336   assert(!Scope->getInlinedAt());
337
338   const MDNode *SP = Scope->getScopeNode();
339
340   ProcessedSPNodes.insert(SP);
341
342   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
343   // was inlined from another compile unit.
344   SPMap[SP]->constructAbstractSubprogramScopeDIE(Scope);
345 }
346
347 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
348   if (!GenerateGnuPubSections)
349     return;
350
351   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
352 }
353
354 // Create new DwarfCompileUnit for the given metadata node with tag
355 // DW_TAG_compile_unit.
356 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
357   StringRef FN = DIUnit.getFilename();
358   CompilationDir = DIUnit.getDirectory();
359
360   auto OwnedUnit = make_unique<DwarfCompileUnit>(
361       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
362   DwarfCompileUnit &NewCU = *OwnedUnit;
363   DIE &Die = NewCU.getUnitDie();
364   InfoHolder.addUnit(std::move(OwnedUnit));
365
366   // LTO with assembly output shares a single line table amongst multiple CUs.
367   // To avoid the compilation directory being ambiguous, let the line table
368   // explicitly describe the directory of all files, never relying on the
369   // compilation directory.
370   if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
371     Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
372         NewCU.getUniqueID(), CompilationDir);
373
374   NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
375   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
376                 DIUnit.getLanguage());
377   NewCU.addString(Die, dwarf::DW_AT_name, FN);
378
379   if (!useSplitDwarf()) {
380     NewCU.initStmtList(DwarfLineSectionSym);
381
382     // If we're using split dwarf the compilation dir is going to be in the
383     // skeleton CU and so we don't need to duplicate it here.
384     if (!CompilationDir.empty())
385       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
386
387     addGnuPubAttributes(NewCU, Die);
388   }
389
390   if (DIUnit.isOptimized())
391     NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
392
393   StringRef Flags = DIUnit.getFlags();
394   if (!Flags.empty())
395     NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
396
397   if (unsigned RVer = DIUnit.getRunTimeVersion())
398     NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
399                   dwarf::DW_FORM_data1, RVer);
400
401   if (useSplitDwarf()) {
402     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
403                       DwarfInfoDWOSectionSym);
404     NewCU.setSkeleton(constructSkeletonCU(NewCU));
405   } else
406     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
407                       DwarfInfoSectionSym);
408
409   CUMap.insert(std::make_pair(DIUnit, &NewCU));
410   CUDieMap.insert(std::make_pair(&Die, &NewCU));
411   return NewCU;
412 }
413
414 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
415                                                   const MDNode *N) {
416   DIImportedEntity Module(N);
417   assert(Module.Verify());
418   if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
419     D->addChild(TheCU.constructImportedEntityDIE(Module));
420 }
421
422 // Emit all Dwarf sections that should come prior to the content. Create
423 // global DIEs and emit initial debug info sections. This is invoked by
424 // the target AsmPrinter.
425 void DwarfDebug::beginModule() {
426   if (DisableDebugInfoPrinting)
427     return;
428
429   const Module *M = MMI->getModule();
430
431   FunctionDIs = makeSubprogramMap(*M);
432
433   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
434   if (!CU_Nodes)
435     return;
436   TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
437
438   // Emit initial sections so we can reference labels later.
439   emitSectionLabels();
440
441   SingleCU = CU_Nodes->getNumOperands() == 1;
442
443   for (MDNode *N : CU_Nodes->operands()) {
444     DICompileUnit CUNode(N);
445     DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
446     DIArray ImportedEntities = CUNode.getImportedEntities();
447     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
448       ScopesWithImportedEntities.push_back(std::make_pair(
449           DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
450           ImportedEntities.getElement(i)));
451     std::sort(ScopesWithImportedEntities.begin(),
452               ScopesWithImportedEntities.end(), less_first());
453     DIArray GVs = CUNode.getGlobalVariables();
454     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
455       CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
456     DIArray SPs = CUNode.getSubprograms();
457     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
458       SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
459     DIArray EnumTypes = CUNode.getEnumTypes();
460     for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
461       DIType Ty(EnumTypes.getElement(i));
462       // The enum types array by design contains pointers to
463       // MDNodes rather than DIRefs. Unique them here.
464       DIType UniqueTy(resolve(Ty.getRef()));
465       CU.getOrCreateTypeDIE(UniqueTy);
466     }
467     DIArray RetainedTypes = CUNode.getRetainedTypes();
468     for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
469       DIType Ty(RetainedTypes.getElement(i));
470       // The retained types array by design contains pointers to
471       // MDNodes rather than DIRefs. Unique them here.
472       DIType UniqueTy(resolve(Ty.getRef()));
473       CU.getOrCreateTypeDIE(UniqueTy);
474     }
475     // Emit imported_modules last so that the relevant context is already
476     // available.
477     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
478       constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
479   }
480
481   // Tell MMI that we have debug info.
482   MMI->setDebugInfoAvailability(true);
483
484   // Prime section data.
485   SectionMap[Asm->getObjFileLowering().getTextSection()];
486 }
487
488 void DwarfDebug::finishVariableDefinitions() {
489   for (const auto &Var : ConcreteVariables) {
490     DIE *VariableDie = Var->getDIE();
491     assert(VariableDie);
492     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
493     // in the ConcreteVariables list, rather than looking it up again here.
494     // DIE::getUnit isn't simple - it walks parent pointers, etc.
495     DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
496     assert(Unit);
497     DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
498     if (AbsVar && AbsVar->getDIE()) {
499       Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
500                         *AbsVar->getDIE());
501     } else
502       Unit->applyVariableAttributes(*Var, *VariableDie);
503   }
504 }
505
506 void DwarfDebug::finishSubprogramDefinitions() {
507   for (const auto &P : SPMap)
508     P.second->finishSubprogramDefinition(DISubprogram(P.first));
509 }
510
511
512 // Collect info for variables that were optimized out.
513 void DwarfDebug::collectDeadVariables() {
514   const Module *M = MMI->getModule();
515
516   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
517     for (MDNode *N : CU_Nodes->operands()) {
518       DICompileUnit TheCU(N);
519       // Construct subprogram DIE and add variables DIEs.
520       DwarfCompileUnit *SPCU =
521           static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
522       assert(SPCU && "Unable to find Compile Unit!");
523       DIArray Subprograms = TheCU.getSubprograms();
524       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
525         DISubprogram SP(Subprograms.getElement(i));
526         if (ProcessedSPNodes.count(SP) != 0)
527           continue;
528         SPCU->collectDeadVariables(SP);
529       }
530     }
531   }
532 }
533
534 void DwarfDebug::finalizeModuleInfo() {
535   finishSubprogramDefinitions();
536
537   finishVariableDefinitions();
538
539   // Collect info for variables that were optimized out.
540   collectDeadVariables();
541
542   // Handle anything that needs to be done on a per-unit basis after
543   // all other generation.
544   for (const auto &TheU : getUnits()) {
545     // Emit DW_AT_containing_type attribute to connect types with their
546     // vtable holding type.
547     TheU->constructContainingTypeDIEs();
548
549     // Add CU specific attributes if we need to add any.
550     if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
551       // If we're splitting the dwarf out now that we've got the entire
552       // CU then add the dwo id to it.
553       DwarfCompileUnit *SkCU = TheU->getSkeleton();
554       if (useSplitDwarf()) {
555         // Emit a unique identifier for this CU.
556         uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
557         TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
558                       dwarf::DW_FORM_data8, ID);
559         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
560                       dwarf::DW_FORM_data8, ID);
561
562         // We don't keep track of which addresses are used in which CU so this
563         // is a bit pessimistic under LTO.
564         if (!AddrPool.isEmpty())
565           SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
566                                 DwarfAddrSectionSym, DwarfAddrSectionSym);
567         if (!TheU->getRangeLists().empty())
568           SkCU->addSectionLabel(
569               SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
570               DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
571       }
572
573       // If we have code split among multiple sections or non-contiguous
574       // ranges of code then emit a DW_AT_ranges attribute on the unit that will
575       // remain in the .o file, otherwise add a DW_AT_low_pc.
576       // FIXME: We should use ranges allow reordering of code ala
577       // .subsections_via_symbols in mach-o. This would mean turning on
578       // ranges for all subprogram DIEs for mach-o.
579       DwarfCompileUnit &U =
580           SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
581       unsigned NumRanges = TheU->getRanges().size();
582       if (NumRanges) {
583         if (NumRanges > 1) {
584           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
585                             Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
586                             DwarfDebugRangeSectionSym);
587
588           // A DW_AT_low_pc attribute may also be specified in combination with
589           // DW_AT_ranges to specify the default base address for use in
590           // location lists (see Section 2.6.2) and range lists (see Section
591           // 2.17.3).
592           U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
593                     0);
594         } else {
595           RangeSpan &Range = TheU->getRanges().back();
596           U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
597         }
598       }
599     }
600   }
601
602   // Compute DIE offsets and sizes.
603   InfoHolder.computeSizeAndOffsets();
604   if (useSplitDwarf())
605     SkeletonHolder.computeSizeAndOffsets();
606 }
607
608 void DwarfDebug::endSections() {
609   // Filter labels by section.
610   for (const SymbolCU &SCU : ArangeLabels) {
611     if (SCU.Sym->isInSection()) {
612       // Make a note of this symbol and it's section.
613       const MCSection *Section = &SCU.Sym->getSection();
614       if (!Section->getKind().isMetadata())
615         SectionMap[Section].push_back(SCU);
616     } else {
617       // Some symbols (e.g. common/bss on mach-o) can have no section but still
618       // appear in the output. This sucks as we rely on sections to build
619       // arange spans. We can do it without, but it's icky.
620       SectionMap[nullptr].push_back(SCU);
621     }
622   }
623
624   // Build a list of sections used.
625   std::vector<const MCSection *> Sections;
626   for (const auto &it : SectionMap) {
627     const MCSection *Section = it.first;
628     Sections.push_back(Section);
629   }
630
631   // Sort the sections into order.
632   // This is only done to ensure consistent output order across different runs.
633   std::sort(Sections.begin(), Sections.end(), SectionSort);
634
635   // Add terminating symbols for each section.
636   for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
637     const MCSection *Section = Sections[ID];
638     MCSymbol *Sym = nullptr;
639
640     if (Section) {
641       // We can't call MCSection::getLabelEndName, as it's only safe to do so
642       // if we know the section name up-front. For user-created sections, the
643       // resulting label may not be valid to use as a label. (section names can
644       // use a greater set of characters on some systems)
645       Sym = Asm->GetTempSymbol("debug_end", ID);
646       Asm->OutStreamer.SwitchSection(Section);
647       Asm->OutStreamer.EmitLabel(Sym);
648     }
649
650     // Insert a final terminator.
651     SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
652   }
653 }
654
655 // Emit all Dwarf sections that should come after the content.
656 void DwarfDebug::endModule() {
657   assert(CurFn == nullptr);
658   assert(CurMI == nullptr);
659
660   // If we aren't actually generating debug info (check beginModule -
661   // conditionalized on !DisableDebugInfoPrinting and the presence of the
662   // llvm.dbg.cu metadata node)
663   if (!DwarfInfoSectionSym)
664     return;
665
666   // End any existing sections.
667   // TODO: Does this need to happen?
668   endSections();
669
670   // Finalize the debug info for the module.
671   finalizeModuleInfo();
672
673   emitDebugStr();
674
675   // Emit all the DIEs into a debug info section.
676   emitDebugInfo();
677
678   // Corresponding abbreviations into a abbrev section.
679   emitAbbreviations();
680
681   // Emit info into a debug aranges section.
682   if (GenerateARangeSection)
683     emitDebugARanges();
684
685   // Emit info into a debug ranges section.
686   emitDebugRanges();
687
688   if (useSplitDwarf()) {
689     emitDebugStrDWO();
690     emitDebugInfoDWO();
691     emitDebugAbbrevDWO();
692     emitDebugLineDWO();
693     emitDebugLocDWO();
694     // Emit DWO addresses.
695     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
696   } else
697     // Emit info into a debug loc section.
698     emitDebugLoc();
699
700   // Emit info into the dwarf accelerator table sections.
701   if (useDwarfAccelTables()) {
702     emitAccelNames();
703     emitAccelObjC();
704     emitAccelNamespaces();
705     emitAccelTypes();
706   }
707
708   // Emit the pubnames and pubtypes sections if requested.
709   if (HasDwarfPubSections) {
710     emitDebugPubNames(GenerateGnuPubSections);
711     emitDebugPubTypes(GenerateGnuPubSections);
712   }
713
714   // clean up.
715   SPMap.clear();
716   AbstractVariables.clear();
717 }
718
719 // Find abstract variable, if any, associated with Var.
720 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
721                                                      DIVariable &Cleansed) {
722   LLVMContext &Ctx = DV->getContext();
723   // More then one inlined variable corresponds to one abstract variable.
724   // FIXME: This duplication of variables when inlining should probably be
725   // removed. It's done to allow each DIVariable to describe its location
726   // because the DebugLoc on the dbg.value/declare isn't accurate. We should
727   // make it accurate then remove this duplication/cleansing stuff.
728   Cleansed = cleanseInlinedVariable(DV, Ctx);
729   auto I = AbstractVariables.find(Cleansed);
730   if (I != AbstractVariables.end())
731     return I->second.get();
732   return nullptr;
733 }
734
735 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
736   DIVariable Cleansed;
737   return getExistingAbstractVariable(DV, Cleansed);
738 }
739
740 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
741                                         LexicalScope *Scope) {
742   auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
743   InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
744   AbstractVariables[Var] = std::move(AbsDbgVariable);
745 }
746
747 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
748                                                  const MDNode *ScopeNode) {
749   DIVariable Cleansed = DV;
750   if (getExistingAbstractVariable(DV, Cleansed))
751     return;
752
753   createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
754 }
755
756 void
757 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
758                                                     const MDNode *ScopeNode) {
759   DIVariable Cleansed = DV;
760   if (getExistingAbstractVariable(DV, Cleansed))
761     return;
762
763   if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
764     createAbstractVariable(Cleansed, Scope);
765 }
766
767 // Collect variable information from side table maintained by MMI.
768 void DwarfDebug::collectVariableInfoFromMMITable(
769     SmallPtrSetImpl<const MDNode *> &Processed) {
770   for (const auto &VI : MMI->getVariableDbgInfo()) {
771     if (!VI.Var)
772       continue;
773     Processed.insert(VI.Var);
774     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
775
776     // If variable scope is not found then skip this variable.
777     if (!Scope)
778       continue;
779
780     DIVariable DV(VI.Var);
781     DIExpression Expr(VI.Expr);
782     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
783     ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
784     DbgVariable *RegVar = ConcreteVariables.back().get();
785     RegVar->setFrameIndex(VI.Slot);
786     InfoHolder.addScopeVariable(Scope, RegVar);
787   }
788 }
789
790 // Get .debug_loc entry for the instruction range starting at MI.
791 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
792   const MDNode *Expr = MI->getDebugExpression();
793   const MDNode *Var = MI->getDebugVariable();
794
795   assert(MI->getNumOperands() == 4);
796   if (MI->getOperand(0).isReg()) {
797     MachineLocation MLoc;
798     // If the second operand is an immediate, this is a
799     // register-indirect address.
800     if (!MI->getOperand(1).isImm())
801       MLoc.set(MI->getOperand(0).getReg());
802     else
803       MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
804     return DebugLocEntry::Value(Var, Expr, MLoc);
805   }
806   if (MI->getOperand(0).isImm())
807     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
808   if (MI->getOperand(0).isFPImm())
809     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
810   if (MI->getOperand(0).isCImm())
811     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
812
813   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
814 }
815
816 /// Determine whether two variable pieces overlap.
817 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
818   if (!P1.isVariablePiece() || !P2.isVariablePiece())
819     return true;
820   unsigned l1 = P1.getPieceOffset();
821   unsigned l2 = P2.getPieceOffset();
822   unsigned r1 = l1 + P1.getPieceSize();
823   unsigned r2 = l2 + P2.getPieceSize();
824   // True where [l1,r1[ and [r1,r2[ overlap.
825   return (l1 < r2) && (l2 < r1);
826 }
827
828 /// Build the location list for all DBG_VALUEs in the function that
829 /// describe the same variable.  If the ranges of several independent
830 /// pieces of the same variable overlap partially, split them up and
831 /// combine the ranges. The resulting DebugLocEntries are will have
832 /// strict monotonically increasing begin addresses and will never
833 /// overlap.
834 //
835 // Input:
836 //
837 //   Ranges History [var, loc, piece ofs size]
838 // 0 |      [x, (reg0, piece 0, 32)]
839 // 1 | |    [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
840 // 2 | |    ...
841 // 3   |    [clobber reg0]
842 // 4        [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
843 //
844 // Output:
845 //
846 // [0-1]    [x, (reg0, piece  0, 32)]
847 // [1-3]    [x, (reg0, piece  0, 32), (reg1, piece 32, 32)]
848 // [3-4]    [x, (reg1, piece 32, 32)]
849 // [4- ]    [x, (mem,  piece  0, 64)]
850 void
851 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
852                               const DbgValueHistoryMap::InstrRanges &Ranges) {
853   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
854
855   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
856     const MachineInstr *Begin = I->first;
857     const MachineInstr *End = I->second;
858     assert(Begin->isDebugValue() && "Invalid History entry");
859
860     // Check if a variable is inaccessible in this range.
861     if (Begin->getNumOperands() > 1 &&
862         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
863       OpenRanges.clear();
864       continue;
865     }
866
867     // If this piece overlaps with any open ranges, truncate them.
868     DIExpression DIExpr = Begin->getDebugExpression();
869     auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
870                                [&](DebugLocEntry::Value R) {
871       return piecesOverlap(DIExpr, R.getExpression());
872     });
873     OpenRanges.erase(Last, OpenRanges.end());
874
875     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
876     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
877
878     const MCSymbol *EndLabel;
879     if (End != nullptr)
880       EndLabel = getLabelAfterInsn(End);
881     else if (std::next(I) == Ranges.end())
882       EndLabel = FunctionEndSym;
883     else
884       EndLabel = getLabelBeforeInsn(std::next(I)->first);
885     assert(EndLabel && "Forgot label after instruction ending a range!");
886
887     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
888
889     auto Value = getDebugLocValue(Begin);
890     DebugLocEntry Loc(StartLabel, EndLabel, Value);
891     bool couldMerge = false;
892
893     // If this is a piece, it may belong to the current DebugLocEntry.
894     if (DIExpr.isVariablePiece()) {
895       // Add this value to the list of open ranges.
896       OpenRanges.push_back(Value);
897
898       // Attempt to add the piece to the last entry.
899       if (!DebugLoc.empty())
900         if (DebugLoc.back().MergeValues(Loc))
901           couldMerge = true;
902     }
903
904     if (!couldMerge) {
905       // Need to add a new DebugLocEntry. Add all values from still
906       // valid non-overlapping pieces.
907       if (OpenRanges.size())
908         Loc.addValues(OpenRanges);
909
910       DebugLoc.push_back(std::move(Loc));
911     }
912
913     // Attempt to coalesce the ranges of two otherwise identical
914     // DebugLocEntries.
915     auto CurEntry = DebugLoc.rbegin();
916     auto PrevEntry = std::next(CurEntry);
917     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
918       DebugLoc.pop_back();
919
920     DEBUG({
921       dbgs() << CurEntry->getValues().size() << " Values:\n";
922       for (auto Value : CurEntry->getValues()) {
923         Value.getVariable()->dump();
924         Value.getExpression()->dump();
925       }
926       dbgs() << "-----\n";
927     });
928   }
929 }
930
931
932 // Find variables for each lexical scope.
933 void
934 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
935                                 SmallPtrSetImpl<const MDNode *> &Processed) {
936   // Grab the variable info that was squirreled away in the MMI side-table.
937   collectVariableInfoFromMMITable(Processed);
938
939   for (const auto &I : DbgValues) {
940     DIVariable DV(I.first);
941     if (Processed.count(DV))
942       continue;
943
944     // Instruction ranges, specifying where DV is accessible.
945     const auto &Ranges = I.second;
946     if (Ranges.empty())
947       continue;
948
949     LexicalScope *Scope = nullptr;
950     if (MDNode *IA = DV.getInlinedAt()) {
951       DebugLoc DL = DebugLoc::getFromDILocation(IA);
952       Scope = LScopes.findInlinedScope(DebugLoc::get(
953           DL.getLine(), DL.getCol(), DV.getContext(), IA));
954     } else
955       Scope = LScopes.findLexicalScope(DV.getContext());
956     // If variable scope is not found then skip this variable.
957     if (!Scope)
958       continue;
959
960     Processed.insert(DV);
961     const MachineInstr *MInsn = Ranges.front().first;
962     assert(MInsn->isDebugValue() && "History must begin with debug value");
963     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
964     ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
965     DbgVariable *RegVar = ConcreteVariables.back().get();
966     InfoHolder.addScopeVariable(Scope, RegVar);
967
968     // Check if the first DBG_VALUE is valid for the rest of the function.
969     if (Ranges.size() == 1 && Ranges.front().second == nullptr)
970       continue;
971
972     // Handle multiple DBG_VALUE instructions describing one variable.
973     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
974
975     DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
976     DebugLocList &LocList = DotDebugLocEntries.back();
977     LocList.CU = &TheCU;
978     LocList.Label =
979         Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
980
981     // Build the location list for this variable.
982     buildLocationList(LocList.List, Ranges);
983   }
984
985   // Collect info for variables that were optimized out.
986   DIArray Variables = SP.getVariables();
987   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
988     DIVariable DV(Variables.getElement(i));
989     assert(DV.isVariable());
990     if (!Processed.insert(DV))
991       continue;
992     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
993       ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
994       DIExpression NoExpr;
995       ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
996       InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
997     }
998   }
999 }
1000
1001 // Return Label preceding the instruction.
1002 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1003   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1004   assert(Label && "Didn't insert label before instruction");
1005   return Label;
1006 }
1007
1008 // Return Label immediately following the instruction.
1009 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1010   return LabelsAfterInsn.lookup(MI);
1011 }
1012
1013 // Process beginning of an instruction.
1014 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1015   assert(CurMI == nullptr);
1016   CurMI = MI;
1017   // Check if source location changes, but ignore DBG_VALUE locations.
1018   if (!MI->isDebugValue()) {
1019     DebugLoc DL = MI->getDebugLoc();
1020     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1021       unsigned Flags = 0;
1022       PrevInstLoc = DL;
1023       if (DL == PrologEndLoc) {
1024         Flags |= DWARF2_FLAG_PROLOGUE_END;
1025         PrologEndLoc = DebugLoc();
1026       }
1027       if (PrologEndLoc.isUnknown())
1028         Flags |= DWARF2_FLAG_IS_STMT;
1029
1030       if (!DL.isUnknown()) {
1031         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1032         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1033       } else
1034         recordSourceLine(0, 0, nullptr, 0);
1035     }
1036   }
1037
1038   // Insert labels where requested.
1039   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1040       LabelsBeforeInsn.find(MI);
1041
1042   // No label needed.
1043   if (I == LabelsBeforeInsn.end())
1044     return;
1045
1046   // Label already assigned.
1047   if (I->second)
1048     return;
1049
1050   if (!PrevLabel) {
1051     PrevLabel = MMI->getContext().CreateTempSymbol();
1052     Asm->OutStreamer.EmitLabel(PrevLabel);
1053   }
1054   I->second = PrevLabel;
1055 }
1056
1057 // Process end of an instruction.
1058 void DwarfDebug::endInstruction() {
1059   assert(CurMI != nullptr);
1060   // Don't create a new label after DBG_VALUE instructions.
1061   // They don't generate code.
1062   if (!CurMI->isDebugValue())
1063     PrevLabel = nullptr;
1064
1065   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1066       LabelsAfterInsn.find(CurMI);
1067   CurMI = nullptr;
1068
1069   // No label needed.
1070   if (I == LabelsAfterInsn.end())
1071     return;
1072
1073   // Label already assigned.
1074   if (I->second)
1075     return;
1076
1077   // We need a label after this instruction.
1078   if (!PrevLabel) {
1079     PrevLabel = MMI->getContext().CreateTempSymbol();
1080     Asm->OutStreamer.EmitLabel(PrevLabel);
1081   }
1082   I->second = PrevLabel;
1083 }
1084
1085 // Each LexicalScope has first instruction and last instruction to mark
1086 // beginning and end of a scope respectively. Create an inverse map that list
1087 // scopes starts (and ends) with an instruction. One instruction may start (or
1088 // end) multiple scopes. Ignore scopes that are not reachable.
1089 void DwarfDebug::identifyScopeMarkers() {
1090   SmallVector<LexicalScope *, 4> WorkList;
1091   WorkList.push_back(LScopes.getCurrentFunctionScope());
1092   while (!WorkList.empty()) {
1093     LexicalScope *S = WorkList.pop_back_val();
1094
1095     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1096     if (!Children.empty())
1097       WorkList.append(Children.begin(), Children.end());
1098
1099     if (S->isAbstractScope())
1100       continue;
1101
1102     for (const InsnRange &R : S->getRanges()) {
1103       assert(R.first && "InsnRange does not have first instruction!");
1104       assert(R.second && "InsnRange does not have second instruction!");
1105       requestLabelBeforeInsn(R.first);
1106       requestLabelAfterInsn(R.second);
1107     }
1108   }
1109 }
1110
1111 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1112   // First known non-DBG_VALUE and non-frame setup location marks
1113   // the beginning of the function body.
1114   for (const auto &MBB : *MF)
1115     for (const auto &MI : MBB)
1116       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1117           !MI.getDebugLoc().isUnknown())
1118         return MI.getDebugLoc();
1119   return DebugLoc();
1120 }
1121
1122 // Gather pre-function debug information.  Assumes being called immediately
1123 // after the function entry point has been emitted.
1124 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1125   CurFn = MF;
1126
1127   // If there's no debug info for the function we're not going to do anything.
1128   if (!MMI->hasDebugInfo())
1129     return;
1130
1131   auto DI = FunctionDIs.find(MF->getFunction());
1132   if (DI == FunctionDIs.end())
1133     return;
1134
1135   // Grab the lexical scopes for the function, if we don't have any of those
1136   // then we're not going to be able to do anything.
1137   LScopes.initialize(*MF);
1138   if (LScopes.empty())
1139     return;
1140
1141   assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1142
1143   // Make sure that each lexical scope will have a begin/end label.
1144   identifyScopeMarkers();
1145
1146   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1147   // belongs to so that we add to the correct per-cu line table in the
1148   // non-asm case.
1149   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1150   // FnScope->getScopeNode() and DI->second should represent the same function,
1151   // though they may not be the same MDNode due to inline functions merged in
1152   // LTO where the debug info metadata still differs (either due to distinct
1153   // written differences - two versions of a linkonce_odr function
1154   // written/copied into two separate files, or some sub-optimal metadata that
1155   // isn't structurally identical (see: file path/name info from clang, which
1156   // includes the directory of the cpp file being built, even when the file name
1157   // is absolute (such as an <> lookup header)))
1158   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1159   assert(TheCU && "Unable to find compile unit!");
1160   if (Asm->OutStreamer.hasRawTextSupport())
1161     // Use a single line table if we are generating assembly.
1162     Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1163   else
1164     Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1165
1166   // Emit a label for the function so that we have a beginning address.
1167   FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1168   // Assumes in correct section after the entry point.
1169   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1170
1171   // Calculate history for local variables.
1172   calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1173                            DbgValues);
1174
1175   // Request labels for the full history.
1176   for (const auto &I : DbgValues) {
1177     const auto &Ranges = I.second;
1178     if (Ranges.empty())
1179       continue;
1180
1181     // The first mention of a function argument gets the FunctionBeginSym
1182     // label, so arguments are visible when breaking at function entry.
1183     DIVariable DIVar(Ranges.front().first->getDebugVariable());
1184     if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1185         getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1186       LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1187       if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1188         // Mark all non-overlapping initial pieces.
1189         for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1190           DIExpression Piece = I->first->getDebugExpression();
1191           if (std::all_of(Ranges.begin(), I,
1192                           [&](DbgValueHistoryMap::InstrRange Pred) {
1193                 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1194               }))
1195             LabelsBeforeInsn[I->first] = FunctionBeginSym;
1196           else
1197             break;
1198         }
1199       }
1200     }
1201
1202     for (const auto &Range : Ranges) {
1203       requestLabelBeforeInsn(Range.first);
1204       if (Range.second)
1205         requestLabelAfterInsn(Range.second);
1206     }
1207   }
1208
1209   PrevInstLoc = DebugLoc();
1210   PrevLabel = FunctionBeginSym;
1211
1212   // Record beginning of function.
1213   PrologEndLoc = findPrologueEndLoc(MF);
1214   if (!PrologEndLoc.isUnknown()) {
1215     DebugLoc FnStartDL =
1216         PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1217     recordSourceLine(
1218         FnStartDL.getLine(), FnStartDL.getCol(),
1219         FnStartDL.getScope(MF->getFunction()->getContext()),
1220         // We'd like to list the prologue as "not statements" but GDB behaves
1221         // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1222         DWARF2_FLAG_IS_STMT);
1223   }
1224 }
1225
1226 // Gather and emit post-function debug information.
1227 void DwarfDebug::endFunction(const MachineFunction *MF) {
1228   assert(CurFn == MF &&
1229       "endFunction should be called with the same function as beginFunction");
1230
1231   if (!MMI->hasDebugInfo() || LScopes.empty() ||
1232       !FunctionDIs.count(MF->getFunction())) {
1233     // If we don't have a lexical scope for this function then there will
1234     // be a hole in the range information. Keep note of this by setting the
1235     // previously used section to nullptr.
1236     PrevCU = nullptr;
1237     CurFn = nullptr;
1238     return;
1239   }
1240
1241   // Define end label for subprogram.
1242   FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1243   // Assumes in correct section after the entry point.
1244   Asm->OutStreamer.EmitLabel(FunctionEndSym);
1245
1246   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1247   Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1248
1249   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1250   DISubprogram SP(FnScope->getScopeNode());
1251   DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1252
1253   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1254   collectVariableInfo(TheCU, SP, ProcessedVars);
1255
1256   // Add the range of this function to the list of ranges for the CU.
1257   TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1258
1259   // Under -gmlt, skip building the subprogram if there are no inlined
1260   // subroutines inside it.
1261   if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1262       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1263     assert(InfoHolder.getScopeVariables().empty());
1264     assert(DbgValues.empty());
1265     // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1266     // by a -gmlt CU. Add a test and remove this assertion.
1267     assert(AbstractVariables.empty());
1268     LabelsBeforeInsn.clear();
1269     LabelsAfterInsn.clear();
1270     PrevLabel = nullptr;
1271     CurFn = nullptr;
1272     return;
1273   }
1274
1275 #ifndef NDEBUG
1276   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1277 #endif
1278   // Construct abstract scopes.
1279   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1280     DISubprogram SP(AScope->getScopeNode());
1281     assert(SP.isSubprogram());
1282     // Collect info for variables that were optimized out.
1283     DIArray Variables = SP.getVariables();
1284     for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1285       DIVariable DV(Variables.getElement(i));
1286       assert(DV && DV.isVariable());
1287       if (!ProcessedVars.insert(DV))
1288         continue;
1289       ensureAbstractVariableIsCreated(DV, DV.getContext());
1290       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1291              && "ensureAbstractVariableIsCreated inserted abstract scopes");
1292     }
1293     constructAbstractSubprogramScopeDIE(AScope);
1294   }
1295
1296   TheCU.constructSubprogramScopeDIE(FnScope);
1297
1298   // Clear debug info
1299   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1300   // DbgVariables except those that are also in AbstractVariables (since they
1301   // can be used cross-function)
1302   InfoHolder.getScopeVariables().clear();
1303   DbgValues.clear();
1304   LabelsBeforeInsn.clear();
1305   LabelsAfterInsn.clear();
1306   PrevLabel = nullptr;
1307   CurFn = nullptr;
1308 }
1309
1310 // Register a source line with debug info. Returns the  unique label that was
1311 // emitted and which provides correspondence to the source line list.
1312 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1313                                   unsigned Flags) {
1314   StringRef Fn;
1315   StringRef Dir;
1316   unsigned Src = 1;
1317   unsigned Discriminator = 0;
1318   if (DIScope Scope = DIScope(S)) {
1319     assert(Scope.isScope());
1320     Fn = Scope.getFilename();
1321     Dir = Scope.getDirectory();
1322     if (Scope.isLexicalBlockFile())
1323       Discriminator = DILexicalBlockFile(S).getDiscriminator();
1324
1325     unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1326     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1327               .getOrCreateSourceID(Fn, Dir);
1328   }
1329   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1330                                          Discriminator, Fn);
1331 }
1332
1333 //===----------------------------------------------------------------------===//
1334 // Emit Methods
1335 //===----------------------------------------------------------------------===//
1336
1337 // Emit initial Dwarf sections with a label at the start of each one.
1338 void DwarfDebug::emitSectionLabels() {
1339   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1340
1341   // Dwarf sections base addresses.
1342   DwarfInfoSectionSym =
1343       emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1344   if (useSplitDwarf()) {
1345     DwarfInfoDWOSectionSym =
1346         emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1347     DwarfTypesDWOSectionSym =
1348         emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1349   }
1350   DwarfAbbrevSectionSym =
1351       emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1352   if (useSplitDwarf())
1353     DwarfAbbrevDWOSectionSym = emitSectionSym(
1354         Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1355   if (GenerateARangeSection)
1356     emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1357
1358   DwarfLineSectionSym =
1359       emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1360   if (GenerateGnuPubSections) {
1361     DwarfGnuPubNamesSectionSym =
1362         emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1363     DwarfGnuPubTypesSectionSym =
1364         emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1365   } else if (HasDwarfPubSections) {
1366     emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1367     emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1368   }
1369
1370   DwarfStrSectionSym =
1371       emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1372   if (useSplitDwarf()) {
1373     DwarfStrDWOSectionSym =
1374         emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1375     DwarfAddrSectionSym =
1376         emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1377     DwarfDebugLocSectionSym =
1378         emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1379   } else
1380     DwarfDebugLocSectionSym =
1381         emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1382   DwarfDebugRangeSectionSym =
1383       emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1384 }
1385
1386 // Recursively emits a debug information entry.
1387 void DwarfDebug::emitDIE(DIE &Die) {
1388   // Get the abbreviation for this DIE.
1389   const DIEAbbrev &Abbrev = Die.getAbbrev();
1390
1391   // Emit the code (index) for the abbreviation.
1392   if (Asm->isVerbose())
1393     Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1394                                 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1395                                 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1396                                 dwarf::TagString(Abbrev.getTag()));
1397   Asm->EmitULEB128(Abbrev.getNumber());
1398
1399   const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1400   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1401
1402   // Emit the DIE attribute values.
1403   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1404     dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1405     dwarf::Form Form = AbbrevData[i].getForm();
1406     assert(Form && "Too many attributes for DIE (check abbreviation)");
1407
1408     if (Asm->isVerbose()) {
1409       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1410       if (Attr == dwarf::DW_AT_accessibility)
1411         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1412             cast<DIEInteger>(Values[i])->getValue()));
1413     }
1414
1415     // Emit an attribute using the defined form.
1416     Values[i]->EmitValue(Asm, Form);
1417   }
1418
1419   // Emit the DIE children if any.
1420   if (Abbrev.hasChildren()) {
1421     for (auto &Child : Die.getChildren())
1422       emitDIE(*Child);
1423
1424     Asm->OutStreamer.AddComment("End Of Children Mark");
1425     Asm->EmitInt8(0);
1426   }
1427 }
1428
1429 // Emit the debug info section.
1430 void DwarfDebug::emitDebugInfo() {
1431   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1432
1433   Holder.emitUnits(DwarfAbbrevSectionSym);
1434 }
1435
1436 // Emit the abbreviation section.
1437 void DwarfDebug::emitAbbreviations() {
1438   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1439
1440   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1441 }
1442
1443 // Emit the last address of the section and the end of the line matrix.
1444 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1445   // Define last address of section.
1446   Asm->OutStreamer.AddComment("Extended Op");
1447   Asm->EmitInt8(0);
1448
1449   Asm->OutStreamer.AddComment("Op size");
1450   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1451   Asm->OutStreamer.AddComment("DW_LNE_set_address");
1452   Asm->EmitInt8(dwarf::DW_LNE_set_address);
1453
1454   Asm->OutStreamer.AddComment("Section end label");
1455
1456   Asm->OutStreamer.EmitSymbolValue(
1457       Asm->GetTempSymbol("section_end", SectionEnd),
1458       Asm->getDataLayout().getPointerSize());
1459
1460   // Mark end of matrix.
1461   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1462   Asm->EmitInt8(0);
1463   Asm->EmitInt8(1);
1464   Asm->EmitInt8(1);
1465 }
1466
1467 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1468                            StringRef TableName, StringRef SymName) {
1469   Accel.FinalizeTable(Asm, TableName);
1470   Asm->OutStreamer.SwitchSection(Section);
1471   auto *SectionBegin = Asm->GetTempSymbol(SymName);
1472   Asm->OutStreamer.EmitLabel(SectionBegin);
1473
1474   // Emit the full data.
1475   Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1476 }
1477
1478 // Emit visible names into a hashed accelerator table section.
1479 void DwarfDebug::emitAccelNames() {
1480   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1481             "Names", "names_begin");
1482 }
1483
1484 // Emit objective C classes and categories into a hashed accelerator table
1485 // section.
1486 void DwarfDebug::emitAccelObjC() {
1487   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1488             "ObjC", "objc_begin");
1489 }
1490
1491 // Emit namespace dies into a hashed accelerator table.
1492 void DwarfDebug::emitAccelNamespaces() {
1493   emitAccel(AccelNamespace,
1494             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1495             "namespac", "namespac_begin");
1496 }
1497
1498 // Emit type dies into a hashed accelerator table.
1499 void DwarfDebug::emitAccelTypes() {
1500   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1501             "types", "types_begin");
1502 }
1503
1504 // Public name handling.
1505 // The format for the various pubnames:
1506 //
1507 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1508 // for the DIE that is named.
1509 //
1510 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1511 // into the CU and the index value is computed according to the type of value
1512 // for the DIE that is named.
1513 //
1514 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1515 // it's the offset within the debug_info/debug_types dwo section, however, the
1516 // reference in the pubname header doesn't change.
1517
1518 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1519 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1520                                                         const DIE *Die) {
1521   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1522
1523   // We could have a specification DIE that has our most of our knowledge,
1524   // look for that now.
1525   DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1526   if (SpecVal) {
1527     DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1528     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1529       Linkage = dwarf::GIEL_EXTERNAL;
1530   } else if (Die->findAttribute(dwarf::DW_AT_external))
1531     Linkage = dwarf::GIEL_EXTERNAL;
1532
1533   switch (Die->getTag()) {
1534   case dwarf::DW_TAG_class_type:
1535   case dwarf::DW_TAG_structure_type:
1536   case dwarf::DW_TAG_union_type:
1537   case dwarf::DW_TAG_enumeration_type:
1538     return dwarf::PubIndexEntryDescriptor(
1539         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1540                               ? dwarf::GIEL_STATIC
1541                               : dwarf::GIEL_EXTERNAL);
1542   case dwarf::DW_TAG_typedef:
1543   case dwarf::DW_TAG_base_type:
1544   case dwarf::DW_TAG_subrange_type:
1545     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1546   case dwarf::DW_TAG_namespace:
1547     return dwarf::GIEK_TYPE;
1548   case dwarf::DW_TAG_subprogram:
1549     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1550   case dwarf::DW_TAG_constant:
1551   case dwarf::DW_TAG_variable:
1552     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1553   case dwarf::DW_TAG_enumerator:
1554     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1555                                           dwarf::GIEL_STATIC);
1556   default:
1557     return dwarf::GIEK_NONE;
1558   }
1559 }
1560
1561 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1562 ///
1563 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1564   const MCSection *PSec =
1565       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1566                : Asm->getObjFileLowering().getDwarfPubNamesSection();
1567
1568   emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1569 }
1570
1571 void DwarfDebug::emitDebugPubSection(
1572     bool GnuStyle, const MCSection *PSec, StringRef Name,
1573     const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1574   for (const auto &NU : CUMap) {
1575     DwarfCompileUnit *TheU = NU.second;
1576
1577     const auto &Globals = (TheU->*Accessor)();
1578
1579     if (Globals.empty())
1580       continue;
1581
1582     if (auto *Skeleton = TheU->getSkeleton())
1583       TheU = Skeleton;
1584     unsigned ID = TheU->getUniqueID();
1585
1586     // Start the dwarf pubnames section.
1587     Asm->OutStreamer.SwitchSection(PSec);
1588
1589     // Emit the header.
1590     Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1591     MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1592     MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1593     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1594
1595     Asm->OutStreamer.EmitLabel(BeginLabel);
1596
1597     Asm->OutStreamer.AddComment("DWARF Version");
1598     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1599
1600     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1601     Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1602
1603     Asm->OutStreamer.AddComment("Compilation Unit Length");
1604     Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1605
1606     // Emit the pubnames for this compilation unit.
1607     for (const auto &GI : Globals) {
1608       const char *Name = GI.getKeyData();
1609       const DIE *Entity = GI.second;
1610
1611       Asm->OutStreamer.AddComment("DIE offset");
1612       Asm->EmitInt32(Entity->getOffset());
1613
1614       if (GnuStyle) {
1615         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1616         Asm->OutStreamer.AddComment(
1617             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1618             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1619         Asm->EmitInt8(Desc.toBits());
1620       }
1621
1622       Asm->OutStreamer.AddComment("External Name");
1623       Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1624     }
1625
1626     Asm->OutStreamer.AddComment("End Mark");
1627     Asm->EmitInt32(0);
1628     Asm->OutStreamer.EmitLabel(EndLabel);
1629   }
1630 }
1631
1632 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1633   const MCSection *PSec =
1634       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1635                : Asm->getObjFileLowering().getDwarfPubTypesSection();
1636
1637   emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1638 }
1639
1640 // Emit visible names into a debug str section.
1641 void DwarfDebug::emitDebugStr() {
1642   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1643   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1644 }
1645
1646 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1647 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1648                                const DITypeIdentifierMap &Map,
1649                                ArrayRef<DebugLocEntry::Value> Values) {
1650   assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1651         return P.isVariablePiece();
1652       }) && "all values are expected to be pieces");
1653   assert(std::is_sorted(Values.begin(), Values.end()) &&
1654          "pieces are expected to be sorted");
1655
1656   unsigned Offset = 0;
1657   for (auto Piece : Values) {
1658     DIExpression Expr = Piece.getExpression();
1659     unsigned PieceOffset = Expr.getPieceOffset();
1660     unsigned PieceSize = Expr.getPieceSize();
1661     assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1662     if (Offset < PieceOffset) {
1663       // The DWARF spec seriously mandates pieces with no locations for gaps.
1664       Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1665       Offset += PieceOffset-Offset;
1666     }
1667
1668     Offset += PieceSize;
1669
1670     const unsigned SizeOfByte = 8;
1671 #ifndef NDEBUG
1672     DIVariable Var = Piece.getVariable();
1673     assert(!Var.isIndirect() && "indirect address for piece");
1674     unsigned VarSize = Var.getSizeInBits(Map);
1675     assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1676            && "piece is larger than or outside of variable");
1677     assert(PieceSize*SizeOfByte != VarSize
1678            && "piece covers entire variable");
1679 #endif
1680     if (Piece.isLocation() && Piece.getLoc().isReg())
1681       Asm->EmitDwarfRegOpPiece(Streamer,
1682                                Piece.getLoc(),
1683                                PieceSize*SizeOfByte);
1684     else {
1685       emitDebugLocValue(Streamer, Piece);
1686       Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1687     }
1688   }
1689 }
1690
1691
1692 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1693                                    const DebugLocEntry &Entry) {
1694   const DebugLocEntry::Value Value = Entry.getValues()[0];
1695   if (Value.isVariablePiece())
1696     // Emit all pieces that belong to the same variable and range.
1697     return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1698
1699   assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1700   emitDebugLocValue(Streamer, Value);
1701 }
1702
1703 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1704                                    const DebugLocEntry::Value &Value) {
1705   DIVariable DV = Value.getVariable();
1706   // Regular entry.
1707   if (Value.isInt()) {
1708     DIBasicType BTy(resolve(DV.getType()));
1709     if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1710                          BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1711       Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1712       Streamer.EmitSLEB128(Value.getInt());
1713     } else {
1714       Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1715       Streamer.EmitULEB128(Value.getInt());
1716     }
1717   } else if (Value.isLocation()) {
1718     MachineLocation Loc = Value.getLoc();
1719     DIExpression Expr = Value.getExpression();
1720     if (!Expr)
1721       // Regular entry.
1722       Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1723     else {
1724       // Complex address entry.
1725       unsigned N = Expr.getNumElements();
1726       unsigned i = 0;
1727       if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
1728         if (Loc.getOffset()) {
1729           i = 2;
1730           Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1731           Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1732           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1733           Streamer.EmitSLEB128(Expr.getElement(1));
1734         } else {
1735           // If first address element is OpPlus then emit
1736           // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1737           MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
1738           Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1739           i = 2;
1740         }
1741       } else {
1742         Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1743       }
1744
1745       // Emit remaining complex address elements.
1746       for (; i < N; ++i) {
1747         uint64_t Element = Expr.getElement(i);
1748         if (Element == dwarf::DW_OP_plus) {
1749           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1750           Streamer.EmitULEB128(Expr.getElement(++i));
1751         } else if (Element == dwarf::DW_OP_deref) {
1752           if (!Loc.isReg())
1753             Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1754         } else if (Element == dwarf::DW_OP_piece) {
1755           i += 3;
1756           // handled in emitDebugLocEntry.
1757         } else
1758           llvm_unreachable("unknown Opcode found in complex address");
1759       }
1760     }
1761   }
1762   // else ... ignore constant fp. There is not any good way to
1763   // to represent them here in dwarf.
1764   // FIXME: ^
1765 }
1766
1767 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1768   Asm->OutStreamer.AddComment("Loc expr size");
1769   MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1770   MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1771   Asm->EmitLabelDifference(end, begin, 2);
1772   Asm->OutStreamer.EmitLabel(begin);
1773   // Emit the entry.
1774   APByteStreamer Streamer(*Asm);
1775   emitDebugLocEntry(Streamer, Entry);
1776   // Close the range.
1777   Asm->OutStreamer.EmitLabel(end);
1778 }
1779
1780 // Emit locations into the debug loc section.
1781 void DwarfDebug::emitDebugLoc() {
1782   // Start the dwarf loc section.
1783   Asm->OutStreamer.SwitchSection(
1784       Asm->getObjFileLowering().getDwarfLocSection());
1785   unsigned char Size = Asm->getDataLayout().getPointerSize();
1786   for (const auto &DebugLoc : DotDebugLocEntries) {
1787     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1788     const DwarfCompileUnit *CU = DebugLoc.CU;
1789     assert(!CU->getRanges().empty());
1790     for (const auto &Entry : DebugLoc.List) {
1791       // Set up the range. This range is relative to the entry point of the
1792       // compile unit. This is a hard coded 0 for low_pc when we're emitting
1793       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1794       if (CU->getRanges().size() == 1) {
1795         // Grab the begin symbol from the first range as our base.
1796         const MCSymbol *Base = CU->getRanges()[0].getStart();
1797         Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1798         Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1799       } else {
1800         Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1801         Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1802       }
1803
1804       emitDebugLocEntryLocation(Entry);
1805     }
1806     Asm->OutStreamer.EmitIntValue(0, Size);
1807     Asm->OutStreamer.EmitIntValue(0, Size);
1808   }
1809 }
1810
1811 void DwarfDebug::emitDebugLocDWO() {
1812   Asm->OutStreamer.SwitchSection(
1813       Asm->getObjFileLowering().getDwarfLocDWOSection());
1814   for (const auto &DebugLoc : DotDebugLocEntries) {
1815     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1816     for (const auto &Entry : DebugLoc.List) {
1817       // Just always use start_length for now - at least that's one address
1818       // rather than two. We could get fancier and try to, say, reuse an
1819       // address we know we've emitted elsewhere (the start of the function?
1820       // The start of the CU or CU subrange that encloses this range?)
1821       Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1822       unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1823       Asm->EmitULEB128(idx);
1824       Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1825
1826       emitDebugLocEntryLocation(Entry);
1827     }
1828     Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1829   }
1830 }
1831
1832 struct ArangeSpan {
1833   const MCSymbol *Start, *End;
1834 };
1835
1836 // Emit a debug aranges section, containing a CU lookup for any
1837 // address we can tie back to a CU.
1838 void DwarfDebug::emitDebugARanges() {
1839   // Start the dwarf aranges section.
1840   Asm->OutStreamer.SwitchSection(
1841       Asm->getObjFileLowering().getDwarfARangesSection());
1842
1843   typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
1844
1845   SpansType Spans;
1846
1847   // Build a list of sections used.
1848   std::vector<const MCSection *> Sections;
1849   for (const auto &it : SectionMap) {
1850     const MCSection *Section = it.first;
1851     Sections.push_back(Section);
1852   }
1853
1854   // Sort the sections into order.
1855   // This is only done to ensure consistent output order across different runs.
1856   std::sort(Sections.begin(), Sections.end(), SectionSort);
1857
1858   // Build a set of address spans, sorted by CU.
1859   for (const MCSection *Section : Sections) {
1860     SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1861     if (List.size() < 2)
1862       continue;
1863
1864     // Sort the symbols by offset within the section.
1865     std::sort(List.begin(), List.end(),
1866               [&](const SymbolCU &A, const SymbolCU &B) {
1867       unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1868       unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1869
1870       // Symbols with no order assigned should be placed at the end.
1871       // (e.g. section end labels)
1872       if (IA == 0)
1873         return false;
1874       if (IB == 0)
1875         return true;
1876       return IA < IB;
1877     });
1878
1879     // If we have no section (e.g. common), just write out
1880     // individual spans for each symbol.
1881     if (!Section) {
1882       for (const SymbolCU &Cur : List) {
1883         ArangeSpan Span;
1884         Span.Start = Cur.Sym;
1885         Span.End = nullptr;
1886         if (Cur.CU)
1887           Spans[Cur.CU].push_back(Span);
1888       }
1889     } else {
1890       // Build spans between each label.
1891       const MCSymbol *StartSym = List[0].Sym;
1892       for (size_t n = 1, e = List.size(); n < e; n++) {
1893         const SymbolCU &Prev = List[n - 1];
1894         const SymbolCU &Cur = List[n];
1895
1896         // Try and build the longest span we can within the same CU.
1897         if (Cur.CU != Prev.CU) {
1898           ArangeSpan Span;
1899           Span.Start = StartSym;
1900           Span.End = Cur.Sym;
1901           Spans[Prev.CU].push_back(Span);
1902           StartSym = Cur.Sym;
1903         }
1904       }
1905     }
1906   }
1907
1908   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1909
1910   // Build a list of CUs used.
1911   std::vector<DwarfCompileUnit *> CUs;
1912   for (const auto &it : Spans) {
1913     DwarfCompileUnit *CU = it.first;
1914     CUs.push_back(CU);
1915   }
1916
1917   // Sort the CU list (again, to ensure consistent output order).
1918   std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1919     return A->getUniqueID() < B->getUniqueID();
1920   });
1921
1922   // Emit an arange table for each CU we used.
1923   for (DwarfCompileUnit *CU : CUs) {
1924     std::vector<ArangeSpan> &List = Spans[CU];
1925
1926     // Emit size of content not including length itself.
1927     unsigned ContentSize =
1928         sizeof(int16_t) + // DWARF ARange version number
1929         sizeof(int32_t) + // Offset of CU in the .debug_info section
1930         sizeof(int8_t) +  // Pointer Size (in bytes)
1931         sizeof(int8_t);   // Segment Size (in bytes)
1932
1933     unsigned TupleSize = PtrSize * 2;
1934
1935     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1936     unsigned Padding =
1937         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1938
1939     ContentSize += Padding;
1940     ContentSize += (List.size() + 1) * TupleSize;
1941
1942     // For each compile unit, write the list of spans it covers.
1943     Asm->OutStreamer.AddComment("Length of ARange Set");
1944     Asm->EmitInt32(ContentSize);
1945     Asm->OutStreamer.AddComment("DWARF Arange version number");
1946     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1947     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1948     Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
1949     Asm->OutStreamer.AddComment("Address Size (in bytes)");
1950     Asm->EmitInt8(PtrSize);
1951     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1952     Asm->EmitInt8(0);
1953
1954     Asm->OutStreamer.EmitFill(Padding, 0xff);
1955
1956     for (const ArangeSpan &Span : List) {
1957       Asm->EmitLabelReference(Span.Start, PtrSize);
1958
1959       // Calculate the size as being from the span start to it's end.
1960       if (Span.End) {
1961         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1962       } else {
1963         // For symbols without an end marker (e.g. common), we
1964         // write a single arange entry containing just that one symbol.
1965         uint64_t Size = SymSize[Span.Start];
1966         if (Size == 0)
1967           Size = 1;
1968
1969         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1970       }
1971     }
1972
1973     Asm->OutStreamer.AddComment("ARange terminator");
1974     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1975     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1976   }
1977 }
1978
1979 // Emit visible names into a debug ranges section.
1980 void DwarfDebug::emitDebugRanges() {
1981   // Start the dwarf ranges section.
1982   Asm->OutStreamer.SwitchSection(
1983       Asm->getObjFileLowering().getDwarfRangesSection());
1984
1985   // Size for our labels.
1986   unsigned char Size = Asm->getDataLayout().getPointerSize();
1987
1988   // Grab the specific ranges for the compile units in the module.
1989   for (const auto &I : CUMap) {
1990     DwarfCompileUnit *TheCU = I.second;
1991
1992     // Iterate over the misc ranges for the compile units in the module.
1993     for (const RangeSpanList &List : TheCU->getRangeLists()) {
1994       // Emit our symbol so we can find the beginning of the range.
1995       Asm->OutStreamer.EmitLabel(List.getSym());
1996
1997       for (const RangeSpan &Range : List.getRanges()) {
1998         const MCSymbol *Begin = Range.getStart();
1999         const MCSymbol *End = Range.getEnd();
2000         assert(Begin && "Range without a begin symbol?");
2001         assert(End && "Range without an end symbol?");
2002         if (TheCU->getRanges().size() == 1) {
2003           // Grab the begin symbol from the first range as our base.
2004           const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2005           Asm->EmitLabelDifference(Begin, Base, Size);
2006           Asm->EmitLabelDifference(End, Base, Size);
2007         } else {
2008           Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2009           Asm->OutStreamer.EmitSymbolValue(End, Size);
2010         }
2011       }
2012
2013       // And terminate the list with two 0 values.
2014       Asm->OutStreamer.EmitIntValue(0, Size);
2015       Asm->OutStreamer.EmitIntValue(0, Size);
2016     }
2017
2018     // Now emit a range for the CU itself.
2019     if (TheCU->getRanges().size() > 1) {
2020       Asm->OutStreamer.EmitLabel(
2021           Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2022       for (const RangeSpan &Range : TheCU->getRanges()) {
2023         const MCSymbol *Begin = Range.getStart();
2024         const MCSymbol *End = Range.getEnd();
2025         assert(Begin && "Range without a begin symbol?");
2026         assert(End && "Range without an end symbol?");
2027         Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2028         Asm->OutStreamer.EmitSymbolValue(End, Size);
2029       }
2030       // And terminate the list with two 0 values.
2031       Asm->OutStreamer.EmitIntValue(0, Size);
2032       Asm->OutStreamer.EmitIntValue(0, Size);
2033     }
2034   }
2035 }
2036
2037 // DWARF5 Experimental Separate Dwarf emitters.
2038
2039 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2040                                   std::unique_ptr<DwarfUnit> NewU) {
2041   NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2042                        U.getCUNode().getSplitDebugFilename());
2043
2044   if (!CompilationDir.empty())
2045     NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2046
2047   addGnuPubAttributes(*NewU, Die);
2048
2049   SkeletonHolder.addUnit(std::move(NewU));
2050 }
2051
2052 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2053 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2054 // DW_AT_addr_base, DW_AT_ranges_base.
2055 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2056
2057   auto OwnedUnit = make_unique<DwarfCompileUnit>(
2058       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2059   DwarfCompileUnit &NewCU = *OwnedUnit;
2060   NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2061                     DwarfInfoSectionSym);
2062
2063   NewCU.initStmtList(DwarfLineSectionSym);
2064
2065   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2066
2067   return NewCU;
2068 }
2069
2070 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2071 // compile units that would normally be in debug_info.
2072 void DwarfDebug::emitDebugInfoDWO() {
2073   assert(useSplitDwarf() && "No split dwarf debug info?");
2074   // Don't pass an abbrev symbol, using a constant zero instead so as not to
2075   // emit relocations into the dwo file.
2076   InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2077 }
2078
2079 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2080 // abbreviations for the .debug_info.dwo section.
2081 void DwarfDebug::emitDebugAbbrevDWO() {
2082   assert(useSplitDwarf() && "No split dwarf?");
2083   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2084 }
2085
2086 void DwarfDebug::emitDebugLineDWO() {
2087   assert(useSplitDwarf() && "No split dwarf?");
2088   Asm->OutStreamer.SwitchSection(
2089       Asm->getObjFileLowering().getDwarfLineDWOSection());
2090   SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2091 }
2092
2093 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2094 // string section and is identical in format to traditional .debug_str
2095 // sections.
2096 void DwarfDebug::emitDebugStrDWO() {
2097   assert(useSplitDwarf() && "No split dwarf?");
2098   const MCSection *OffSec =
2099       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2100   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2101                          OffSec);
2102 }
2103
2104 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2105   if (!useSplitDwarf())
2106     return nullptr;
2107   if (SingleCU)
2108     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2109   return &SplitTypeUnitFileTable;
2110 }
2111
2112 static uint64_t makeTypeSignature(StringRef Identifier) {
2113   MD5 Hash;
2114   Hash.update(Identifier);
2115   // ... take the least significant 8 bytes and return those. Our MD5
2116   // implementation always returns its results in little endian, swap bytes
2117   // appropriately.
2118   MD5::MD5Result Result;
2119   Hash.final(Result);
2120   return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2121 }
2122
2123 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2124                                       StringRef Identifier, DIE &RefDie,
2125                                       DICompositeType CTy) {
2126   // Fast path if we're building some type units and one has already used the
2127   // address pool we know we're going to throw away all this work anyway, so
2128   // don't bother building dependent types.
2129   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2130     return;
2131
2132   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2133   if (TU) {
2134     CU.addDIETypeSignature(RefDie, *TU);
2135     return;
2136   }
2137
2138   bool TopLevelType = TypeUnitsUnderConstruction.empty();
2139   AddrPool.resetUsedFlag();
2140
2141   auto OwnedUnit = make_unique<DwarfTypeUnit>(
2142       InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2143       this, &InfoHolder, getDwoLineTable(CU));
2144   DwarfTypeUnit &NewTU = *OwnedUnit;
2145   DIE &UnitDie = NewTU.getUnitDie();
2146   TU = &NewTU;
2147   TypeUnitsUnderConstruction.push_back(
2148       std::make_pair(std::move(OwnedUnit), CTy));
2149
2150   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2151                 CU.getLanguage());
2152
2153   uint64_t Signature = makeTypeSignature(Identifier);
2154   NewTU.setTypeSignature(Signature);
2155
2156   if (useSplitDwarf())
2157     NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2158                       DwarfTypesDWOSectionSym);
2159   else {
2160     CU.applyStmtList(UnitDie);
2161     NewTU.initSection(
2162         Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2163   }
2164
2165   NewTU.setType(NewTU.createTypeDIE(CTy));
2166
2167   if (TopLevelType) {
2168     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2169     TypeUnitsUnderConstruction.clear();
2170
2171     // Types referencing entries in the address table cannot be placed in type
2172     // units.
2173     if (AddrPool.hasBeenUsed()) {
2174
2175       // Remove all the types built while building this type.
2176       // This is pessimistic as some of these types might not be dependent on
2177       // the type that used an address.
2178       for (const auto &TU : TypeUnitsToAdd)
2179         DwarfTypeUnits.erase(TU.second);
2180
2181       // Construct this type in the CU directly.
2182       // This is inefficient because all the dependent types will be rebuilt
2183       // from scratch, including building them in type units, discovering that
2184       // they depend on addresses, throwing them out and rebuilding them.
2185       CU.constructTypeDIE(RefDie, CTy);
2186       return;
2187     }
2188
2189     // If the type wasn't dependent on fission addresses, finish adding the type
2190     // and all its dependent types.
2191     for (auto &TU : TypeUnitsToAdd)
2192       InfoHolder.addUnit(std::move(TU.first));
2193   }
2194   CU.addDIETypeSignature(RefDie, NewTU);
2195 }
2196
2197 // Accelerator table mutators - add each name along with its companion
2198 // DIE to the proper table while ensuring that the name that we're going
2199 // to reference is in the string table. We do this since the names we
2200 // add may not only be identical to the names in the DIE.
2201 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2202   if (!useDwarfAccelTables())
2203     return;
2204   AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2205                      &Die);
2206 }
2207
2208 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2209   if (!useDwarfAccelTables())
2210     return;
2211   AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2212                     &Die);
2213 }
2214
2215 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2216   if (!useDwarfAccelTables())
2217     return;
2218   AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2219                          &Die);
2220 }
2221
2222 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2223   if (!useDwarfAccelTables())
2224     return;
2225   AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2226                      &Die);
2227 }