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 #include "ByteStreamer.h"
16 #include "DIEHash.h"
17 #include "DebugLocEntry.h"
18 #include "DebugLocStream.h"
19 #include "DwarfAccelTable.h"
20 #include "DwarfCompileUnit.h"
21 #include "DwarfExpression.h"
22 #include "DwarfFile.h"
23 #include "DwarfUnit.h"
24 #include "llvm/ADT/APInt.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/MapVector.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/BinaryFormat/Dwarf.h"
34 #include "llvm/CodeGen/AsmPrinter.h"
35 #include "llvm/CodeGen/DIE.h"
36 #include "llvm/CodeGen/LexicalScopes.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineOperand.h"
42 #include "llvm/CodeGen/TargetLoweringObjectFile.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/IR/Constants.h"
46 #include "llvm/IR/DebugInfoMetadata.h"
47 #include "llvm/IR/DebugLoc.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalVariable.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/MC/MCAsmInfo.h"
52 #include "llvm/MC/MCContext.h"
53 #include "llvm/MC/MCDwarf.h"
54 #include "llvm/MC/MCSection.h"
55 #include "llvm/MC/MCStreamer.h"
56 #include "llvm/MC/MCSymbol.h"
57 #include "llvm/MC/MCTargetOptions.h"
58 #include "llvm/MC/MachineLocation.h"
59 #include "llvm/MC/SectionKind.h"
60 #include "llvm/Pass.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/CommandLine.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/MD5.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/Timer.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Target/TargetOptions.h"
71 #include <algorithm>
72 #include <cassert>
73 #include <cstddef>
74 #include <cstdint>
75 #include <iterator>
76 #include <string>
77 #include <utility>
78 #include <vector>
79 
80 using namespace llvm;
81 
82 #define DEBUG_TYPE "dwarfdebug"
83 
84 static cl::opt<bool>
85 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
86                          cl::desc("Disable debug info printing"));
87 
88 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
89     "use-dwarf-ranges-base-address-specifier", cl::Hidden,
90     cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
91 
92 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
93                                            cl::Hidden,
94                                            cl::desc("Generate dwarf aranges"),
95                                            cl::init(false));
96 
97 static cl::opt<bool> SplitDwarfCrossCuReferences(
98     "split-dwarf-cross-cu-references", cl::Hidden,
99     cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
100 
101 enum DefaultOnOff { Default, Enable, Disable };
102 
103 static cl::opt<DefaultOnOff> UnknownLocations(
104     "use-unknown-locations", cl::Hidden,
105     cl::desc("Make an absence of debug location information explicit."),
106     cl::values(clEnumVal(Default, "At top of block or after label"),
107                clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
108     cl::init(Default));
109 
110 static cl::opt<DefaultOnOff>
111 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
112                  cl::desc("Output prototype dwarf accelerator tables."),
113                  cl::values(clEnumVal(Default, "Default for platform"),
114                             clEnumVal(Enable, "Enabled"),
115                             clEnumVal(Disable, "Disabled")),
116                  cl::init(Default));
117 
118 enum LinkageNameOption {
119   DefaultLinkageNames,
120   AllLinkageNames,
121   AbstractLinkageNames
122 };
123 
124 static cl::opt<LinkageNameOption>
125     DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
126                       cl::desc("Which DWARF linkage-name attributes to emit."),
127                       cl::values(clEnumValN(DefaultLinkageNames, "Default",
128                                             "Default for platform"),
129                                  clEnumValN(AllLinkageNames, "All", "All"),
130                                  clEnumValN(AbstractLinkageNames, "Abstract",
131                                             "Abstract subprograms")),
132                       cl::init(DefaultLinkageNames));
133 
134 static const char *const DWARFGroupName = "dwarf";
135 static const char *const DWARFGroupDescription = "DWARF Emission";
136 static const char *const DbgTimerName = "writer";
137 static const char *const DbgTimerDescription = "DWARF Debug Writer";
138 
139 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
140   BS.EmitInt8(
141       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
142                   : dwarf::OperationEncodingString(Op));
143 }
144 
145 void DebugLocDwarfExpression::emitSigned(int64_t Value) {
146   BS.EmitSLEB128(Value, Twine(Value));
147 }
148 
149 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
150   BS.EmitULEB128(Value, Twine(Value));
151 }
152 
153 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
154                                               unsigned MachineReg) {
155   // This information is not available while emitting .debug_loc entries.
156   return false;
157 }
158 
159 bool DbgVariable::isBlockByrefVariable() const {
160   assert(Var && "Invalid complex DbgVariable!");
161   return Var->getType().resolve()->isBlockByrefStruct();
162 }
163 
164 const DIType *DbgVariable::getType() const {
165   DIType *Ty = Var->getType().resolve();
166   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
167   // addresses instead.
168   if (Ty->isBlockByrefStruct()) {
169     /* Byref variables, in Blocks, are declared by the programmer as
170        "SomeType VarName;", but the compiler creates a
171        __Block_byref_x_VarName struct, and gives the variable VarName
172        either the struct, or a pointer to the struct, as its type.  This
173        is necessary for various behind-the-scenes things the compiler
174        needs to do with by-reference variables in blocks.
175 
176        However, as far as the original *programmer* is concerned, the
177        variable should still have type 'SomeType', as originally declared.
178 
179        The following function dives into the __Block_byref_x_VarName
180        struct to find the original type of the variable.  This will be
181        passed back to the code generating the type for the Debug
182        Information Entry for the variable 'VarName'.  'VarName' will then
183        have the original type 'SomeType' in its debug information.
184 
185        The original type 'SomeType' will be the type of the field named
186        'VarName' inside the __Block_byref_x_VarName struct.
187 
188        NOTE: In order for this to not completely fail on the debugger
189        side, the Debug Information Entry for the variable VarName needs to
190        have a DW_AT_location that tells the debugger how to unwind through
191        the pointers and __Block_byref_x_VarName struct to find the actual
192        value of the variable.  The function addBlockByrefType does this.  */
193     DIType *subType = Ty;
194     uint16_t tag = Ty->getTag();
195 
196     if (tag == dwarf::DW_TAG_pointer_type)
197       subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
198 
199     auto Elements = cast<DICompositeType>(subType)->getElements();
200     for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
201       auto *DT = cast<DIDerivedType>(Elements[i]);
202       if (getName() == DT->getName())
203         return resolve(DT->getBaseType());
204     }
205   }
206   return Ty;
207 }
208 
209 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
210   if (FrameIndexExprs.size() == 1)
211     return FrameIndexExprs;
212 
213   assert(llvm::all_of(FrameIndexExprs,
214                       [](const FrameIndexExpr &A) {
215                         return A.Expr->isFragment();
216                       }) &&
217          "multiple FI expressions without DW_OP_LLVM_fragment");
218   std::sort(FrameIndexExprs.begin(), FrameIndexExprs.end(),
219             [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
220               return A.Expr->getFragmentInfo()->OffsetInBits <
221                      B.Expr->getFragmentInfo()->OffsetInBits;
222             });
223 
224   return FrameIndexExprs;
225 }
226 
227 void DbgVariable::addMMIEntry(const DbgVariable &V) {
228   assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
229   assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
230   assert(V.Var == Var && "conflicting variable");
231   assert(V.IA == IA && "conflicting inlined-at location");
232 
233   assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
234   assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
235 
236   // FIXME: This logic should not be necessary anymore, as we now have proper
237   // deduplication. However, without it, we currently run into the assertion
238   // below, which means that we are likely dealing with broken input, i.e. two
239   // non-fragment entries for the same variable at different frame indices.
240   if (FrameIndexExprs.size()) {
241     auto *Expr = FrameIndexExprs.back().Expr;
242     if (!Expr || !Expr->isFragment())
243       return;
244   }
245 
246   for (const auto &FIE : V.FrameIndexExprs)
247     // Ignore duplicate entries.
248     if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
249           return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
250         }))
251       FrameIndexExprs.push_back(FIE);
252 
253   assert((FrameIndexExprs.size() == 1 ||
254           llvm::all_of(FrameIndexExprs,
255                        [](FrameIndexExpr &FIE) {
256                          return FIE.Expr && FIE.Expr->isFragment();
257                        })) &&
258          "conflicting locations for variable");
259 }
260 
261 static const DwarfAccelTable::Atom TypeAtoms[] = {
262     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
263     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
264     DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
265 
266 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
267     : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
268       InfoHolder(A, "info_string", DIEValueAllocator),
269       SkeletonHolder(A, "skel_string", DIEValueAllocator),
270       IsDarwin(A->TM.getTargetTriple().isOSDarwin()),
271       AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
272                                        dwarf::DW_FORM_data4)),
273       AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
274                                       dwarf::DW_FORM_data4)),
275       AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
276                                            dwarf::DW_FORM_data4)),
277       AccelTypes(TypeAtoms) {
278   const Triple &TT = Asm->TM.getTargetTriple();
279 
280   // Make sure we know our "debugger tuning."  The target option takes
281   // precedence; fall back to triple-based defaults.
282   if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
283     DebuggerTuning = Asm->TM.Options.DebuggerTuning;
284   else if (IsDarwin)
285     DebuggerTuning = DebuggerKind::LLDB;
286   else if (TT.isPS4CPU())
287     DebuggerTuning = DebuggerKind::SCE;
288   else
289     DebuggerTuning = DebuggerKind::GDB;
290 
291   // Turn on accelerator tables for LLDB by default.
292   if (DwarfAccelTables == Default)
293     HasDwarfAccelTables = tuneForLLDB();
294   else
295     HasDwarfAccelTables = DwarfAccelTables == Enable;
296 
297   HasAppleExtensionAttributes = tuneForLLDB();
298 
299   // Handle split DWARF.
300   HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
301 
302   // SCE defaults to linkage names only for abstract subprograms.
303   if (DwarfLinkageNames == DefaultLinkageNames)
304     UseAllLinkageNames = !tuneForSCE();
305   else
306     UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
307 
308   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
309   unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
310                                     : MMI->getModule()->getDwarfVersion();
311   // Use dwarf 4 by default if nothing is requested.
312   DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION;
313 
314   // Work around a GDB bug. GDB doesn't support the standard opcode;
315   // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
316   // is defined as of DWARF 3.
317   // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
318   // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
319   UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
320 
321   // GDB does not fully support the DWARF 4 representation for bitfields.
322   UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
323 
324   Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
325 }
326 
327 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
328 DwarfDebug::~DwarfDebug() = default;
329 
330 static bool isObjCClass(StringRef Name) {
331   return Name.startswith("+") || Name.startswith("-");
332 }
333 
334 static bool hasObjCCategory(StringRef Name) {
335   if (!isObjCClass(Name))
336     return false;
337 
338   return Name.find(") ") != StringRef::npos;
339 }
340 
341 static void getObjCClassCategory(StringRef In, StringRef &Class,
342                                  StringRef &Category) {
343   if (!hasObjCCategory(In)) {
344     Class = In.slice(In.find('[') + 1, In.find(' '));
345     Category = "";
346     return;
347   }
348 
349   Class = In.slice(In.find('[') + 1, In.find('('));
350   Category = In.slice(In.find('[') + 1, In.find(' '));
351 }
352 
353 static StringRef getObjCMethodName(StringRef In) {
354   return In.slice(In.find(' ') + 1, In.find(']'));
355 }
356 
357 // Add the various names to the Dwarf accelerator table names.
358 // TODO: Determine whether or not we should add names for programs
359 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
360 // is only slightly different than the lookup of non-standard ObjC names.
361 void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
362   if (!SP->isDefinition())
363     return;
364   addAccelName(SP->getName(), Die);
365 
366   // If the linkage name is different than the name, go ahead and output
367   // that as well into the name table.
368   if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName())
369     addAccelName(SP->getLinkageName(), Die);
370 
371   // If this is an Objective-C selector name add it to the ObjC accelerator
372   // too.
373   if (isObjCClass(SP->getName())) {
374     StringRef Class, Category;
375     getObjCClassCategory(SP->getName(), Class, Category);
376     addAccelObjC(Class, Die);
377     if (Category != "")
378       addAccelObjC(Category, Die);
379     // Also add the base method name to the name table.
380     addAccelName(getObjCMethodName(SP->getName()), Die);
381   }
382 }
383 
384 /// Check whether we should create a DIE for the given Scope, return true
385 /// if we don't create a DIE (the corresponding DIE is null).
386 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
387   if (Scope->isAbstractScope())
388     return false;
389 
390   // We don't create a DIE if there is no Range.
391   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
392   if (Ranges.empty())
393     return true;
394 
395   if (Ranges.size() > 1)
396     return false;
397 
398   // We don't create a DIE if we have a single Range and the end label
399   // is null.
400   return !getLabelAfterInsn(Ranges.front().second);
401 }
402 
403 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
404   F(CU);
405   if (auto *SkelCU = CU.getSkeleton())
406     if (CU.getCUNode()->getSplitDebugInlining())
407       F(*SkelCU);
408 }
409 
410 bool DwarfDebug::shareAcrossDWOCUs() const {
411   return SplitDwarfCrossCuReferences;
412 }
413 
414 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
415                                                      LexicalScope *Scope) {
416   assert(Scope && Scope->getScopeNode());
417   assert(Scope->isAbstractScope());
418   assert(!Scope->getInlinedAt());
419 
420   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
421 
422   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
423   // was inlined from another compile unit.
424   if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
425     // Avoid building the original CU if it won't be used
426     SrcCU.constructAbstractSubprogramScopeDIE(Scope);
427   else {
428     auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
429     if (auto *SkelCU = CU.getSkeleton()) {
430       (shareAcrossDWOCUs() ? CU : SrcCU)
431           .constructAbstractSubprogramScopeDIE(Scope);
432       if (CU.getCUNode()->getSplitDebugInlining())
433         SkelCU->constructAbstractSubprogramScopeDIE(Scope);
434     } else
435       CU.constructAbstractSubprogramScopeDIE(Scope);
436   }
437 }
438 
439 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
440   if (!U.hasDwarfPubSections())
441     return;
442 
443   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
444 }
445 
446 // Create new DwarfCompileUnit for the given metadata node with tag
447 // DW_TAG_compile_unit.
448 DwarfCompileUnit &
449 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
450   if (auto *CU = CUMap.lookup(DIUnit))
451     return *CU;
452   StringRef FN = DIUnit->getFilename();
453   CompilationDir = DIUnit->getDirectory();
454 
455   auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
456       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
457   DwarfCompileUnit &NewCU = *OwnedUnit;
458   DIE &Die = NewCU.getUnitDie();
459   InfoHolder.addUnit(std::move(OwnedUnit));
460   if (useSplitDwarf()) {
461     NewCU.setSkeleton(constructSkeletonCU(NewCU));
462     NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
463                   Asm->TM.Options.MCOptions.SplitDwarfFile);
464   }
465 
466   for (auto *IE : DIUnit->getImportedEntities())
467     NewCU.addImportedEntity(IE);
468 
469   // LTO with assembly output shares a single line table amongst multiple CUs.
470   // To avoid the compilation directory being ambiguous, let the line table
471   // explicitly describe the directory of all files, never relying on the
472   // compilation directory.
473   if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
474     Asm->OutStreamer->getContext().setMCLineTableCompilationDir(
475         NewCU.getUniqueID(), CompilationDir);
476 
477   StringRef Producer = DIUnit->getProducer();
478   StringRef Flags = DIUnit->getFlags();
479   if (!Flags.empty()) {
480     std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
481     NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
482   } else
483     NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
484 
485   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
486                 DIUnit->getSourceLanguage());
487   NewCU.addString(Die, dwarf::DW_AT_name, FN);
488 
489   if (!useSplitDwarf()) {
490     NewCU.initStmtList();
491 
492     // If we're using split dwarf the compilation dir is going to be in the
493     // skeleton CU and so we don't need to duplicate it here.
494     if (!CompilationDir.empty())
495       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
496 
497     addGnuPubAttributes(NewCU, Die);
498   }
499 
500   if (useAppleExtensionAttributes()) {
501     if (DIUnit->isOptimized())
502       NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
503 
504     StringRef Flags = DIUnit->getFlags();
505     if (!Flags.empty())
506       NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
507 
508     if (unsigned RVer = DIUnit->getRuntimeVersion())
509       NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
510                     dwarf::DW_FORM_data1, RVer);
511   }
512 
513   if (useSplitDwarf())
514     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
515   else
516     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
517 
518   if (DIUnit->getDWOId()) {
519     // This CU is either a clang module DWO or a skeleton CU.
520     NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
521                   DIUnit->getDWOId());
522     if (!DIUnit->getSplitDebugFilename().empty())
523       // This is a prefabricated skeleton CU.
524       NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
525                       DIUnit->getSplitDebugFilename());
526   }
527 
528   CUMap.insert({DIUnit, &NewCU});
529   CUDieMap.insert({&Die, &NewCU});
530   return NewCU;
531 }
532 
533 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
534                                                   const DIImportedEntity *N) {
535   if (isa<DILocalScope>(N->getScope()))
536     return;
537   if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
538     D->addChild(TheCU.constructImportedEntityDIE(N));
539 }
540 
541 /// Sort and unique GVEs by comparing their fragment offset.
542 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
543 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
544   std::sort(GVEs.begin(), GVEs.end(),
545             [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
546               // Sort order: first null exprs, then exprs without fragment
547               // info, then sort by fragment offset in bits.
548               // FIXME: Come up with a more comprehensive comparator so
549               // the sorting isn't non-deterministic, and so the following
550               // std::unique call works correctly.
551               if (!A.Expr || !B.Expr)
552                 return !!B.Expr;
553               auto FragmentA = A.Expr->getFragmentInfo();
554               auto FragmentB = B.Expr->getFragmentInfo();
555               if (!FragmentA || !FragmentB)
556                 return !!FragmentB;
557               return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
558             });
559   GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
560                          [](DwarfCompileUnit::GlobalExpr A,
561                             DwarfCompileUnit::GlobalExpr B) {
562                            return A.Expr == B.Expr;
563                          }),
564              GVEs.end());
565   return GVEs;
566 }
567 
568 // Emit all Dwarf sections that should come prior to the content. Create
569 // global DIEs and emit initial debug info sections. This is invoked by
570 // the target AsmPrinter.
571 void DwarfDebug::beginModule() {
572   NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
573                      DWARFGroupDescription, TimePassesIsEnabled);
574   if (DisableDebugInfoPrinting)
575     return;
576 
577   const Module *M = MMI->getModule();
578 
579   unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
580                                        M->debug_compile_units_end());
581   // Tell MMI whether we have debug info.
582   MMI->setDebugInfoAvailability(NumDebugCUs > 0);
583   SingleCU = NumDebugCUs == 1;
584   DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
585       GVMap;
586   for (const GlobalVariable &Global : M->globals()) {
587     SmallVector<DIGlobalVariableExpression *, 1> GVs;
588     Global.getDebugInfo(GVs);
589     for (auto *GVE : GVs)
590       GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
591   }
592 
593   for (DICompileUnit *CUNode : M->debug_compile_units()) {
594     // FIXME: Move local imported entities into a list attached to the
595     // subprogram, then this search won't be needed and a
596     // getImportedEntities().empty() test should go below with the rest.
597     bool HasNonLocalImportedEntities = llvm::any_of(
598         CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
599           return !isa<DILocalScope>(IE->getScope());
600         });
601 
602     if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
603         CUNode->getRetainedTypes().empty() &&
604         CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
605       continue;
606 
607     DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
608 
609     // Global Variables.
610     for (auto *GVE : CUNode->getGlobalVariables()) {
611       // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
612       // already know about the variable and it isn't adding a constant
613       // expression.
614       auto &GVMapEntry = GVMap[GVE->getVariable()];
615       auto *Expr = GVE->getExpression();
616       if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
617         GVMapEntry.push_back({nullptr, Expr});
618     }
619     DenseSet<DIGlobalVariable *> Processed;
620     for (auto *GVE : CUNode->getGlobalVariables()) {
621       DIGlobalVariable *GV = GVE->getVariable();
622       if (Processed.insert(GV).second)
623         CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
624     }
625 
626     for (auto *Ty : CUNode->getEnumTypes()) {
627       // The enum types array by design contains pointers to
628       // MDNodes rather than DIRefs. Unique them here.
629       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
630     }
631     for (auto *Ty : CUNode->getRetainedTypes()) {
632       // The retained types array by design contains pointers to
633       // MDNodes rather than DIRefs. Unique them here.
634       if (DIType *RT = dyn_cast<DIType>(Ty))
635           // There is no point in force-emitting a forward declaration.
636           CU.getOrCreateTypeDIE(RT);
637     }
638     // Emit imported_modules last so that the relevant context is already
639     // available.
640     for (auto *IE : CUNode->getImportedEntities())
641       constructAndAddImportedEntityDIE(CU, IE);
642   }
643 }
644 
645 void DwarfDebug::finishVariableDefinitions() {
646   for (const auto &Var : ConcreteVariables) {
647     DIE *VariableDie = Var->getDIE();
648     assert(VariableDie);
649     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
650     // in the ConcreteVariables list, rather than looking it up again here.
651     // DIE::getUnit isn't simple - it walks parent pointers, etc.
652     DwarfCompileUnit *Unit = CUDieMap.lookup(VariableDie->getUnitDie());
653     assert(Unit);
654     Unit->finishVariableDefinition(*Var);
655   }
656 }
657 
658 void DwarfDebug::finishSubprogramDefinitions() {
659   for (const DISubprogram *SP : ProcessedSPNodes) {
660     assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
661     forBothCUs(
662         getOrCreateDwarfCompileUnit(SP->getUnit()),
663         [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
664   }
665 }
666 
667 void DwarfDebug::finalizeModuleInfo() {
668   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
669 
670   finishSubprogramDefinitions();
671 
672   finishVariableDefinitions();
673 
674   // Include the DWO file name in the hash if there's more than one CU.
675   // This handles ThinLTO's situation where imported CUs may very easily be
676   // duplicate with the same CU partially imported into another ThinLTO unit.
677   StringRef DWOName;
678   if (CUMap.size() > 1)
679     DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
680 
681   // Handle anything that needs to be done on a per-unit basis after
682   // all other generation.
683   for (const auto &P : CUMap) {
684     auto &TheCU = *P.second;
685     // Emit DW_AT_containing_type attribute to connect types with their
686     // vtable holding type.
687     TheCU.constructContainingTypeDIEs();
688 
689     // Add CU specific attributes if we need to add any.
690     // If we're splitting the dwarf out now that we've got the entire
691     // CU then add the dwo id to it.
692     auto *SkCU = TheCU.getSkeleton();
693     if (useSplitDwarf()) {
694       // Emit a unique identifier for this CU.
695       uint64_t ID =
696           DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
697       TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
698                     dwarf::DW_FORM_data8, ID);
699       SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
700                     dwarf::DW_FORM_data8, ID);
701 
702       // We don't keep track of which addresses are used in which CU so this
703       // is a bit pessimistic under LTO.
704       if (!AddrPool.isEmpty()) {
705         const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
706         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
707                               Sym, Sym);
708       }
709       if (!SkCU->getRangeLists().empty()) {
710         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
711         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
712                               Sym, Sym);
713       }
714     }
715 
716     // If we have code split among multiple sections or non-contiguous
717     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
718     // remain in the .o file, otherwise add a DW_AT_low_pc.
719     // FIXME: We should use ranges allow reordering of code ala
720     // .subsections_via_symbols in mach-o. This would mean turning on
721     // ranges for all subprogram DIEs for mach-o.
722     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
723     if (unsigned NumRanges = TheCU.getRanges().size()) {
724       if (NumRanges > 1)
725         // A DW_AT_low_pc attribute may also be specified in combination with
726         // DW_AT_ranges to specify the default base address for use in
727         // location lists (see Section 2.6.2) and range lists (see Section
728         // 2.17.3).
729         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
730       else
731         U.setBaseAddress(TheCU.getRanges().front().getStart());
732       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
733     }
734 
735     auto *CUNode = cast<DICompileUnit>(P.first);
736     // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
737     if (CUNode->getMacros())
738       U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
739                         U.getMacroLabelBegin(),
740                         TLOF.getDwarfMacinfoSection()->getBeginSymbol());
741   }
742 
743   // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
744   for (auto *CUNode : MMI->getModule()->debug_compile_units())
745     if (CUNode->getDWOId())
746       getOrCreateDwarfCompileUnit(CUNode);
747 
748   // Compute DIE offsets and sizes.
749   InfoHolder.computeSizeAndOffsets();
750   if (useSplitDwarf())
751     SkeletonHolder.computeSizeAndOffsets();
752 }
753 
754 // Emit all Dwarf sections that should come after the content.
755 void DwarfDebug::endModule() {
756   assert(CurFn == nullptr);
757   assert(CurMI == nullptr);
758 
759   // If we aren't actually generating debug info (check beginModule -
760   // conditionalized on !DisableDebugInfoPrinting and the presence of the
761   // llvm.dbg.cu metadata node)
762   if (!MMI->hasDebugInfo())
763     return;
764 
765   // Finalize the debug info for the module.
766   finalizeModuleInfo();
767 
768   emitDebugStr();
769 
770   if (useSplitDwarf())
771     emitDebugLocDWO();
772   else
773     // Emit info into a debug loc section.
774     emitDebugLoc();
775 
776   // Corresponding abbreviations into a abbrev section.
777   emitAbbreviations();
778 
779   // Emit all the DIEs into a debug info section.
780   emitDebugInfo();
781 
782   // Emit info into a debug aranges section.
783   if (GenerateARangeSection)
784     emitDebugARanges();
785 
786   // Emit info into a debug ranges section.
787   emitDebugRanges();
788 
789   // Emit info into a debug macinfo section.
790   emitDebugMacinfo();
791 
792   if (useSplitDwarf()) {
793     emitDebugStrDWO();
794     emitDebugInfoDWO();
795     emitDebugAbbrevDWO();
796     emitDebugLineDWO();
797     // Emit DWO addresses.
798     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
799   }
800 
801   // Emit info into the dwarf accelerator table sections.
802   if (useDwarfAccelTables()) {
803     emitAccelNames();
804     emitAccelObjC();
805     emitAccelNamespaces();
806     emitAccelTypes();
807   }
808 
809   // Emit the pubnames and pubtypes sections if requested.
810   emitDebugPubSections();
811 
812   // clean up.
813   // FIXME: AbstractVariables.clear();
814 }
815 
816 void DwarfDebug::ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable IV,
817                                                  const MDNode *ScopeNode) {
818   const DILocalVariable *Cleansed = nullptr;
819   if (CU.getExistingAbstractVariable(IV, Cleansed))
820     return;
821 
822   CU.createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
823                                        cast<DILocalScope>(ScopeNode)));
824 }
825 
826 void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU,
827     InlinedVariable IV, const MDNode *ScopeNode) {
828   const DILocalVariable *Cleansed = nullptr;
829   if (CU.getExistingAbstractVariable(IV, Cleansed))
830     return;
831 
832   if (LexicalScope *Scope =
833           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
834     CU.createAbstractVariable(Cleansed, Scope);
835 }
836 
837 // Collect variable information from side table maintained by MF.
838 void DwarfDebug::collectVariableInfoFromMFTable(
839     DwarfCompileUnit &TheCU, DenseSet<InlinedVariable> &Processed) {
840   SmallDenseMap<InlinedVariable, DbgVariable *> MFVars;
841   for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
842     if (!VI.Var)
843       continue;
844     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
845            "Expected inlined-at fields to agree");
846 
847     InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
848     Processed.insert(Var);
849     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
850 
851     // If variable scope is not found then skip this variable.
852     if (!Scope)
853       continue;
854 
855     ensureAbstractVariableIsCreatedIfScoped(TheCU, Var, Scope->getScopeNode());
856     auto RegVar = llvm::make_unique<DbgVariable>(Var.first, Var.second);
857     RegVar->initializeMMI(VI.Expr, VI.Slot);
858     if (DbgVariable *DbgVar = MFVars.lookup(Var))
859       DbgVar->addMMIEntry(*RegVar);
860     else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
861       MFVars.insert({Var, RegVar.get()});
862       ConcreteVariables.push_back(std::move(RegVar));
863     }
864   }
865 }
866 
867 // Get .debug_loc entry for the instruction range starting at MI.
868 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
869   const DIExpression *Expr = MI->getDebugExpression();
870   assert(MI->getNumOperands() == 4);
871   if (MI->getOperand(0).isReg()) {
872     auto RegOp = MI->getOperand(0);
873     auto Op1 = MI->getOperand(1);
874     // If the second operand is an immediate, this is a
875     // register-indirect address.
876     assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
877     MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
878     return DebugLocEntry::Value(Expr, MLoc);
879   }
880   if (MI->getOperand(0).isImm())
881     return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
882   if (MI->getOperand(0).isFPImm())
883     return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
884   if (MI->getOperand(0).isCImm())
885     return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
886 
887   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
888 }
889 
890 /// \brief If this and Next are describing different fragments of the same
891 /// variable, merge them by appending Next's values to the current
892 /// list of values.
893 /// Return true if the merge was successful.
894 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
895   if (Begin == Next.Begin) {
896     auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
897     auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
898     if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
899       return false;
900 
901     // We can only merge entries if none of the fragments overlap any others.
902     // In doing so, we can take advantage of the fact that both lists are
903     // sorted.
904     for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
905       for (; j < Next.Values.size(); ++j) {
906         int res = DebugHandlerBase::fragmentCmp(
907             cast<DIExpression>(Values[i].Expression),
908             cast<DIExpression>(Next.Values[j].Expression));
909         if (res == 0) // The two expressions overlap, we can't merge.
910           return false;
911         // Values[i] is entirely before Next.Values[j],
912         // so go back to the next entry of Values.
913         else if (res == -1)
914           break;
915         // Next.Values[j] is entirely before Values[i], so go on to the
916         // next entry of Next.Values.
917       }
918     }
919 
920     addValues(Next.Values);
921     End = Next.End;
922     return true;
923   }
924   return false;
925 }
926 
927 /// Build the location list for all DBG_VALUEs in the function that
928 /// describe the same variable.  If the ranges of several independent
929 /// fragments of the same variable overlap partially, split them up and
930 /// combine the ranges. The resulting DebugLocEntries are will have
931 /// strict monotonically increasing begin addresses and will never
932 /// overlap.
933 //
934 // Input:
935 //
936 //   Ranges History [var, loc, fragment ofs size]
937 // 0 |      [x, (reg0, fragment 0, 32)]
938 // 1 | |    [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
939 // 2 | |    ...
940 // 3   |    [clobber reg0]
941 // 4        [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
942 //                                     x.
943 //
944 // Output:
945 //
946 // [0-1]    [x, (reg0, fragment  0, 32)]
947 // [1-3]    [x, (reg0, fragment  0, 32), (reg1, fragment 32, 32)]
948 // [3-4]    [x, (reg1, fragment 32, 32)]
949 // [4- ]    [x, (mem,  fragment  0, 64)]
950 void
951 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
952                               const DbgValueHistoryMap::InstrRanges &Ranges) {
953   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
954 
955   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
956     const MachineInstr *Begin = I->first;
957     const MachineInstr *End = I->second;
958     assert(Begin->isDebugValue() && "Invalid History entry");
959 
960     // Check if a variable is inaccessible in this range.
961     if (Begin->getNumOperands() > 1 &&
962         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
963       OpenRanges.clear();
964       continue;
965     }
966 
967     // If this fragment overlaps with any open ranges, truncate them.
968     const DIExpression *DIExpr = Begin->getDebugExpression();
969     auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
970       return fragmentsOverlap(DIExpr, R.getExpression());
971     });
972     OpenRanges.erase(Last, OpenRanges.end());
973 
974     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
975     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
976 
977     const MCSymbol *EndLabel;
978     if (End != nullptr)
979       EndLabel = getLabelAfterInsn(End);
980     else if (std::next(I) == Ranges.end())
981       EndLabel = Asm->getFunctionEnd();
982     else
983       EndLabel = getLabelBeforeInsn(std::next(I)->first);
984     assert(EndLabel && "Forgot label after instruction ending a range!");
985 
986     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
987 
988     auto Value = getDebugLocValue(Begin);
989     DebugLocEntry Loc(StartLabel, EndLabel, Value);
990     bool couldMerge = false;
991 
992     // If this is a fragment, it may belong to the current DebugLocEntry.
993     if (DIExpr->isFragment()) {
994       // Add this value to the list of open ranges.
995       OpenRanges.push_back(Value);
996 
997       // Attempt to add the fragment to the last entry.
998       if (!DebugLoc.empty())
999         if (DebugLoc.back().MergeValues(Loc))
1000           couldMerge = true;
1001     }
1002 
1003     if (!couldMerge) {
1004       // Need to add a new DebugLocEntry. Add all values from still
1005       // valid non-overlapping fragments.
1006       if (OpenRanges.size())
1007         Loc.addValues(OpenRanges);
1008 
1009       DebugLoc.push_back(std::move(Loc));
1010     }
1011 
1012     // Attempt to coalesce the ranges of two otherwise identical
1013     // DebugLocEntries.
1014     auto CurEntry = DebugLoc.rbegin();
1015     DEBUG({
1016       dbgs() << CurEntry->getValues().size() << " Values:\n";
1017       for (auto &Value : CurEntry->getValues())
1018         Value.dump();
1019       dbgs() << "-----\n";
1020     });
1021 
1022     auto PrevEntry = std::next(CurEntry);
1023     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1024       DebugLoc.pop_back();
1025   }
1026 }
1027 
1028 DbgVariable *DwarfDebug::createConcreteVariable(DwarfCompileUnit &TheCU,
1029                                                 LexicalScope &Scope,
1030                                                 InlinedVariable IV) {
1031   ensureAbstractVariableIsCreatedIfScoped(TheCU, IV, Scope.getScopeNode());
1032   ConcreteVariables.push_back(
1033       llvm::make_unique<DbgVariable>(IV.first, IV.second));
1034   InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
1035   return ConcreteVariables.back().get();
1036 }
1037 
1038 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1039 /// enclosing lexical scope. The check ensures there are no other instructions
1040 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1041 /// either open or otherwise rolls off the end of the scope.
1042 static bool validThroughout(LexicalScopes &LScopes,
1043                             const MachineInstr *DbgValue,
1044                             const MachineInstr *RangeEnd) {
1045   assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1046   auto MBB = DbgValue->getParent();
1047   auto DL = DbgValue->getDebugLoc();
1048   auto *LScope = LScopes.findLexicalScope(DL);
1049   // Scope doesn't exist; this is a dead DBG_VALUE.
1050   if (!LScope)
1051     return false;
1052   auto &LSRange = LScope->getRanges();
1053   if (LSRange.size() == 0)
1054     return false;
1055 
1056   // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1057   const MachineInstr *LScopeBegin = LSRange.front().first;
1058   // Early exit if the lexical scope begins outside of the current block.
1059   if (LScopeBegin->getParent() != MBB)
1060     return false;
1061   MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1062   for (++Pred; Pred != MBB->rend(); ++Pred) {
1063     if (Pred->getFlag(MachineInstr::FrameSetup))
1064       break;
1065     auto PredDL = Pred->getDebugLoc();
1066     if (!PredDL || Pred->isMetaInstruction())
1067       continue;
1068     // Check whether the instruction preceding the DBG_VALUE is in the same
1069     // (sub)scope as the DBG_VALUE.
1070     if (DL->getScope() == PredDL->getScope())
1071       return false;
1072     auto *PredScope = LScopes.findLexicalScope(PredDL);
1073     if (!PredScope || LScope->dominates(PredScope))
1074       return false;
1075   }
1076 
1077   // If the range of the DBG_VALUE is open-ended, report success.
1078   if (!RangeEnd)
1079     return true;
1080 
1081   // Fail if there are instructions belonging to our scope in another block.
1082   const MachineInstr *LScopeEnd = LSRange.back().second;
1083   if (LScopeEnd->getParent() != MBB)
1084     return false;
1085 
1086   // Single, constant DBG_VALUEs in the prologue are promoted to be live
1087   // throughout the function. This is a hack, presumably for DWARF v2 and not
1088   // necessarily correct. It would be much better to use a dbg.declare instead
1089   // if we know the constant is live throughout the scope.
1090   if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1091     return true;
1092 
1093   return false;
1094 }
1095 
1096 // Find variables for each lexical scope.
1097 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
1098                                      const DISubprogram *SP,
1099                                      DenseSet<InlinedVariable> &Processed) {
1100   // Grab the variable info that was squirreled away in the MMI side-table.
1101   collectVariableInfoFromMFTable(TheCU, Processed);
1102 
1103   for (const auto &I : DbgValues) {
1104     InlinedVariable IV = I.first;
1105     if (Processed.count(IV))
1106       continue;
1107 
1108     // Instruction ranges, specifying where IV is accessible.
1109     const auto &Ranges = I.second;
1110     if (Ranges.empty())
1111       continue;
1112 
1113     LexicalScope *Scope = nullptr;
1114     if (const DILocation *IA = IV.second)
1115       Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
1116     else
1117       Scope = LScopes.findLexicalScope(IV.first->getScope());
1118     // If variable scope is not found then skip this variable.
1119     if (!Scope)
1120       continue;
1121 
1122     Processed.insert(IV);
1123     DbgVariable *RegVar = createConcreteVariable(TheCU, *Scope, IV);
1124 
1125     const MachineInstr *MInsn = Ranges.front().first;
1126     assert(MInsn->isDebugValue() && "History must begin with debug value");
1127 
1128     // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1129     if (Ranges.size() == 1 &&
1130         validThroughout(LScopes, MInsn, Ranges.front().second)) {
1131       RegVar->initializeDbgValue(MInsn);
1132       continue;
1133     }
1134 
1135     // Handle multiple DBG_VALUE instructions describing one variable.
1136     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1137 
1138     // Build the location list for this variable.
1139     SmallVector<DebugLocEntry, 8> Entries;
1140     buildLocationList(Entries, Ranges);
1141 
1142     // If the variable has a DIBasicType, extract it.  Basic types cannot have
1143     // unique identifiers, so don't bother resolving the type with the
1144     // identifier map.
1145     const DIBasicType *BT = dyn_cast<DIBasicType>(
1146         static_cast<const Metadata *>(IV.first->getType()));
1147 
1148     // Finalize the entry by lowering it into a DWARF bytestream.
1149     for (auto &Entry : Entries)
1150       Entry.finalize(*Asm, List, BT);
1151   }
1152 
1153   // Collect info for variables that were optimized out.
1154   for (const DILocalVariable *DV : SP->getVariables()) {
1155     if (Processed.insert(InlinedVariable(DV, nullptr)).second)
1156       if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
1157         createConcreteVariable(TheCU, *Scope, InlinedVariable(DV, nullptr));
1158   }
1159 }
1160 
1161 // Process beginning of an instruction.
1162 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1163   DebugHandlerBase::beginInstruction(MI);
1164   assert(CurMI);
1165 
1166   const auto *SP = MI->getMF()->getFunction().getSubprogram();
1167   if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1168     return;
1169 
1170   // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1171   if (MI->isMetaInstruction())
1172     return;
1173   const DebugLoc &DL = MI->getDebugLoc();
1174   // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1175   // the last line number actually emitted, to see if it was line 0.
1176   unsigned LastAsmLine =
1177       Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1178 
1179   if (DL == PrevInstLoc) {
1180     // If we have an ongoing unspecified location, nothing to do here.
1181     if (!DL)
1182       return;
1183     // We have an explicit location, same as the previous location.
1184     // But we might be coming back to it after a line 0 record.
1185     if (LastAsmLine == 0 && DL.getLine() != 0) {
1186       // Reinstate the source location but not marked as a statement.
1187       const MDNode *Scope = DL.getScope();
1188       recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1189     }
1190     return;
1191   }
1192 
1193   if (!DL) {
1194     // We have an unspecified location, which might want to be line 0.
1195     // If we have already emitted a line-0 record, don't repeat it.
1196     if (LastAsmLine == 0)
1197       return;
1198     // If user said Don't Do That, don't do that.
1199     if (UnknownLocations == Disable)
1200       return;
1201     // See if we have a reason to emit a line-0 record now.
1202     // Reasons to emit a line-0 record include:
1203     // - User asked for it (UnknownLocations).
1204     // - Instruction has a label, so it's referenced from somewhere else,
1205     //   possibly debug information; we want it to have a source location.
1206     // - Instruction is at the top of a block; we don't want to inherit the
1207     //   location from the physically previous (maybe unrelated) block.
1208     if (UnknownLocations == Enable || PrevLabel ||
1209         (PrevInstBB && PrevInstBB != MI->getParent())) {
1210       // Preserve the file and column numbers, if we can, to save space in
1211       // the encoded line table.
1212       // Do not update PrevInstLoc, it remembers the last non-0 line.
1213       const MDNode *Scope = nullptr;
1214       unsigned Column = 0;
1215       if (PrevInstLoc) {
1216         Scope = PrevInstLoc.getScope();
1217         Column = PrevInstLoc.getCol();
1218       }
1219       recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1220     }
1221     return;
1222   }
1223 
1224   // We have an explicit location, different from the previous location.
1225   // Don't repeat a line-0 record, but otherwise emit the new location.
1226   // (The new location might be an explicit line 0, which we do emit.)
1227   if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
1228     return;
1229   unsigned Flags = 0;
1230   if (DL == PrologEndLoc) {
1231     Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1232     PrologEndLoc = DebugLoc();
1233   }
1234   // If the line changed, we call that a new statement; unless we went to
1235   // line 0 and came back, in which case it is not a new statement.
1236   unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1237   if (DL.getLine() && DL.getLine() != OldLine)
1238     Flags |= DWARF2_FLAG_IS_STMT;
1239 
1240   const MDNode *Scope = DL.getScope();
1241   recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1242 
1243   // If we're not at line 0, remember this location.
1244   if (DL.getLine())
1245     PrevInstLoc = DL;
1246 }
1247 
1248 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1249   // First known non-DBG_VALUE and non-frame setup location marks
1250   // the beginning of the function body.
1251   for (const auto &MBB : *MF)
1252     for (const auto &MI : MBB)
1253       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1254           MI.getDebugLoc())
1255         return MI.getDebugLoc();
1256   return DebugLoc();
1257 }
1258 
1259 // Gather pre-function debug information.  Assumes being called immediately
1260 // after the function entry point has been emitted.
1261 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1262   CurFn = MF;
1263 
1264   auto *SP = MF->getFunction().getSubprogram();
1265   assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1266   if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1267     return;
1268 
1269   DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1270 
1271   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1272   // belongs to so that we add to the correct per-cu line table in the
1273   // non-asm case.
1274   if (Asm->OutStreamer->hasRawTextSupport())
1275     // Use a single line table if we are generating assembly.
1276     Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1277   else
1278     Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1279 
1280   // Record beginning of function.
1281   PrologEndLoc = findPrologueEndLoc(MF);
1282   if (PrologEndLoc) {
1283     // We'd like to list the prologue as "not statements" but GDB behaves
1284     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1285     auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1286     recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1287   }
1288 }
1289 
1290 void DwarfDebug::skippedNonDebugFunction() {
1291   // If we don't have a subprogram for this function then there will be a hole
1292   // in the range information. Keep note of this by setting the previously used
1293   // section to nullptr.
1294   PrevCU = nullptr;
1295   CurFn = nullptr;
1296 }
1297 
1298 // Gather and emit post-function debug information.
1299 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1300   const DISubprogram *SP = MF->getFunction().getSubprogram();
1301 
1302   assert(CurFn == MF &&
1303       "endFunction should be called with the same function as beginFunction");
1304 
1305   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1306   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1307 
1308   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1309   assert(!FnScope || SP == FnScope->getScopeNode());
1310   DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1311 
1312   DenseSet<InlinedVariable> ProcessedVars;
1313   collectVariableInfo(TheCU, SP, ProcessedVars);
1314 
1315   // Add the range of this function to the list of ranges for the CU.
1316   TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1317 
1318   // Under -gmlt, skip building the subprogram if there are no inlined
1319   // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1320   // is still needed as we need its source location.
1321   if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1322       TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1323       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1324     assert(InfoHolder.getScopeVariables().empty());
1325     PrevLabel = nullptr;
1326     CurFn = nullptr;
1327     return;
1328   }
1329 
1330 #ifndef NDEBUG
1331   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1332 #endif
1333   // Construct abstract scopes.
1334   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1335     auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1336     // Collect info for variables that were optimized out.
1337     for (const DILocalVariable *DV : SP->getVariables()) {
1338       if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
1339         continue;
1340       ensureAbstractVariableIsCreated(TheCU, InlinedVariable(DV, nullptr),
1341                                       DV->getScope());
1342       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1343              && "ensureAbstractVariableIsCreated inserted abstract scopes");
1344     }
1345     constructAbstractSubprogramScopeDIE(TheCU, AScope);
1346   }
1347 
1348   ProcessedSPNodes.insert(SP);
1349   TheCU.constructSubprogramScopeDIE(SP, FnScope);
1350   if (auto *SkelCU = TheCU.getSkeleton())
1351     if (!LScopes.getAbstractScopesList().empty() &&
1352         TheCU.getCUNode()->getSplitDebugInlining())
1353       SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1354 
1355   // Clear debug info
1356   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1357   // DbgVariables except those that are also in AbstractVariables (since they
1358   // can be used cross-function)
1359   InfoHolder.getScopeVariables().clear();
1360   PrevLabel = nullptr;
1361   CurFn = nullptr;
1362 }
1363 
1364 // Register a source line with debug info. Returns the  unique label that was
1365 // emitted and which provides correspondence to the source line list.
1366 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1367                                   unsigned Flags) {
1368   StringRef Fn;
1369   unsigned Src = 1;
1370   unsigned Discriminator = 0;
1371   if (auto *Scope = cast_or_null<DIScope>(S)) {
1372     Fn = Scope->getFilename();
1373     if (Line != 0 && getDwarfVersion() >= 4)
1374       if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1375         Discriminator = LBF->getDiscriminator();
1376 
1377     unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
1378     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1379               .getOrCreateSourceID(Scope->getFile());
1380   }
1381   Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1382                                           Discriminator, Fn);
1383 }
1384 
1385 //===----------------------------------------------------------------------===//
1386 // Emit Methods
1387 //===----------------------------------------------------------------------===//
1388 
1389 // Emit the debug info section.
1390 void DwarfDebug::emitDebugInfo() {
1391   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1392   Holder.emitUnits(/* UseOffsets */ false);
1393 }
1394 
1395 // Emit the abbreviation section.
1396 void DwarfDebug::emitAbbreviations() {
1397   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1398 
1399   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1400 }
1401 
1402 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, MCSection *Section,
1403                            StringRef TableName) {
1404   Accel.FinalizeTable(Asm, TableName);
1405   Asm->OutStreamer->SwitchSection(Section);
1406 
1407   // Emit the full data.
1408   Accel.emit(Asm, Section->getBeginSymbol(), this);
1409 }
1410 
1411 // Emit visible names into a hashed accelerator table section.
1412 void DwarfDebug::emitAccelNames() {
1413   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1414             "Names");
1415 }
1416 
1417 // Emit objective C classes and categories into a hashed accelerator table
1418 // section.
1419 void DwarfDebug::emitAccelObjC() {
1420   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1421             "ObjC");
1422 }
1423 
1424 // Emit namespace dies into a hashed accelerator table.
1425 void DwarfDebug::emitAccelNamespaces() {
1426   emitAccel(AccelNamespace,
1427             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1428             "namespac");
1429 }
1430 
1431 // Emit type dies into a hashed accelerator table.
1432 void DwarfDebug::emitAccelTypes() {
1433   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1434             "types");
1435 }
1436 
1437 // Public name handling.
1438 // The format for the various pubnames:
1439 //
1440 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1441 // for the DIE that is named.
1442 //
1443 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1444 // into the CU and the index value is computed according to the type of value
1445 // for the DIE that is named.
1446 //
1447 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1448 // it's the offset within the debug_info/debug_types dwo section, however, the
1449 // reference in the pubname header doesn't change.
1450 
1451 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1452 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1453                                                         const DIE *Die) {
1454   // Entities that ended up only in a Type Unit reference the CU instead (since
1455   // the pub entry has offsets within the CU there's no real offset that can be
1456   // provided anyway). As it happens all such entities (namespaces and types,
1457   // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
1458   // not to be true it would be necessary to persist this information from the
1459   // point at which the entry is added to the index data structure - since by
1460   // the time the index is built from that, the original type/namespace DIE in a
1461   // type unit has already been destroyed so it can't be queried for properties
1462   // like tag, etc.
1463   if (Die->getTag() == dwarf::DW_TAG_compile_unit)
1464     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
1465                                           dwarf::GIEL_EXTERNAL);
1466   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1467 
1468   // We could have a specification DIE that has our most of our knowledge,
1469   // look for that now.
1470   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1471     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1472     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1473       Linkage = dwarf::GIEL_EXTERNAL;
1474   } else if (Die->findAttribute(dwarf::DW_AT_external))
1475     Linkage = dwarf::GIEL_EXTERNAL;
1476 
1477   switch (Die->getTag()) {
1478   case dwarf::DW_TAG_class_type:
1479   case dwarf::DW_TAG_structure_type:
1480   case dwarf::DW_TAG_union_type:
1481   case dwarf::DW_TAG_enumeration_type:
1482     return dwarf::PubIndexEntryDescriptor(
1483         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1484                               ? dwarf::GIEL_STATIC
1485                               : dwarf::GIEL_EXTERNAL);
1486   case dwarf::DW_TAG_typedef:
1487   case dwarf::DW_TAG_base_type:
1488   case dwarf::DW_TAG_subrange_type:
1489     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1490   case dwarf::DW_TAG_namespace:
1491     return dwarf::GIEK_TYPE;
1492   case dwarf::DW_TAG_subprogram:
1493     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1494   case dwarf::DW_TAG_variable:
1495     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1496   case dwarf::DW_TAG_enumerator:
1497     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1498                                           dwarf::GIEL_STATIC);
1499   default:
1500     return dwarf::GIEK_NONE;
1501   }
1502 }
1503 
1504 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
1505 /// pubtypes sections.
1506 void DwarfDebug::emitDebugPubSections() {
1507   for (const auto &NU : CUMap) {
1508     DwarfCompileUnit *TheU = NU.second;
1509     if (!TheU->hasDwarfPubSections())
1510       continue;
1511 
1512     bool GnuStyle = TheU->getCUNode()->getGnuPubnames();
1513 
1514     Asm->OutStreamer->SwitchSection(
1515         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1516                  : Asm->getObjFileLowering().getDwarfPubNamesSection());
1517     emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
1518 
1519     Asm->OutStreamer->SwitchSection(
1520         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1521                  : Asm->getObjFileLowering().getDwarfPubTypesSection());
1522     emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
1523   }
1524 }
1525 
1526 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
1527                                      DwarfCompileUnit *TheU,
1528                                      const StringMap<const DIE *> &Globals) {
1529   if (auto *Skeleton = TheU->getSkeleton())
1530     TheU = Skeleton;
1531 
1532   // Emit the header.
1533   Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1534   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1535   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1536   Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1537 
1538   Asm->OutStreamer->EmitLabel(BeginLabel);
1539 
1540   Asm->OutStreamer->AddComment("DWARF Version");
1541   Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1542 
1543   Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1544   Asm->emitDwarfSymbolReference(TheU->getLabelBegin());
1545 
1546   Asm->OutStreamer->AddComment("Compilation Unit Length");
1547   Asm->EmitInt32(TheU->getLength());
1548 
1549   // Emit the pubnames for this compilation unit.
1550   for (const auto &GI : Globals) {
1551     const char *Name = GI.getKeyData();
1552     const DIE *Entity = GI.second;
1553 
1554     Asm->OutStreamer->AddComment("DIE offset");
1555     Asm->EmitInt32(Entity->getOffset());
1556 
1557     if (GnuStyle) {
1558       dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1559       Asm->OutStreamer->AddComment(
1560           Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1561           dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1562       Asm->EmitInt8(Desc.toBits());
1563     }
1564 
1565     Asm->OutStreamer->AddComment("External Name");
1566     Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1567   }
1568 
1569   Asm->OutStreamer->AddComment("End Mark");
1570   Asm->EmitInt32(0);
1571   Asm->OutStreamer->EmitLabel(EndLabel);
1572 }
1573 
1574 /// Emit null-terminated strings into a debug str section.
1575 void DwarfDebug::emitDebugStr() {
1576   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1577   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1578 }
1579 
1580 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1581                                    const DebugLocStream::Entry &Entry) {
1582   auto &&Comments = DebugLocs.getComments(Entry);
1583   auto Comment = Comments.begin();
1584   auto End = Comments.end();
1585   for (uint8_t Byte : DebugLocs.getBytes(Entry))
1586     Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1587 }
1588 
1589 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1590                               ByteStreamer &Streamer,
1591                               const DebugLocEntry::Value &Value,
1592                               DwarfExpression &DwarfExpr) {
1593   auto *DIExpr = Value.getExpression();
1594   DIExpressionCursor ExprCursor(DIExpr);
1595   DwarfExpr.addFragmentOffset(DIExpr);
1596   // Regular entry.
1597   if (Value.isInt()) {
1598     if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1599                BT->getEncoding() == dwarf::DW_ATE_signed_char))
1600       DwarfExpr.addSignedConstant(Value.getInt());
1601     else
1602       DwarfExpr.addUnsignedConstant(Value.getInt());
1603   } else if (Value.isLocation()) {
1604     MachineLocation Location = Value.getLoc();
1605     if (Location.isIndirect())
1606       DwarfExpr.setMemoryLocationKind();
1607     DIExpressionCursor Cursor(DIExpr);
1608     const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
1609     if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1610       return;
1611     return DwarfExpr.addExpression(std::move(Cursor));
1612   } else if (Value.isConstantFP()) {
1613     APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
1614     DwarfExpr.addUnsignedConstant(RawBytes);
1615   }
1616   DwarfExpr.addExpression(std::move(ExprCursor));
1617 }
1618 
1619 void DebugLocEntry::finalize(const AsmPrinter &AP,
1620                              DebugLocStream::ListBuilder &List,
1621                              const DIBasicType *BT) {
1622   DebugLocStream::EntryBuilder Entry(List, Begin, End);
1623   BufferByteStreamer Streamer = Entry.getStreamer();
1624   DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
1625   const DebugLocEntry::Value &Value = Values[0];
1626   if (Value.isFragment()) {
1627     // Emit all fragments that belong to the same variable and range.
1628     assert(llvm::all_of(Values, [](DebugLocEntry::Value P) {
1629           return P.isFragment();
1630         }) && "all values are expected to be fragments");
1631     assert(std::is_sorted(Values.begin(), Values.end()) &&
1632            "fragments are expected to be sorted");
1633 
1634     for (auto Fragment : Values)
1635       emitDebugLocValue(AP, BT, Streamer, Fragment, DwarfExpr);
1636 
1637   } else {
1638     assert(Values.size() == 1 && "only fragments may have >1 value");
1639     emitDebugLocValue(AP, BT, Streamer, Value, DwarfExpr);
1640   }
1641   DwarfExpr.finalize();
1642 }
1643 
1644 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
1645   // Emit the size.
1646   Asm->OutStreamer->AddComment("Loc expr size");
1647   Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
1648 
1649   // Emit the entry.
1650   APByteStreamer Streamer(*Asm);
1651   emitDebugLocEntry(Streamer, Entry);
1652 }
1653 
1654 // Emit locations into the debug loc section.
1655 void DwarfDebug::emitDebugLoc() {
1656   if (DebugLocs.getLists().empty())
1657     return;
1658 
1659   // Start the dwarf loc section.
1660   Asm->OutStreamer->SwitchSection(
1661       Asm->getObjFileLowering().getDwarfLocSection());
1662   unsigned char Size = Asm->MAI->getCodePointerSize();
1663   for (const auto &List : DebugLocs.getLists()) {
1664     Asm->OutStreamer->EmitLabel(List.Label);
1665     const DwarfCompileUnit *CU = List.CU;
1666     for (const auto &Entry : DebugLocs.getEntries(List)) {
1667       // Set up the range. This range is relative to the entry point of the
1668       // compile unit. This is a hard coded 0 for low_pc when we're emitting
1669       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1670       if (auto *Base = CU->getBaseAddress()) {
1671         Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
1672         Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
1673       } else {
1674         Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
1675         Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
1676       }
1677 
1678       emitDebugLocEntryLocation(Entry);
1679     }
1680     Asm->OutStreamer->EmitIntValue(0, Size);
1681     Asm->OutStreamer->EmitIntValue(0, Size);
1682   }
1683 }
1684 
1685 void DwarfDebug::emitDebugLocDWO() {
1686   Asm->OutStreamer->SwitchSection(
1687       Asm->getObjFileLowering().getDwarfLocDWOSection());
1688   for (const auto &List : DebugLocs.getLists()) {
1689     Asm->OutStreamer->EmitLabel(List.Label);
1690     for (const auto &Entry : DebugLocs.getEntries(List)) {
1691       // Just always use start_length for now - at least that's one address
1692       // rather than two. We could get fancier and try to, say, reuse an
1693       // address we know we've emitted elsewhere (the start of the function?
1694       // The start of the CU or CU subrange that encloses this range?)
1695       Asm->EmitInt8(dwarf::DW_LLE_startx_length);
1696       unsigned idx = AddrPool.getIndex(Entry.BeginSym);
1697       Asm->EmitULEB128(idx);
1698       Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
1699 
1700       emitDebugLocEntryLocation(Entry);
1701     }
1702     Asm->EmitInt8(dwarf::DW_LLE_end_of_list);
1703   }
1704 }
1705 
1706 struct ArangeSpan {
1707   const MCSymbol *Start, *End;
1708 };
1709 
1710 // Emit a debug aranges section, containing a CU lookup for any
1711 // address we can tie back to a CU.
1712 void DwarfDebug::emitDebugARanges() {
1713   // Provides a unique id per text section.
1714   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1715 
1716   // Filter labels by section.
1717   for (const SymbolCU &SCU : ArangeLabels) {
1718     if (SCU.Sym->isInSection()) {
1719       // Make a note of this symbol and it's section.
1720       MCSection *Section = &SCU.Sym->getSection();
1721       if (!Section->getKind().isMetadata())
1722         SectionMap[Section].push_back(SCU);
1723     } else {
1724       // Some symbols (e.g. common/bss on mach-o) can have no section but still
1725       // appear in the output. This sucks as we rely on sections to build
1726       // arange spans. We can do it without, but it's icky.
1727       SectionMap[nullptr].push_back(SCU);
1728     }
1729   }
1730 
1731   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1732 
1733   for (auto &I : SectionMap) {
1734     MCSection *Section = I.first;
1735     SmallVector<SymbolCU, 8> &List = I.second;
1736     if (List.size() < 1)
1737       continue;
1738 
1739     // If we have no section (e.g. common), just write out
1740     // individual spans for each symbol.
1741     if (!Section) {
1742       for (const SymbolCU &Cur : List) {
1743         ArangeSpan Span;
1744         Span.Start = Cur.Sym;
1745         Span.End = nullptr;
1746         assert(Cur.CU);
1747         Spans[Cur.CU].push_back(Span);
1748       }
1749       continue;
1750     }
1751 
1752     // Sort the symbols by offset within the section.
1753     std::sort(
1754         List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
1755           unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
1756           unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
1757 
1758           // Symbols with no order assigned should be placed at the end.
1759           // (e.g. section end labels)
1760           if (IA == 0)
1761             return false;
1762           if (IB == 0)
1763             return true;
1764           return IA < IB;
1765         });
1766 
1767     // Insert a final terminator.
1768     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
1769 
1770     // Build spans between each label.
1771     const MCSymbol *StartSym = List[0].Sym;
1772     for (size_t n = 1, e = List.size(); n < e; n++) {
1773       const SymbolCU &Prev = List[n - 1];
1774       const SymbolCU &Cur = List[n];
1775 
1776       // Try and build the longest span we can within the same CU.
1777       if (Cur.CU != Prev.CU) {
1778         ArangeSpan Span;
1779         Span.Start = StartSym;
1780         Span.End = Cur.Sym;
1781         assert(Prev.CU);
1782         Spans[Prev.CU].push_back(Span);
1783         StartSym = Cur.Sym;
1784       }
1785     }
1786   }
1787 
1788   // Start the dwarf aranges section.
1789   Asm->OutStreamer->SwitchSection(
1790       Asm->getObjFileLowering().getDwarfARangesSection());
1791 
1792   unsigned PtrSize = Asm->MAI->getCodePointerSize();
1793 
1794   // Build a list of CUs used.
1795   std::vector<DwarfCompileUnit *> CUs;
1796   for (const auto &it : Spans) {
1797     DwarfCompileUnit *CU = it.first;
1798     CUs.push_back(CU);
1799   }
1800 
1801   // Sort the CU list (again, to ensure consistent output order).
1802   std::sort(CUs.begin(), CUs.end(),
1803             [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
1804               return A->getUniqueID() < B->getUniqueID();
1805             });
1806 
1807   // Emit an arange table for each CU we used.
1808   for (DwarfCompileUnit *CU : CUs) {
1809     std::vector<ArangeSpan> &List = Spans[CU];
1810 
1811     // Describe the skeleton CU's offset and length, not the dwo file's.
1812     if (auto *Skel = CU->getSkeleton())
1813       CU = Skel;
1814 
1815     // Emit size of content not including length itself.
1816     unsigned ContentSize =
1817         sizeof(int16_t) + // DWARF ARange version number
1818         sizeof(int32_t) + // Offset of CU in the .debug_info section
1819         sizeof(int8_t) +  // Pointer Size (in bytes)
1820         sizeof(int8_t);   // Segment Size (in bytes)
1821 
1822     unsigned TupleSize = PtrSize * 2;
1823 
1824     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1825     unsigned Padding =
1826         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1827 
1828     ContentSize += Padding;
1829     ContentSize += (List.size() + 1) * TupleSize;
1830 
1831     // For each compile unit, write the list of spans it covers.
1832     Asm->OutStreamer->AddComment("Length of ARange Set");
1833     Asm->EmitInt32(ContentSize);
1834     Asm->OutStreamer->AddComment("DWARF Arange version number");
1835     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1836     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
1837     Asm->emitDwarfSymbolReference(CU->getLabelBegin());
1838     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1839     Asm->EmitInt8(PtrSize);
1840     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
1841     Asm->EmitInt8(0);
1842 
1843     Asm->OutStreamer->emitFill(Padding, 0xff);
1844 
1845     for (const ArangeSpan &Span : List) {
1846       Asm->EmitLabelReference(Span.Start, PtrSize);
1847 
1848       // Calculate the size as being from the span start to it's end.
1849       if (Span.End) {
1850         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1851       } else {
1852         // For symbols without an end marker (e.g. common), we
1853         // write a single arange entry containing just that one symbol.
1854         uint64_t Size = SymSize[Span.Start];
1855         if (Size == 0)
1856           Size = 1;
1857 
1858         Asm->OutStreamer->EmitIntValue(Size, PtrSize);
1859       }
1860     }
1861 
1862     Asm->OutStreamer->AddComment("ARange terminator");
1863     Asm->OutStreamer->EmitIntValue(0, PtrSize);
1864     Asm->OutStreamer->EmitIntValue(0, PtrSize);
1865   }
1866 }
1867 
1868 /// Emit address ranges into a debug ranges section.
1869 void DwarfDebug::emitDebugRanges() {
1870   if (CUMap.empty())
1871     return;
1872 
1873   // Start the dwarf ranges section.
1874   Asm->OutStreamer->SwitchSection(
1875       Asm->getObjFileLowering().getDwarfRangesSection());
1876 
1877   // Size for our labels.
1878   unsigned char Size = Asm->MAI->getCodePointerSize();
1879 
1880   // Grab the specific ranges for the compile units in the module.
1881   for (const auto &I : CUMap) {
1882     DwarfCompileUnit *TheCU = I.second;
1883 
1884     if (auto *Skel = TheCU->getSkeleton())
1885       TheCU = Skel;
1886 
1887     // Iterate over the misc ranges for the compile units in the module.
1888     for (const RangeSpanList &List : TheCU->getRangeLists()) {
1889       // Emit our symbol so we can find the beginning of the range.
1890       Asm->OutStreamer->EmitLabel(List.getSym());
1891 
1892       // Gather all the ranges that apply to the same section so they can share
1893       // a base address entry.
1894       MapVector<const MCSection *, std::vector<const RangeSpan *>> MV;
1895       for (const RangeSpan &Range : List.getRanges()) {
1896         MV[&Range.getStart()->getSection()].push_back(&Range);
1897       }
1898 
1899       auto *CUBase = TheCU->getBaseAddress();
1900       bool BaseIsSet = false;
1901       for (const auto &P : MV) {
1902         // Don't bother with a base address entry if there's only one range in
1903         // this section in this range list - for example ranges for a CU will
1904         // usually consist of single regions from each of many sections
1905         // (-ffunction-sections, or just C++ inline functions) except under LTO
1906         // or optnone where there may be holes in a single CU's section
1907         // contrubutions.
1908         auto *Base = CUBase;
1909         if (!Base && P.second.size() > 1 &&
1910             UseDwarfRangesBaseAddressSpecifier) {
1911           BaseIsSet = true;
1912           // FIXME/use care: This may not be a useful base address if it's not
1913           // the lowest address/range in this object.
1914           Base = P.second.front()->getStart();
1915           Asm->OutStreamer->EmitIntValue(-1, Size);
1916           Asm->OutStreamer->EmitSymbolValue(Base, Size);
1917         } else if (BaseIsSet) {
1918           BaseIsSet = false;
1919           Asm->OutStreamer->EmitIntValue(-1, Size);
1920           Asm->OutStreamer->EmitIntValue(0, Size);
1921         }
1922 
1923         for (const auto *RS : P.second) {
1924           const MCSymbol *Begin = RS->getStart();
1925           const MCSymbol *End = RS->getEnd();
1926           assert(Begin && "Range without a begin symbol?");
1927           assert(End && "Range without an end symbol?");
1928           if (Base) {
1929             Asm->EmitLabelDifference(Begin, Base, Size);
1930             Asm->EmitLabelDifference(End, Base, Size);
1931           } else {
1932             Asm->OutStreamer->EmitSymbolValue(Begin, Size);
1933             Asm->OutStreamer->EmitSymbolValue(End, Size);
1934           }
1935         }
1936       }
1937 
1938       // And terminate the list with two 0 values.
1939       Asm->OutStreamer->EmitIntValue(0, Size);
1940       Asm->OutStreamer->EmitIntValue(0, Size);
1941     }
1942   }
1943 }
1944 
1945 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
1946   for (auto *MN : Nodes) {
1947     if (auto *M = dyn_cast<DIMacro>(MN))
1948       emitMacro(*M);
1949     else if (auto *F = dyn_cast<DIMacroFile>(MN))
1950       emitMacroFile(*F, U);
1951     else
1952       llvm_unreachable("Unexpected DI type!");
1953   }
1954 }
1955 
1956 void DwarfDebug::emitMacro(DIMacro &M) {
1957   Asm->EmitULEB128(M.getMacinfoType());
1958   Asm->EmitULEB128(M.getLine());
1959   StringRef Name = M.getName();
1960   StringRef Value = M.getValue();
1961   Asm->OutStreamer->EmitBytes(Name);
1962   if (!Value.empty()) {
1963     // There should be one space between macro name and macro value.
1964     Asm->EmitInt8(' ');
1965     Asm->OutStreamer->EmitBytes(Value);
1966   }
1967   Asm->EmitInt8('\0');
1968 }
1969 
1970 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
1971   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
1972   Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
1973   Asm->EmitULEB128(F.getLine());
1974   Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
1975   handleMacroNodes(F.getElements(), U);
1976   Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
1977 }
1978 
1979 /// Emit macros into a debug macinfo section.
1980 void DwarfDebug::emitDebugMacinfo() {
1981   if (CUMap.empty())
1982     return;
1983 
1984   // Start the dwarf macinfo section.
1985   Asm->OutStreamer->SwitchSection(
1986       Asm->getObjFileLowering().getDwarfMacinfoSection());
1987 
1988   for (const auto &P : CUMap) {
1989     auto &TheCU = *P.second;
1990     auto *SkCU = TheCU.getSkeleton();
1991     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1992     auto *CUNode = cast<DICompileUnit>(P.first);
1993     Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
1994     handleMacroNodes(CUNode->getMacros(), U);
1995   }
1996   Asm->OutStreamer->AddComment("End Of Macro List Mark");
1997   Asm->EmitInt8(0);
1998 }
1999 
2000 // DWARF5 Experimental Separate Dwarf emitters.
2001 
2002 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2003                                   std::unique_ptr<DwarfCompileUnit> NewU) {
2004   NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
2005                   Asm->TM.Options.MCOptions.SplitDwarfFile);
2006 
2007   if (!CompilationDir.empty())
2008     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2009 
2010   addGnuPubAttributes(*NewU, Die);
2011 
2012   SkeletonHolder.addUnit(std::move(NewU));
2013 }
2014 
2015 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2016 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2017 // DW_AT_addr_base, DW_AT_ranges_base.
2018 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2019 
2020   auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
2021       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2022   DwarfCompileUnit &NewCU = *OwnedUnit;
2023   NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2024 
2025   NewCU.initStmtList();
2026 
2027   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2028 
2029   return NewCU;
2030 }
2031 
2032 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2033 // compile units that would normally be in debug_info.
2034 void DwarfDebug::emitDebugInfoDWO() {
2035   assert(useSplitDwarf() && "No split dwarf debug info?");
2036   // Don't emit relocations into the dwo file.
2037   InfoHolder.emitUnits(/* UseOffsets */ true);
2038 }
2039 
2040 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2041 // abbreviations for the .debug_info.dwo section.
2042 void DwarfDebug::emitDebugAbbrevDWO() {
2043   assert(useSplitDwarf() && "No split dwarf?");
2044   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2045 }
2046 
2047 void DwarfDebug::emitDebugLineDWO() {
2048   assert(useSplitDwarf() && "No split dwarf?");
2049   Asm->OutStreamer->SwitchSection(
2050       Asm->getObjFileLowering().getDwarfLineDWOSection());
2051   SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams());
2052 }
2053 
2054 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2055 // string section and is identical in format to traditional .debug_str
2056 // sections.
2057 void DwarfDebug::emitDebugStrDWO() {
2058   assert(useSplitDwarf() && "No split dwarf?");
2059   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2060   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2061                          OffSec);
2062 }
2063 
2064 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2065   if (!useSplitDwarf())
2066     return nullptr;
2067   if (SingleCU)
2068     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
2069   return &SplitTypeUnitFileTable;
2070 }
2071 
2072 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2073   MD5 Hash;
2074   Hash.update(Identifier);
2075   // ... take the least significant 8 bytes and return those. Our MD5
2076   // implementation always returns its results in little endian, so we actually
2077   // need the "high" word.
2078   MD5::MD5Result Result;
2079   Hash.final(Result);
2080   return Result.high();
2081 }
2082 
2083 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2084                                       StringRef Identifier, DIE &RefDie,
2085                                       const DICompositeType *CTy) {
2086   // Fast path if we're building some type units and one has already used the
2087   // address pool we know we're going to throw away all this work anyway, so
2088   // don't bother building dependent types.
2089   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2090     return;
2091 
2092   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2093   if (!Ins.second) {
2094     CU.addDIETypeSignature(RefDie, Ins.first->second);
2095     return;
2096   }
2097 
2098   bool TopLevelType = TypeUnitsUnderConstruction.empty();
2099   AddrPool.resetUsedFlag();
2100 
2101   auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2102                                                     getDwoLineTable(CU));
2103   DwarfTypeUnit &NewTU = *OwnedUnit;
2104   DIE &UnitDie = NewTU.getUnitDie();
2105   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
2106 
2107   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2108                 CU.getLanguage());
2109 
2110   uint64_t Signature = makeTypeSignature(Identifier);
2111   NewTU.setTypeSignature(Signature);
2112   Ins.first->second = Signature;
2113 
2114   if (useSplitDwarf())
2115     NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2116   else {
2117     CU.applyStmtList(UnitDie);
2118     NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2119   }
2120 
2121   NewTU.setType(NewTU.createTypeDIE(CTy));
2122 
2123   if (TopLevelType) {
2124     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2125     TypeUnitsUnderConstruction.clear();
2126 
2127     // Types referencing entries in the address table cannot be placed in type
2128     // units.
2129     if (AddrPool.hasBeenUsed()) {
2130 
2131       // Remove all the types built while building this type.
2132       // This is pessimistic as some of these types might not be dependent on
2133       // the type that used an address.
2134       for (const auto &TU : TypeUnitsToAdd)
2135         TypeSignatures.erase(TU.second);
2136 
2137       // Construct this type in the CU directly.
2138       // This is inefficient because all the dependent types will be rebuilt
2139       // from scratch, including building them in type units, discovering that
2140       // they depend on addresses, throwing them out and rebuilding them.
2141       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2142       return;
2143     }
2144 
2145     // If the type wasn't dependent on fission addresses, finish adding the type
2146     // and all its dependent types.
2147     for (auto &TU : TypeUnitsToAdd) {
2148       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2149       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2150     }
2151   }
2152   CU.addDIETypeSignature(RefDie, Signature);
2153 }
2154 
2155 // Accelerator table mutators - add each name along with its companion
2156 // DIE to the proper table while ensuring that the name that we're going
2157 // to reference is in the string table. We do this since the names we
2158 // add may not only be identical to the names in the DIE.
2159 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2160   if (!useDwarfAccelTables())
2161     return;
2162   AccelNames.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2163 }
2164 
2165 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2166   if (!useDwarfAccelTables())
2167     return;
2168   AccelObjC.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2169 }
2170 
2171 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2172   if (!useDwarfAccelTables())
2173     return;
2174   AccelNamespace.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2175 }
2176 
2177 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2178   if (!useDwarfAccelTables())
2179     return;
2180   AccelTypes.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2181 }
2182 
2183 uint16_t DwarfDebug::getDwarfVersion() const {
2184   return Asm->OutStreamer->getContext().getDwarfVersion();
2185 }
2186