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