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