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