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