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