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