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