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