1 //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for writing dwarf debug info into asm files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "DwarfDebug.h"
14 #include "ByteStreamer.h"
15 #include "DIEHash.h"
16 #include "DebugLocEntry.h"
17 #include "DebugLocStream.h"
18 #include "DwarfCompileUnit.h"
19 #include "DwarfExpression.h"
20 #include "DwarfFile.h"
21 #include "DwarfUnit.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/MapVector.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Statistic.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/TargetInstrInfo.h"
43 #include "llvm/CodeGen/TargetLowering.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
47 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GlobalVariable.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/MC/MCAsmInfo.h"
55 #include "llvm/MC/MCContext.h"
56 #include "llvm/MC/MCDwarf.h"
57 #include "llvm/MC/MCSection.h"
58 #include "llvm/MC/MCStreamer.h"
59 #include "llvm/MC/MCSymbol.h"
60 #include "llvm/MC/MCTargetOptions.h"
61 #include "llvm/MC/MachineLocation.h"
62 #include "llvm/MC/SectionKind.h"
63 #include "llvm/Pass.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/ErrorHandling.h"
68 #include "llvm/Support/MD5.h"
69 #include "llvm/Support/MathExtras.h"
70 #include "llvm/Support/Timer.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Target/TargetLoweringObjectFile.h"
73 #include "llvm/Target/TargetMachine.h"
74 #include "llvm/Target/TargetOptions.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstddef>
78 #include <cstdint>
79 #include <iterator>
80 #include <string>
81 #include <utility>
82 #include <vector>
83 
84 using namespace llvm;
85 
86 #define DEBUG_TYPE "dwarfdebug"
87 
88 STATISTIC(NumCSParams, "Number of dbg call site params created");
89 
90 static cl::opt<bool>
91 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
92                          cl::desc("Disable debug info printing"));
93 
94 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
95     "use-dwarf-ranges-base-address-specifier", cl::Hidden,
96     cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
97 
98 static cl::opt<bool> EmitDwarfDebugEntryValues(
99     "emit-debug-entry-values", cl::Hidden,
100     cl::desc("Emit the debug entry values"), cl::init(false));
101 
102 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
103                                            cl::Hidden,
104                                            cl::desc("Generate dwarf aranges"),
105                                            cl::init(false));
106 
107 static cl::opt<bool>
108     GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
109                            cl::desc("Generate DWARF4 type units."),
110                            cl::init(false));
111 
112 static cl::opt<bool> SplitDwarfCrossCuReferences(
113     "split-dwarf-cross-cu-references", cl::Hidden,
114     cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
115 
116 enum DefaultOnOff { Default, Enable, Disable };
117 
118 static cl::opt<DefaultOnOff> UnknownLocations(
119     "use-unknown-locations", cl::Hidden,
120     cl::desc("Make an absence of debug location information explicit."),
121     cl::values(clEnumVal(Default, "At top of block or after label"),
122                clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
123     cl::init(Default));
124 
125 static cl::opt<AccelTableKind> AccelTables(
126     "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
127     cl::values(clEnumValN(AccelTableKind::Default, "Default",
128                           "Default for platform"),
129                clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
130                clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
131                clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
132     cl::init(AccelTableKind::Default));
133 
134 static cl::opt<DefaultOnOff>
135 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
136                  cl::desc("Use inlined strings rather than string section."),
137                  cl::values(clEnumVal(Default, "Default for platform"),
138                             clEnumVal(Enable, "Enabled"),
139                             clEnumVal(Disable, "Disabled")),
140                  cl::init(Default));
141 
142 static cl::opt<bool>
143     NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
144                          cl::desc("Disable emission .debug_ranges section."),
145                          cl::init(false));
146 
147 static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
148     "dwarf-sections-as-references", cl::Hidden,
149     cl::desc("Use sections+offset as references rather than labels."),
150     cl::values(clEnumVal(Default, "Default for platform"),
151                clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
152     cl::init(Default));
153 
154 enum LinkageNameOption {
155   DefaultLinkageNames,
156   AllLinkageNames,
157   AbstractLinkageNames
158 };
159 
160 static cl::opt<LinkageNameOption>
161     DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
162                       cl::desc("Which DWARF linkage-name attributes to emit."),
163                       cl::values(clEnumValN(DefaultLinkageNames, "Default",
164                                             "Default for platform"),
165                                  clEnumValN(AllLinkageNames, "All", "All"),
166                                  clEnumValN(AbstractLinkageNames, "Abstract",
167                                             "Abstract subprograms")),
168                       cl::init(DefaultLinkageNames));
169 
170 static const char *const DWARFGroupName = "dwarf";
171 static const char *const DWARFGroupDescription = "DWARF Emission";
172 static const char *const DbgTimerName = "writer";
173 static const char *const DbgTimerDescription = "DWARF Debug Writer";
174 static constexpr unsigned ULEB128PadSize = 4;
175 
176 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
177   getActiveStreamer().EmitInt8(
178       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
179                   : dwarf::OperationEncodingString(Op));
180 }
181 
182 void DebugLocDwarfExpression::emitSigned(int64_t Value) {
183   getActiveStreamer().emitSLEB128(Value, Twine(Value));
184 }
185 
186 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
187   getActiveStreamer().emitULEB128(Value, Twine(Value));
188 }
189 
190 void DebugLocDwarfExpression::emitData1(uint8_t Value) {
191   getActiveStreamer().EmitInt8(Value, Twine(Value));
192 }
193 
194 void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
195   assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
196   getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
197 }
198 
199 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
200                                               unsigned MachineReg) {
201   // This information is not available while emitting .debug_loc entries.
202   return false;
203 }
204 
205 void DebugLocDwarfExpression::enableTemporaryBuffer() {
206   assert(!IsBuffering && "Already buffering?");
207   if (!TmpBuf)
208     TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
209   IsBuffering = true;
210 }
211 
212 void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
213 
214 unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
215   return TmpBuf ? TmpBuf->Bytes.size() : 0;
216 }
217 
218 void DebugLocDwarfExpression::commitTemporaryBuffer() {
219   if (!TmpBuf)
220     return;
221   for (auto Byte : enumerate(TmpBuf->Bytes)) {
222     const char *Comment = (Byte.index() < TmpBuf->Comments.size())
223                               ? TmpBuf->Comments[Byte.index()].c_str()
224                               : "";
225     OutBS.EmitInt8(Byte.value(), Comment);
226   }
227   TmpBuf->Bytes.clear();
228   TmpBuf->Comments.clear();
229 }
230 
231 const DIType *DbgVariable::getType() const {
232   return getVariable()->getType();
233 }
234 
235 /// Get .debug_loc entry for the instruction range starting at MI.
236 static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
237   const DIExpression *Expr = MI->getDebugExpression();
238   assert(MI->getNumOperands() == 4);
239   if (MI->getOperand(0).isReg()) {
240     auto RegOp = MI->getOperand(0);
241     auto Op1 = MI->getOperand(1);
242     // If the second operand is an immediate, this is a
243     // register-indirect address.
244     assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
245     MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
246     return DbgValueLoc(Expr, MLoc);
247   }
248   if (MI->getOperand(0).isTargetIndex()) {
249     auto Op = MI->getOperand(0);
250     return DbgValueLoc(Expr,
251                        TargetIndexLocation(Op.getIndex(), Op.getOffset()));
252   }
253   if (MI->getOperand(0).isImm())
254     return DbgValueLoc(Expr, MI->getOperand(0).getImm());
255   if (MI->getOperand(0).isFPImm())
256     return DbgValueLoc(Expr, MI->getOperand(0).getFPImm());
257   if (MI->getOperand(0).isCImm())
258     return DbgValueLoc(Expr, MI->getOperand(0).getCImm());
259 
260   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
261 }
262 
263 void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) {
264   assert(FrameIndexExprs.empty() && "Already initialized?");
265   assert(!ValueLoc.get() && "Already initialized?");
266 
267   assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable");
268   assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() &&
269          "Wrong inlined-at");
270 
271   ValueLoc = std::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue));
272   if (auto *E = DbgValue->getDebugExpression())
273     if (E->getNumElements())
274       FrameIndexExprs.push_back({0, E});
275 }
276 
277 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
278   if (FrameIndexExprs.size() == 1)
279     return FrameIndexExprs;
280 
281   assert(llvm::all_of(FrameIndexExprs,
282                       [](const FrameIndexExpr &A) {
283                         return A.Expr->isFragment();
284                       }) &&
285          "multiple FI expressions without DW_OP_LLVM_fragment");
286   llvm::sort(FrameIndexExprs,
287              [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
288                return A.Expr->getFragmentInfo()->OffsetInBits <
289                       B.Expr->getFragmentInfo()->OffsetInBits;
290              });
291 
292   return FrameIndexExprs;
293 }
294 
295 void DbgVariable::addMMIEntry(const DbgVariable &V) {
296   assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry");
297   assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry");
298   assert(V.getVariable() == getVariable() && "conflicting variable");
299   assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
300 
301   assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
302   assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
303 
304   // FIXME: This logic should not be necessary anymore, as we now have proper
305   // deduplication. However, without it, we currently run into the assertion
306   // below, which means that we are likely dealing with broken input, i.e. two
307   // non-fragment entries for the same variable at different frame indices.
308   if (FrameIndexExprs.size()) {
309     auto *Expr = FrameIndexExprs.back().Expr;
310     if (!Expr || !Expr->isFragment())
311       return;
312   }
313 
314   for (const auto &FIE : V.FrameIndexExprs)
315     // Ignore duplicate entries.
316     if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
317           return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
318         }))
319       FrameIndexExprs.push_back(FIE);
320 
321   assert((FrameIndexExprs.size() == 1 ||
322           llvm::all_of(FrameIndexExprs,
323                        [](FrameIndexExpr &FIE) {
324                          return FIE.Expr && FIE.Expr->isFragment();
325                        })) &&
326          "conflicting locations for variable");
327 }
328 
329 static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
330                                             bool GenerateTypeUnits,
331                                             DebuggerKind Tuning,
332                                             const Triple &TT) {
333   // Honor an explicit request.
334   if (AccelTables != AccelTableKind::Default)
335     return AccelTables;
336 
337   // Accelerator tables with type units are currently not supported.
338   if (GenerateTypeUnits)
339     return AccelTableKind::None;
340 
341   // Accelerator tables get emitted if targetting DWARF v5 or LLDB.  DWARF v5
342   // always implies debug_names. For lower standard versions we use apple
343   // accelerator tables on apple platforms and debug_names elsewhere.
344   if (DwarfVersion >= 5)
345     return AccelTableKind::Dwarf;
346   if (Tuning == DebuggerKind::LLDB)
347     return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
348                                    : AccelTableKind::Dwarf;
349   return AccelTableKind::None;
350 }
351 
352 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
353     : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
354       InfoHolder(A, "info_string", DIEValueAllocator),
355       SkeletonHolder(A, "skel_string", DIEValueAllocator),
356       IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
357   const Triple &TT = Asm->TM.getTargetTriple();
358 
359   // Make sure we know our "debugger tuning".  The target option takes
360   // precedence; fall back to triple-based defaults.
361   if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
362     DebuggerTuning = Asm->TM.Options.DebuggerTuning;
363   else if (IsDarwin)
364     DebuggerTuning = DebuggerKind::LLDB;
365   else if (TT.isPS4CPU())
366     DebuggerTuning = DebuggerKind::SCE;
367   else
368     DebuggerTuning = DebuggerKind::GDB;
369 
370   if (DwarfInlinedStrings == Default)
371     UseInlineStrings = TT.isNVPTX();
372   else
373     UseInlineStrings = DwarfInlinedStrings == Enable;
374 
375   UseLocSection = !TT.isNVPTX();
376 
377   HasAppleExtensionAttributes = tuneForLLDB();
378 
379   // Handle split DWARF.
380   HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
381 
382   // SCE defaults to linkage names only for abstract subprograms.
383   if (DwarfLinkageNames == DefaultLinkageNames)
384     UseAllLinkageNames = !tuneForSCE();
385   else
386     UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
387 
388   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
389   unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
390                                     : MMI->getModule()->getDwarfVersion();
391   // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
392   DwarfVersion =
393       TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
394 
395   UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
396 
397   // Use sections as references. Force for NVPTX.
398   if (DwarfSectionsAsReferences == Default)
399     UseSectionsAsReferences = TT.isNVPTX();
400   else
401     UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
402 
403   // Don't generate type units for unsupported object file formats.
404   GenerateTypeUnits =
405       A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits;
406 
407   TheAccelTableKind = computeAccelTableKind(
408       DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
409 
410   // Work around a GDB bug. GDB doesn't support the standard opcode;
411   // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
412   // is defined as of DWARF 3.
413   // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
414   // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
415   UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
416 
417   // GDB does not fully support the DWARF 4 representation for bitfields.
418   UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
419 
420   // The DWARF v5 string offsets table has - possibly shared - contributions
421   // from each compile and type unit each preceded by a header. The string
422   // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
423   // a monolithic string offsets table without any header.
424   UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
425 
426   // Emit call-site-param debug info for GDB and LLDB, if the target supports
427   // the debug entry values feature. It can also be enabled explicitly.
428   EmitDebugEntryValues = (Asm->TM.Options.ShouldEmitDebugEntryValues() &&
429                           (tuneForGDB() || tuneForLLDB())) ||
430                          EmitDwarfDebugEntryValues;
431 
432   Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
433 }
434 
435 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
436 DwarfDebug::~DwarfDebug() = default;
437 
438 static bool isObjCClass(StringRef Name) {
439   return Name.startswith("+") || Name.startswith("-");
440 }
441 
442 static bool hasObjCCategory(StringRef Name) {
443   if (!isObjCClass(Name))
444     return false;
445 
446   return Name.find(") ") != StringRef::npos;
447 }
448 
449 static void getObjCClassCategory(StringRef In, StringRef &Class,
450                                  StringRef &Category) {
451   if (!hasObjCCategory(In)) {
452     Class = In.slice(In.find('[') + 1, In.find(' '));
453     Category = "";
454     return;
455   }
456 
457   Class = In.slice(In.find('[') + 1, In.find('('));
458   Category = In.slice(In.find('[') + 1, In.find(' '));
459 }
460 
461 static StringRef getObjCMethodName(StringRef In) {
462   return In.slice(In.find(' ') + 1, In.find(']'));
463 }
464 
465 // Add the various names to the Dwarf accelerator table names.
466 void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
467                                     const DISubprogram *SP, DIE &Die) {
468   if (getAccelTableKind() != AccelTableKind::Apple &&
469       CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
470     return;
471 
472   if (!SP->isDefinition())
473     return;
474 
475   if (SP->getName() != "")
476     addAccelName(CU, SP->getName(), Die);
477 
478   // If the linkage name is different than the name, go ahead and output that as
479   // well into the name table. Only do that if we are going to actually emit
480   // that name.
481   if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
482       (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
483     addAccelName(CU, SP->getLinkageName(), Die);
484 
485   // If this is an Objective-C selector name add it to the ObjC accelerator
486   // too.
487   if (isObjCClass(SP->getName())) {
488     StringRef Class, Category;
489     getObjCClassCategory(SP->getName(), Class, Category);
490     addAccelObjC(CU, Class, Die);
491     if (Category != "")
492       addAccelObjC(CU, Category, Die);
493     // Also add the base method name to the name table.
494     addAccelName(CU, getObjCMethodName(SP->getName()), Die);
495   }
496 }
497 
498 /// Check whether we should create a DIE for the given Scope, return true
499 /// if we don't create a DIE (the corresponding DIE is null).
500 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
501   if (Scope->isAbstractScope())
502     return false;
503 
504   // We don't create a DIE if there is no Range.
505   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
506   if (Ranges.empty())
507     return true;
508 
509   if (Ranges.size() > 1)
510     return false;
511 
512   // We don't create a DIE if we have a single Range and the end label
513   // is null.
514   return !getLabelAfterInsn(Ranges.front().second);
515 }
516 
517 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
518   F(CU);
519   if (auto *SkelCU = CU.getSkeleton())
520     if (CU.getCUNode()->getSplitDebugInlining())
521       F(*SkelCU);
522 }
523 
524 bool DwarfDebug::shareAcrossDWOCUs() const {
525   return SplitDwarfCrossCuReferences;
526 }
527 
528 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
529                                                      LexicalScope *Scope) {
530   assert(Scope && Scope->getScopeNode());
531   assert(Scope->isAbstractScope());
532   assert(!Scope->getInlinedAt());
533 
534   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
535 
536   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
537   // was inlined from another compile unit.
538   if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
539     // Avoid building the original CU if it won't be used
540     SrcCU.constructAbstractSubprogramScopeDIE(Scope);
541   else {
542     auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
543     if (auto *SkelCU = CU.getSkeleton()) {
544       (shareAcrossDWOCUs() ? CU : SrcCU)
545           .constructAbstractSubprogramScopeDIE(Scope);
546       if (CU.getCUNode()->getSplitDebugInlining())
547         SkelCU->constructAbstractSubprogramScopeDIE(Scope);
548     } else
549       CU.constructAbstractSubprogramScopeDIE(Scope);
550   }
551 }
552 
553 DIE &DwarfDebug::constructSubprogramDefinitionDIE(const DISubprogram *SP) {
554   DICompileUnit *Unit = SP->getUnit();
555   assert(SP->isDefinition() && "Subprogram not a definition");
556   assert(Unit && "Subprogram definition without parent unit");
557   auto &CU = getOrCreateDwarfCompileUnit(Unit);
558   return *CU.getOrCreateSubprogramDIE(SP);
559 }
560 
561 /// Represents a parameter whose call site value can be described by applying a
562 /// debug expression to a register in the forwarded register worklist.
563 struct FwdRegParamInfo {
564   /// The described parameter register.
565   unsigned ParamReg;
566 
567   /// Debug expression that has been built up when walking through the
568   /// instruction chain that produces the parameter's value.
569   const DIExpression *Expr;
570 };
571 
572 /// Register worklist for finding call site values.
573 using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>;
574 
575 /// Append the expression \p Addition to \p Original and return the result.
576 static const DIExpression *combineDIExpressions(const DIExpression *Original,
577                                                 const DIExpression *Addition) {
578   std::vector<uint64_t> Elts = Addition->getElements().vec();
579   // Avoid multiple DW_OP_stack_values.
580   if (Original->isImplicit() && Addition->isImplicit())
581     erase_if(Elts, [](uint64_t Op) { return Op == dwarf::DW_OP_stack_value; });
582   const DIExpression *CombinedExpr =
583       (Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;
584   return CombinedExpr;
585 }
586 
587 /// Emit call site parameter entries that are described by the given value and
588 /// debug expression.
589 template <typename ValT>
590 static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
591                                  ArrayRef<FwdRegParamInfo> DescribedParams,
592                                  ParamSet &Params) {
593   for (auto Param : DescribedParams) {
594     bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
595 
596     // TODO: Entry value operations can currently not be combined with any
597     // other expressions, so we can't emit call site entries in those cases.
598     if (ShouldCombineExpressions && Expr->isEntryValue())
599       continue;
600 
601     // If a parameter's call site value is produced by a chain of
602     // instructions we may have already created an expression for the
603     // parameter when walking through the instructions. Append that to the
604     // base expression.
605     const DIExpression *CombinedExpr =
606         ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)
607                                  : Expr;
608     assert((!CombinedExpr || CombinedExpr->isValid()) &&
609            "Combined debug expression is invalid");
610 
611     DbgValueLoc DbgLocVal(CombinedExpr, Val);
612     DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
613     Params.push_back(CSParm);
614     ++NumCSParams;
615   }
616 }
617 
618 /// Add \p Reg to the worklist, if it's not already present, and mark that the
619 /// given parameter registers' values can (potentially) be described using
620 /// that register and an debug expression.
621 static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
622                                 const DIExpression *Expr,
623                                 ArrayRef<FwdRegParamInfo> ParamsToAdd) {
624   auto I = Worklist.insert({Reg, {}});
625   auto &ParamsForFwdReg = I.first->second;
626   for (auto Param : ParamsToAdd) {
627     assert(none_of(ParamsForFwdReg,
628                    [Param](const FwdRegParamInfo &D) {
629                      return D.ParamReg == Param.ParamReg;
630                    }) &&
631            "Same parameter described twice by forwarding reg");
632 
633     // If a parameter's call site value is produced by a chain of
634     // instructions we may have already created an expression for the
635     // parameter when walking through the instructions. Append that to the
636     // new expression.
637     const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);
638     ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
639   }
640 }
641 
642 /// Try to interpret values loaded into registers that forward parameters
643 /// for \p CallMI. Store parameters with interpreted value into \p Params.
644 static void collectCallSiteParameters(const MachineInstr *CallMI,
645                                       ParamSet &Params) {
646   auto *MF = CallMI->getMF();
647   auto CalleesMap = MF->getCallSitesInfo();
648   auto CallFwdRegsInfo = CalleesMap.find(CallMI);
649 
650   // There is no information for the call instruction.
651   if (CallFwdRegsInfo == CalleesMap.end())
652     return;
653 
654   auto *MBB = CallMI->getParent();
655   const auto &TRI = MF->getSubtarget().getRegisterInfo();
656   const auto &TII = MF->getSubtarget().getInstrInfo();
657   const auto &TLI = MF->getSubtarget().getTargetLowering();
658 
659   // Skip the call instruction.
660   auto I = std::next(CallMI->getReverseIterator());
661 
662   FwdRegWorklist ForwardedRegWorklist;
663 
664   // If an instruction defines more than one item in the worklist, we may run
665   // into situations where a worklist register's value is (potentially)
666   // described by the previous value of another register that is also defined
667   // by that instruction.
668   //
669   // This can for example occur in cases like this:
670   //
671   //   $r1 = mov 123
672   //   $r0, $r1 = mvrr $r1, 456
673   //   call @foo, $r0, $r1
674   //
675   // When describing $r1's value for the mvrr instruction, we need to make sure
676   // that we don't finalize an entry value for $r0, as that is dependent on the
677   // previous value of $r1 (123 rather than 456).
678   //
679   // In order to not have to distinguish between those cases when finalizing
680   // entry values, we simply postpone adding new parameter registers to the
681   // worklist, by first keeping them in this temporary container until the
682   // instruction has been handled.
683   FwdRegWorklist NewWorklistItems;
684 
685   const DIExpression *EmptyExpr =
686       DIExpression::get(MF->getFunction().getContext(), {});
687 
688   // Add all the forwarding registers into the ForwardedRegWorklist.
689   for (auto ArgReg : CallFwdRegsInfo->second) {
690     bool InsertedReg =
691         ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
692             .second;
693     assert(InsertedReg && "Single register used to forward two arguments?");
694     (void)InsertedReg;
695   }
696 
697   // We erase, from the ForwardedRegWorklist, those forwarding registers for
698   // which we successfully describe a loaded value (by using
699   // the describeLoadedValue()). For those remaining arguments in the working
700   // list, for which we do not describe a loaded value by
701   // the describeLoadedValue(), we try to generate an entry value expression
702   // for their call site value description, if the call is within the entry MBB.
703   // TODO: Handle situations when call site parameter value can be described
704   // as the entry value within basic blocks other than the first one.
705   bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
706 
707   // If the MI is an instruction defining one or more parameters' forwarding
708   // registers, add those defines.
709   auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
710                                           SmallSetVector<unsigned, 4> &Defs) {
711     if (MI.isDebugInstr())
712       return;
713 
714     for (const MachineOperand &MO : MI.operands()) {
715       if (MO.isReg() && MO.isDef() &&
716           Register::isPhysicalRegister(MO.getReg())) {
717         for (auto FwdReg : ForwardedRegWorklist)
718           if (TRI->regsOverlap(FwdReg.first, MO.getReg()))
719             Defs.insert(FwdReg.first);
720       }
721     }
722   };
723 
724   // Search for a loading value in forwarding registers.
725   for (; I != MBB->rend(); ++I) {
726     // Skip bundle headers.
727     if (I->isBundle())
728       continue;
729 
730     // If the next instruction is a call we can not interpret parameter's
731     // forwarding registers or we finished the interpretation of all parameters.
732     if (I->isCall())
733       return;
734 
735     if (ForwardedRegWorklist.empty())
736       return;
737 
738     // Set of worklist registers that are defined by this instruction.
739     SmallSetVector<unsigned, 4> FwdRegDefs;
740 
741     getForwardingRegsDefinedByMI(*I, FwdRegDefs);
742     if (FwdRegDefs.empty())
743       continue;
744 
745     for (auto ParamFwdReg : FwdRegDefs) {
746       if (auto ParamValue = TII->describeLoadedValue(*I, ParamFwdReg)) {
747         if (ParamValue->first.isImm()) {
748           int64_t Val = ParamValue->first.getImm();
749           finishCallSiteParams(Val, ParamValue->second,
750                                ForwardedRegWorklist[ParamFwdReg], Params);
751         } else if (ParamValue->first.isReg()) {
752           Register RegLoc = ParamValue->first.getReg();
753           unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
754           Register FP = TRI->getFrameRegister(*MF);
755           bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
756           if (TRI->isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP) {
757             MachineLocation MLoc(RegLoc, /*IsIndirect=*/IsSPorFP);
758             finishCallSiteParams(MLoc, ParamValue->second,
759                                  ForwardedRegWorklist[ParamFwdReg], Params);
760           } else {
761             // ParamFwdReg was described by the non-callee saved register
762             // RegLoc. Mark that the call site values for the parameters are
763             // dependent on that register instead of ParamFwdReg. Since RegLoc
764             // may be a register that will be handled in this iteration, we
765             // postpone adding the items to the worklist, and instead keep them
766             // in a temporary container.
767             addToFwdRegWorklist(NewWorklistItems, RegLoc, ParamValue->second,
768                                 ForwardedRegWorklist[ParamFwdReg]);
769           }
770         }
771       }
772     }
773 
774     // Remove all registers that this instruction defines from the worklist.
775     for (auto ParamFwdReg : FwdRegDefs)
776       ForwardedRegWorklist.erase(ParamFwdReg);
777 
778     // Now that we are done handling this instruction, add items from the
779     // temporary worklist to the real one.
780     for (auto New : NewWorklistItems)
781       addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr,
782                           New.second);
783     NewWorklistItems.clear();
784   }
785 
786   // Emit the call site parameter's value as an entry value.
787   if (ShouldTryEmitEntryVals) {
788     // Create an expression where the register's entry value is used.
789     DIExpression *EntryExpr = DIExpression::get(
790         MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
791     for (auto RegEntry : ForwardedRegWorklist) {
792       MachineLocation MLoc(RegEntry.first);
793       finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
794     }
795   }
796 }
797 
798 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
799                                             DwarfCompileUnit &CU, DIE &ScopeDIE,
800                                             const MachineFunction &MF) {
801   // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
802   // the subprogram is required to have one.
803   if (!SP.areAllCallsDescribed() || !SP.isDefinition())
804     return;
805 
806   // Use DW_AT_call_all_calls to express that call site entries are present
807   // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
808   // because one of its requirements is not met: call site entries for
809   // optimized-out calls are elided.
810   CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
811 
812   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
813   assert(TII && "TargetInstrInfo not found: cannot label tail calls");
814 
815   // Emit call site entries for each call or tail call in the function.
816   for (const MachineBasicBlock &MBB : MF) {
817     for (const MachineInstr &MI : MBB.instrs()) {
818       // Bundles with call in them will pass the isCall() test below but do not
819       // have callee operand information so skip them here. Iterator will
820       // eventually reach the call MI.
821       if (MI.isBundle())
822         continue;
823 
824       // Skip instructions which aren't calls. Both calls and tail-calling jump
825       // instructions (e.g TAILJMPd64) are classified correctly here.
826       if (!MI.isCandidateForCallSiteEntry())
827         continue;
828 
829       // Skip instructions marked as frame setup, as they are not interesting to
830       // the user.
831       if (MI.getFlag(MachineInstr::FrameSetup))
832         continue;
833 
834       // TODO: Add support for targets with delay slots (see: beginInstruction).
835       if (MI.hasDelaySlot())
836         return;
837 
838       // If this is a direct call, find the callee's subprogram.
839       // In the case of an indirect call find the register that holds
840       // the callee.
841       const MachineOperand &CalleeOp = MI.getOperand(0);
842       if (!CalleeOp.isGlobal() && !CalleeOp.isReg())
843         continue;
844 
845       unsigned CallReg = 0;
846       DIE *CalleeDIE = nullptr;
847       const Function *CalleeDecl = nullptr;
848       if (CalleeOp.isReg()) {
849         CallReg = CalleeOp.getReg();
850         if (!CallReg)
851           continue;
852       } else {
853         CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
854         if (!CalleeDecl || !CalleeDecl->getSubprogram())
855           continue;
856         const DISubprogram *CalleeSP = CalleeDecl->getSubprogram();
857 
858         if (CalleeSP->isDefinition()) {
859           // Ensure that a subprogram DIE for the callee is available in the
860           // appropriate CU.
861           CalleeDIE = &constructSubprogramDefinitionDIE(CalleeSP);
862         } else {
863           // Create the declaration DIE if it is missing. This is required to
864           // support compilation of old bitcode with an incomplete list of
865           // retained metadata.
866           CalleeDIE = CU.getOrCreateSubprogramDIE(CalleeSP);
867         }
868         assert(CalleeDIE && "Must have a DIE for the callee");
869       }
870 
871       // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
872 
873       bool IsTail = TII->isTailCall(MI);
874 
875       // If MI is in a bundle, the label was created after the bundle since
876       // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
877       // to search for that label below.
878       const MachineInstr *TopLevelCallMI =
879           MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
880 
881       // For tail calls, no return PC information is needed.
882       // For regular calls (and tail calls in GDB tuning), the return PC
883       // is needed to disambiguate paths in the call graph which could lead to
884       // some target function.
885       const MCSymbol *PCAddr =
886           (IsTail && !tuneForGDB())
887               ? nullptr
888               : const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI));
889 
890       assert((IsTail || PCAddr) && "Call without return PC information");
891 
892       LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
893                         << (CalleeDecl ? CalleeDecl->getName()
894                                        : StringRef(MF.getSubtarget()
895                                                        .getRegisterInfo()
896                                                        ->getName(CallReg)))
897                         << (IsTail ? " [IsTail]" : "") << "\n");
898 
899       DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(ScopeDIE, CalleeDIE,
900                                                       IsTail, PCAddr, CallReg);
901 
902       // Optionally emit call-site-param debug info.
903       if (emitDebugEntryValues()) {
904         ParamSet Params;
905         // Try to interpret values of call site parameters.
906         collectCallSiteParameters(&MI, Params);
907         CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
908       }
909     }
910   }
911 }
912 
913 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
914   if (!U.hasDwarfPubSections())
915     return;
916 
917   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
918 }
919 
920 void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
921                                       DwarfCompileUnit &NewCU) {
922   DIE &Die = NewCU.getUnitDie();
923   StringRef FN = DIUnit->getFilename();
924 
925   StringRef Producer = DIUnit->getProducer();
926   StringRef Flags = DIUnit->getFlags();
927   if (!Flags.empty() && !useAppleExtensionAttributes()) {
928     std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
929     NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
930   } else
931     NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
932 
933   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
934                 DIUnit->getSourceLanguage());
935   NewCU.addString(Die, dwarf::DW_AT_name, FN);
936   StringRef SysRoot = DIUnit->getSysRoot();
937   if (!SysRoot.empty())
938     NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
939   StringRef SDK = DIUnit->getSDK();
940   if (!SDK.empty())
941     NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
942 
943   // Add DW_str_offsets_base to the unit DIE, except for split units.
944   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
945     NewCU.addStringOffsetsStart();
946 
947   if (!useSplitDwarf()) {
948     NewCU.initStmtList();
949 
950     // If we're using split dwarf the compilation dir is going to be in the
951     // skeleton CU and so we don't need to duplicate it here.
952     if (!CompilationDir.empty())
953       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
954     addGnuPubAttributes(NewCU, Die);
955   }
956 
957   if (useAppleExtensionAttributes()) {
958     if (DIUnit->isOptimized())
959       NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
960 
961     StringRef Flags = DIUnit->getFlags();
962     if (!Flags.empty())
963       NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
964 
965     if (unsigned RVer = DIUnit->getRuntimeVersion())
966       NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
967                     dwarf::DW_FORM_data1, RVer);
968   }
969 
970   if (DIUnit->getDWOId()) {
971     // This CU is either a clang module DWO or a skeleton CU.
972     NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
973                   DIUnit->getDWOId());
974     if (!DIUnit->getSplitDebugFilename().empty()) {
975       // This is a prefabricated skeleton CU.
976       dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
977                                          ? dwarf::DW_AT_dwo_name
978                                          : dwarf::DW_AT_GNU_dwo_name;
979       NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
980     }
981   }
982 }
983 // Create new DwarfCompileUnit for the given metadata node with tag
984 // DW_TAG_compile_unit.
985 DwarfCompileUnit &
986 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
987   if (auto *CU = CUMap.lookup(DIUnit))
988     return *CU;
989 
990   CompilationDir = DIUnit->getDirectory();
991 
992   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
993       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
994   DwarfCompileUnit &NewCU = *OwnedUnit;
995   InfoHolder.addUnit(std::move(OwnedUnit));
996 
997   for (auto *IE : DIUnit->getImportedEntities())
998     NewCU.addImportedEntity(IE);
999 
1000   // LTO with assembly output shares a single line table amongst multiple CUs.
1001   // To avoid the compilation directory being ambiguous, let the line table
1002   // explicitly describe the directory of all files, never relying on the
1003   // compilation directory.
1004   if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
1005     Asm->OutStreamer->emitDwarfFile0Directive(
1006         CompilationDir, DIUnit->getFilename(),
1007         NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(),
1008         NewCU.getUniqueID());
1009 
1010   if (useSplitDwarf()) {
1011     NewCU.setSkeleton(constructSkeletonCU(NewCU));
1012     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
1013   } else {
1014     finishUnitAttributes(DIUnit, NewCU);
1015     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
1016   }
1017 
1018   CUMap.insert({DIUnit, &NewCU});
1019   CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
1020   return NewCU;
1021 }
1022 
1023 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
1024                                                   const DIImportedEntity *N) {
1025   if (isa<DILocalScope>(N->getScope()))
1026     return;
1027   if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
1028     D->addChild(TheCU.constructImportedEntityDIE(N));
1029 }
1030 
1031 /// Sort and unique GVEs by comparing their fragment offset.
1032 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
1033 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
1034   llvm::sort(
1035       GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
1036         // Sort order: first null exprs, then exprs without fragment
1037         // info, then sort by fragment offset in bits.
1038         // FIXME: Come up with a more comprehensive comparator so
1039         // the sorting isn't non-deterministic, and so the following
1040         // std::unique call works correctly.
1041         if (!A.Expr || !B.Expr)
1042           return !!B.Expr;
1043         auto FragmentA = A.Expr->getFragmentInfo();
1044         auto FragmentB = B.Expr->getFragmentInfo();
1045         if (!FragmentA || !FragmentB)
1046           return !!FragmentB;
1047         return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
1048       });
1049   GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
1050                          [](DwarfCompileUnit::GlobalExpr A,
1051                             DwarfCompileUnit::GlobalExpr B) {
1052                            return A.Expr == B.Expr;
1053                          }),
1054              GVEs.end());
1055   return GVEs;
1056 }
1057 
1058 // Emit all Dwarf sections that should come prior to the content. Create
1059 // global DIEs and emit initial debug info sections. This is invoked by
1060 // the target AsmPrinter.
1061 void DwarfDebug::beginModule() {
1062   NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
1063                      DWARFGroupDescription, TimePassesIsEnabled);
1064   if (DisableDebugInfoPrinting) {
1065     MMI->setDebugInfoAvailability(false);
1066     return;
1067   }
1068 
1069   const Module *M = MMI->getModule();
1070 
1071   unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
1072                                        M->debug_compile_units_end());
1073   // Tell MMI whether we have debug info.
1074   assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) &&
1075          "DebugInfoAvailabilty initialized unexpectedly");
1076   SingleCU = NumDebugCUs == 1;
1077   DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
1078       GVMap;
1079   for (const GlobalVariable &Global : M->globals()) {
1080     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1081     Global.getDebugInfo(GVs);
1082     for (auto *GVE : GVs)
1083       GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
1084   }
1085 
1086   // Create the symbol that designates the start of the unit's contribution
1087   // to the string offsets table. In a split DWARF scenario, only the skeleton
1088   // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
1089   if (useSegmentedStringOffsetsTable())
1090     (useSplitDwarf() ? SkeletonHolder : InfoHolder)
1091         .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
1092 
1093 
1094   // Create the symbols that designates the start of the DWARF v5 range list
1095   // and locations list tables. They are located past the table headers.
1096   if (getDwarfVersion() >= 5) {
1097     DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1098     Holder.setRnglistsTableBaseSym(
1099         Asm->createTempSymbol("rnglists_table_base"));
1100 
1101     if (useSplitDwarf())
1102       InfoHolder.setRnglistsTableBaseSym(
1103           Asm->createTempSymbol("rnglists_dwo_table_base"));
1104   }
1105 
1106   // Create the symbol that points to the first entry following the debug
1107   // address table (.debug_addr) header.
1108   AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1109   DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1110 
1111   for (DICompileUnit *CUNode : M->debug_compile_units()) {
1112     // FIXME: Move local imported entities into a list attached to the
1113     // subprogram, then this search won't be needed and a
1114     // getImportedEntities().empty() test should go below with the rest.
1115     bool HasNonLocalImportedEntities = llvm::any_of(
1116         CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
1117           return !isa<DILocalScope>(IE->getScope());
1118         });
1119 
1120     if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
1121         CUNode->getRetainedTypes().empty() &&
1122         CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1123       continue;
1124 
1125     DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1126 
1127     // Global Variables.
1128     for (auto *GVE : CUNode->getGlobalVariables()) {
1129       // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1130       // already know about the variable and it isn't adding a constant
1131       // expression.
1132       auto &GVMapEntry = GVMap[GVE->getVariable()];
1133       auto *Expr = GVE->getExpression();
1134       if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1135         GVMapEntry.push_back({nullptr, Expr});
1136     }
1137     DenseSet<DIGlobalVariable *> Processed;
1138     for (auto *GVE : CUNode->getGlobalVariables()) {
1139       DIGlobalVariable *GV = GVE->getVariable();
1140       if (Processed.insert(GV).second)
1141         CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1142     }
1143 
1144     for (auto *Ty : CUNode->getEnumTypes()) {
1145       // The enum types array by design contains pointers to
1146       // MDNodes rather than DIRefs. Unique them here.
1147       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1148     }
1149     for (auto *Ty : CUNode->getRetainedTypes()) {
1150       // The retained types array by design contains pointers to
1151       // MDNodes rather than DIRefs. Unique them here.
1152       if (DIType *RT = dyn_cast<DIType>(Ty))
1153           // There is no point in force-emitting a forward declaration.
1154           CU.getOrCreateTypeDIE(RT);
1155     }
1156     // Emit imported_modules last so that the relevant context is already
1157     // available.
1158     for (auto *IE : CUNode->getImportedEntities())
1159       constructAndAddImportedEntityDIE(CU, IE);
1160   }
1161 }
1162 
1163 void DwarfDebug::finishEntityDefinitions() {
1164   for (const auto &Entity : ConcreteEntities) {
1165     DIE *Die = Entity->getDIE();
1166     assert(Die);
1167     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1168     // in the ConcreteEntities list, rather than looking it up again here.
1169     // DIE::getUnit isn't simple - it walks parent pointers, etc.
1170     DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
1171     assert(Unit);
1172     Unit->finishEntityDefinition(Entity.get());
1173   }
1174 }
1175 
1176 void DwarfDebug::finishSubprogramDefinitions() {
1177   for (const DISubprogram *SP : ProcessedSPNodes) {
1178     assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1179     forBothCUs(
1180         getOrCreateDwarfCompileUnit(SP->getUnit()),
1181         [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1182   }
1183 }
1184 
1185 void DwarfDebug::finalizeModuleInfo() {
1186   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1187 
1188   finishSubprogramDefinitions();
1189 
1190   finishEntityDefinitions();
1191 
1192   // Include the DWO file name in the hash if there's more than one CU.
1193   // This handles ThinLTO's situation where imported CUs may very easily be
1194   // duplicate with the same CU partially imported into another ThinLTO unit.
1195   StringRef DWOName;
1196   if (CUMap.size() > 1)
1197     DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
1198 
1199   // Handle anything that needs to be done on a per-unit basis after
1200   // all other generation.
1201   for (const auto &P : CUMap) {
1202     auto &TheCU = *P.second;
1203     if (TheCU.getCUNode()->isDebugDirectivesOnly())
1204       continue;
1205     // Emit DW_AT_containing_type attribute to connect types with their
1206     // vtable holding type.
1207     TheCU.constructContainingTypeDIEs();
1208 
1209     // Add CU specific attributes if we need to add any.
1210     // If we're splitting the dwarf out now that we've got the entire
1211     // CU then add the dwo id to it.
1212     auto *SkCU = TheCU.getSkeleton();
1213 
1214     bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1215 
1216     if (HasSplitUnit) {
1217       dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1218                                          ? dwarf::DW_AT_dwo_name
1219                                          : dwarf::DW_AT_GNU_dwo_name;
1220       finishUnitAttributes(TheCU.getCUNode(), TheCU);
1221       TheCU.addString(TheCU.getUnitDie(), attrDWOName,
1222                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1223       SkCU->addString(SkCU->getUnitDie(), attrDWOName,
1224                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1225       // Emit a unique identifier for this CU.
1226       uint64_t ID =
1227           DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
1228       if (getDwarfVersion() >= 5) {
1229         TheCU.setDWOId(ID);
1230         SkCU->setDWOId(ID);
1231       } else {
1232         TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1233                       dwarf::DW_FORM_data8, ID);
1234         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1235                       dwarf::DW_FORM_data8, ID);
1236       }
1237 
1238       if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1239         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
1240         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1241                               Sym, Sym);
1242       }
1243     } else if (SkCU) {
1244       finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1245     }
1246 
1247     // If we have code split among multiple sections or non-contiguous
1248     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1249     // remain in the .o file, otherwise add a DW_AT_low_pc.
1250     // FIXME: We should use ranges allow reordering of code ala
1251     // .subsections_via_symbols in mach-o. This would mean turning on
1252     // ranges for all subprogram DIEs for mach-o.
1253     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1254 
1255     if (unsigned NumRanges = TheCU.getRanges().size()) {
1256       if (NumRanges > 1 && useRangesSection())
1257         // A DW_AT_low_pc attribute may also be specified in combination with
1258         // DW_AT_ranges to specify the default base address for use in
1259         // location lists (see Section 2.6.2) and range lists (see Section
1260         // 2.17.3).
1261         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
1262       else
1263         U.setBaseAddress(TheCU.getRanges().front().Begin);
1264       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1265     }
1266 
1267     // We don't keep track of which addresses are used in which CU so this
1268     // is a bit pessimistic under LTO.
1269     if ((!AddrPool.isEmpty() || TheCU.hasRangeLists()) &&
1270         (getDwarfVersion() >= 5 || HasSplitUnit))
1271       U.addAddrTableBase();
1272 
1273     if (getDwarfVersion() >= 5) {
1274       if (U.hasRangeLists())
1275         U.addRnglistsBase();
1276 
1277       if (!DebugLocs.getLists().empty()) {
1278         if (!useSplitDwarf())
1279           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
1280                             DebugLocs.getSym(),
1281                             TLOF.getDwarfLoclistsSection()->getBeginSymbol());
1282       }
1283     }
1284 
1285     auto *CUNode = cast<DICompileUnit>(P.first);
1286     // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
1287     if (CUNode->getMacros()) {
1288       if (useSplitDwarf())
1289         TheCU.addSectionDelta(TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1290                             U.getMacroLabelBegin(),
1291                             TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
1292       else
1293         U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
1294                           U.getMacroLabelBegin(),
1295                           TLOF.getDwarfMacinfoSection()->getBeginSymbol());
1296     }
1297   }
1298 
1299   // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1300   for (auto *CUNode : MMI->getModule()->debug_compile_units())
1301     if (CUNode->getDWOId())
1302       getOrCreateDwarfCompileUnit(CUNode);
1303 
1304   // Compute DIE offsets and sizes.
1305   InfoHolder.computeSizeAndOffsets();
1306   if (useSplitDwarf())
1307     SkeletonHolder.computeSizeAndOffsets();
1308 }
1309 
1310 // Emit all Dwarf sections that should come after the content.
1311 void DwarfDebug::endModule() {
1312   assert(CurFn == nullptr);
1313   assert(CurMI == nullptr);
1314 
1315   for (const auto &P : CUMap) {
1316     auto &CU = *P.second;
1317     CU.createBaseTypeDIEs();
1318   }
1319 
1320   // If we aren't actually generating debug info (check beginModule -
1321   // conditionalized on !DisableDebugInfoPrinting and the presence of the
1322   // llvm.dbg.cu metadata node)
1323   if (!MMI->hasDebugInfo())
1324     return;
1325 
1326   // Finalize the debug info for the module.
1327   finalizeModuleInfo();
1328 
1329   if (useSplitDwarf())
1330     // Emit debug_loc.dwo/debug_loclists.dwo section.
1331     emitDebugLocDWO();
1332   else
1333     // Emit debug_loc/debug_loclists section.
1334     emitDebugLoc();
1335 
1336   // Corresponding abbreviations into a abbrev section.
1337   emitAbbreviations();
1338 
1339   // Emit all the DIEs into a debug info section.
1340   emitDebugInfo();
1341 
1342   // Emit info into a debug aranges section.
1343   if (GenerateARangeSection)
1344     emitDebugARanges();
1345 
1346   // Emit info into a debug ranges section.
1347   emitDebugRanges();
1348 
1349   if (useSplitDwarf())
1350   // Emit info into a debug macinfo.dwo section.
1351     emitDebugMacinfoDWO();
1352   else
1353   // Emit info into a debug macinfo section.
1354     emitDebugMacinfo();
1355 
1356   emitDebugStr();
1357 
1358   if (useSplitDwarf()) {
1359     emitDebugStrDWO();
1360     emitDebugInfoDWO();
1361     emitDebugAbbrevDWO();
1362     emitDebugLineDWO();
1363     emitDebugRangesDWO();
1364   }
1365 
1366   emitDebugAddr();
1367 
1368   // Emit info into the dwarf accelerator table sections.
1369   switch (getAccelTableKind()) {
1370   case AccelTableKind::Apple:
1371     emitAccelNames();
1372     emitAccelObjC();
1373     emitAccelNamespaces();
1374     emitAccelTypes();
1375     break;
1376   case AccelTableKind::Dwarf:
1377     emitAccelDebugNames();
1378     break;
1379   case AccelTableKind::None:
1380     break;
1381   case AccelTableKind::Default:
1382     llvm_unreachable("Default should have already been resolved.");
1383   }
1384 
1385   // Emit the pubnames and pubtypes sections if requested.
1386   emitDebugPubSections();
1387 
1388   // clean up.
1389   // FIXME: AbstractVariables.clear();
1390 }
1391 
1392 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1393                                                const DINode *Node,
1394                                                const MDNode *ScopeNode) {
1395   if (CU.getExistingAbstractEntity(Node))
1396     return;
1397 
1398   CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
1399                                        cast<DILocalScope>(ScopeNode)));
1400 }
1401 
1402 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1403     const DINode *Node, const MDNode *ScopeNode) {
1404   if (CU.getExistingAbstractEntity(Node))
1405     return;
1406 
1407   if (LexicalScope *Scope =
1408           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1409     CU.createAbstractEntity(Node, Scope);
1410 }
1411 
1412 // Collect variable information from side table maintained by MF.
1413 void DwarfDebug::collectVariableInfoFromMFTable(
1414     DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1415   SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1416   LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
1417   for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1418     if (!VI.Var)
1419       continue;
1420     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1421            "Expected inlined-at fields to agree");
1422 
1423     InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1424     Processed.insert(Var);
1425     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1426 
1427     // If variable scope is not found then skip this variable.
1428     if (!Scope) {
1429       LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1430                         << ", no variable scope found\n");
1431       continue;
1432     }
1433 
1434     ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1435     auto RegVar = std::make_unique<DbgVariable>(
1436                     cast<DILocalVariable>(Var.first), Var.second);
1437     RegVar->initializeMMI(VI.Expr, VI.Slot);
1438     LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
1439                       << "\n");
1440     if (DbgVariable *DbgVar = MFVars.lookup(Var))
1441       DbgVar->addMMIEntry(*RegVar);
1442     else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1443       MFVars.insert({Var, RegVar.get()});
1444       ConcreteEntities.push_back(std::move(RegVar));
1445     }
1446   }
1447 }
1448 
1449 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1450 /// enclosing lexical scope. The check ensures there are no other instructions
1451 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1452 /// either open or otherwise rolls off the end of the scope.
1453 static bool validThroughout(LexicalScopes &LScopes,
1454                             const MachineInstr *DbgValue,
1455                             const MachineInstr *RangeEnd) {
1456   assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1457   auto MBB = DbgValue->getParent();
1458   auto DL = DbgValue->getDebugLoc();
1459   auto *LScope = LScopes.findLexicalScope(DL);
1460   // Scope doesn't exist; this is a dead DBG_VALUE.
1461   if (!LScope)
1462     return false;
1463   auto &LSRange = LScope->getRanges();
1464   if (LSRange.size() == 0)
1465     return false;
1466 
1467   // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1468   const MachineInstr *LScopeBegin = LSRange.front().first;
1469   // Early exit if the lexical scope begins outside of the current block.
1470   if (LScopeBegin->getParent() != MBB)
1471     return false;
1472   MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1473   for (++Pred; Pred != MBB->rend(); ++Pred) {
1474     if (Pred->getFlag(MachineInstr::FrameSetup))
1475       break;
1476     auto PredDL = Pred->getDebugLoc();
1477     if (!PredDL || Pred->isMetaInstruction())
1478       continue;
1479     // Check whether the instruction preceding the DBG_VALUE is in the same
1480     // (sub)scope as the DBG_VALUE.
1481     if (DL->getScope() == PredDL->getScope())
1482       return false;
1483     auto *PredScope = LScopes.findLexicalScope(PredDL);
1484     if (!PredScope || LScope->dominates(PredScope))
1485       return false;
1486   }
1487 
1488   // If the range of the DBG_VALUE is open-ended, report success.
1489   if (!RangeEnd)
1490     return true;
1491 
1492   // Fail if there are instructions belonging to our scope in another block.
1493   const MachineInstr *LScopeEnd = LSRange.back().second;
1494   if (LScopeEnd->getParent() != MBB)
1495     return false;
1496 
1497   // Single, constant DBG_VALUEs in the prologue are promoted to be live
1498   // throughout the function. This is a hack, presumably for DWARF v2 and not
1499   // necessarily correct. It would be much better to use a dbg.declare instead
1500   // if we know the constant is live throughout the scope.
1501   if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1502     return true;
1503 
1504   return false;
1505 }
1506 
1507 /// Build the location list for all DBG_VALUEs in the function that
1508 /// describe the same variable. The resulting DebugLocEntries will have
1509 /// strict monotonically increasing begin addresses and will never
1510 /// overlap. If the resulting list has only one entry that is valid
1511 /// throughout variable's scope return true.
1512 //
1513 // See the definition of DbgValueHistoryMap::Entry for an explanation of the
1514 // different kinds of history map entries. One thing to be aware of is that if
1515 // a debug value is ended by another entry (rather than being valid until the
1516 // end of the function), that entry's instruction may or may not be included in
1517 // the range, depending on if the entry is a clobbering entry (it has an
1518 // instruction that clobbers one or more preceding locations), or if it is an
1519 // (overlapping) debug value entry. This distinction can be seen in the example
1520 // below. The first debug value is ended by the clobbering entry 2, and the
1521 // second and third debug values are ended by the overlapping debug value entry
1522 // 4.
1523 //
1524 // Input:
1525 //
1526 //   History map entries [type, end index, mi]
1527 //
1528 // 0 |      [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1529 // 1 | |    [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1530 // 2 | |    [Clobber, $reg0 = [...], -, -]
1531 // 3   | |  [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1532 // 4        [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1533 //
1534 // Output [start, end) [Value...]:
1535 //
1536 // [0-1)    [(reg0, fragment 0, 32)]
1537 // [1-3)    [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1538 // [3-4)    [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1539 // [4-)     [(@g, fragment 0, 96)]
1540 bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1541                                    const DbgValueHistoryMap::Entries &Entries) {
1542   using OpenRange =
1543       std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1544   SmallVector<OpenRange, 4> OpenRanges;
1545   bool isSafeForSingleLocation = true;
1546   const MachineInstr *StartDebugMI = nullptr;
1547   const MachineInstr *EndMI = nullptr;
1548 
1549   for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1550     const MachineInstr *Instr = EI->getInstr();
1551 
1552     // Remove all values that are no longer live.
1553     size_t Index = std::distance(EB, EI);
1554     auto Last =
1555         remove_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1556     OpenRanges.erase(Last, OpenRanges.end());
1557 
1558     // If we are dealing with a clobbering entry, this iteration will result in
1559     // a location list entry starting after the clobbering instruction.
1560     const MCSymbol *StartLabel =
1561         EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1562     assert(StartLabel &&
1563            "Forgot label before/after instruction starting a range!");
1564 
1565     const MCSymbol *EndLabel;
1566     if (std::next(EI) == Entries.end()) {
1567       EndLabel = Asm->getFunctionEnd();
1568       if (EI->isClobber())
1569         EndMI = EI->getInstr();
1570     }
1571     else if (std::next(EI)->isClobber())
1572       EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1573     else
1574       EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1575     assert(EndLabel && "Forgot label after instruction ending a range!");
1576 
1577     if (EI->isDbgValue())
1578       LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1579 
1580     // If this history map entry has a debug value, add that to the list of
1581     // open ranges and check if its location is valid for a single value
1582     // location.
1583     if (EI->isDbgValue()) {
1584       // Do not add undef debug values, as they are redundant information in
1585       // the location list entries. An undef debug results in an empty location
1586       // description. If there are any non-undef fragments then padding pieces
1587       // with empty location descriptions will automatically be inserted, and if
1588       // all fragments are undef then the whole location list entry is
1589       // redundant.
1590       if (!Instr->isUndefDebugValue()) {
1591         auto Value = getDebugLocValue(Instr);
1592         OpenRanges.emplace_back(EI->getEndIndex(), Value);
1593 
1594         // TODO: Add support for single value fragment locations.
1595         if (Instr->getDebugExpression()->isFragment())
1596           isSafeForSingleLocation = false;
1597 
1598         if (!StartDebugMI)
1599           StartDebugMI = Instr;
1600       } else {
1601         isSafeForSingleLocation = false;
1602       }
1603     }
1604 
1605     // Location list entries with empty location descriptions are redundant
1606     // information in DWARF, so do not emit those.
1607     if (OpenRanges.empty())
1608       continue;
1609 
1610     // Omit entries with empty ranges as they do not have any effect in DWARF.
1611     if (StartLabel == EndLabel) {
1612       LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1613       continue;
1614     }
1615 
1616     SmallVector<DbgValueLoc, 4> Values;
1617     for (auto &R : OpenRanges)
1618       Values.push_back(R.second);
1619     DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1620 
1621     // Attempt to coalesce the ranges of two otherwise identical
1622     // DebugLocEntries.
1623     auto CurEntry = DebugLoc.rbegin();
1624     LLVM_DEBUG({
1625       dbgs() << CurEntry->getValues().size() << " Values:\n";
1626       for (auto &Value : CurEntry->getValues())
1627         Value.dump();
1628       dbgs() << "-----\n";
1629     });
1630 
1631     auto PrevEntry = std::next(CurEntry);
1632     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1633       DebugLoc.pop_back();
1634   }
1635 
1636   return DebugLoc.size() == 1 && isSafeForSingleLocation &&
1637          validThroughout(LScopes, StartDebugMI, EndMI);
1638 }
1639 
1640 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1641                                             LexicalScope &Scope,
1642                                             const DINode *Node,
1643                                             const DILocation *Location,
1644                                             const MCSymbol *Sym) {
1645   ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1646   if (isa<const DILocalVariable>(Node)) {
1647     ConcreteEntities.push_back(
1648         std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1649                                        Location));
1650     InfoHolder.addScopeVariable(&Scope,
1651         cast<DbgVariable>(ConcreteEntities.back().get()));
1652   } else if (isa<const DILabel>(Node)) {
1653     ConcreteEntities.push_back(
1654         std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1655                                     Location, Sym));
1656     InfoHolder.addScopeLabel(&Scope,
1657         cast<DbgLabel>(ConcreteEntities.back().get()));
1658   }
1659   return ConcreteEntities.back().get();
1660 }
1661 
1662 // Find variables for each lexical scope.
1663 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1664                                    const DISubprogram *SP,
1665                                    DenseSet<InlinedEntity> &Processed) {
1666   // Grab the variable info that was squirreled away in the MMI side-table.
1667   collectVariableInfoFromMFTable(TheCU, Processed);
1668 
1669   for (const auto &I : DbgValues) {
1670     InlinedEntity IV = I.first;
1671     if (Processed.count(IV))
1672       continue;
1673 
1674     // Instruction ranges, specifying where IV is accessible.
1675     const auto &HistoryMapEntries = I.second;
1676     if (HistoryMapEntries.empty())
1677       continue;
1678 
1679     LexicalScope *Scope = nullptr;
1680     const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1681     if (const DILocation *IA = IV.second)
1682       Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1683     else
1684       Scope = LScopes.findLexicalScope(LocalVar->getScope());
1685     // If variable scope is not found then skip this variable.
1686     if (!Scope)
1687       continue;
1688 
1689     Processed.insert(IV);
1690     DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1691                                             *Scope, LocalVar, IV.second));
1692 
1693     const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1694     assert(MInsn->isDebugValue() && "History must begin with debug value");
1695 
1696     // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1697     // If the history map contains a single debug value, there may be an
1698     // additional entry which clobbers the debug value.
1699     size_t HistSize = HistoryMapEntries.size();
1700     bool SingleValueWithClobber =
1701         HistSize == 2 && HistoryMapEntries[1].isClobber();
1702     if (HistSize == 1 || SingleValueWithClobber) {
1703       const auto *End =
1704           SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1705       if (validThroughout(LScopes, MInsn, End)) {
1706         RegVar->initializeDbgValue(MInsn);
1707         continue;
1708       }
1709     }
1710 
1711     // Do not emit location lists if .debug_loc secton is disabled.
1712     if (!useLocSection())
1713       continue;
1714 
1715     // Handle multiple DBG_VALUE instructions describing one variable.
1716     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1717 
1718     // Build the location list for this variable.
1719     SmallVector<DebugLocEntry, 8> Entries;
1720     bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1721 
1722     // Check whether buildLocationList managed to merge all locations to one
1723     // that is valid throughout the variable's scope. If so, produce single
1724     // value location.
1725     if (isValidSingleLocation) {
1726       RegVar->initializeDbgValue(Entries[0].getValues()[0]);
1727       continue;
1728     }
1729 
1730     // If the variable has a DIBasicType, extract it.  Basic types cannot have
1731     // unique identifiers, so don't bother resolving the type with the
1732     // identifier map.
1733     const DIBasicType *BT = dyn_cast<DIBasicType>(
1734         static_cast<const Metadata *>(LocalVar->getType()));
1735 
1736     // Finalize the entry by lowering it into a DWARF bytestream.
1737     for (auto &Entry : Entries)
1738       Entry.finalize(*Asm, List, BT, TheCU);
1739   }
1740 
1741   // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1742   // DWARF-related DbgLabel.
1743   for (const auto &I : DbgLabels) {
1744     InlinedEntity IL = I.first;
1745     const MachineInstr *MI = I.second;
1746     if (MI == nullptr)
1747       continue;
1748 
1749     LexicalScope *Scope = nullptr;
1750     const DILabel *Label = cast<DILabel>(IL.first);
1751     // The scope could have an extra lexical block file.
1752     const DILocalScope *LocalScope =
1753         Label->getScope()->getNonLexicalBlockFileScope();
1754     // Get inlined DILocation if it is inlined label.
1755     if (const DILocation *IA = IL.second)
1756       Scope = LScopes.findInlinedScope(LocalScope, IA);
1757     else
1758       Scope = LScopes.findLexicalScope(LocalScope);
1759     // If label scope is not found then skip this label.
1760     if (!Scope)
1761       continue;
1762 
1763     Processed.insert(IL);
1764     /// At this point, the temporary label is created.
1765     /// Save the temporary label to DbgLabel entity to get the
1766     /// actually address when generating Dwarf DIE.
1767     MCSymbol *Sym = getLabelBeforeInsn(MI);
1768     createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1769   }
1770 
1771   // Collect info for variables/labels that were optimized out.
1772   for (const DINode *DN : SP->getRetainedNodes()) {
1773     if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1774       continue;
1775     LexicalScope *Scope = nullptr;
1776     if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1777       Scope = LScopes.findLexicalScope(DV->getScope());
1778     } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1779       Scope = LScopes.findLexicalScope(DL->getScope());
1780     }
1781 
1782     if (Scope)
1783       createConcreteEntity(TheCU, *Scope, DN, nullptr);
1784   }
1785 }
1786 
1787 // Process beginning of an instruction.
1788 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1789   DebugHandlerBase::beginInstruction(MI);
1790   assert(CurMI);
1791 
1792   const auto *SP = MI->getMF()->getFunction().getSubprogram();
1793   if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1794     return;
1795 
1796   // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1797   // If the instruction is part of the function frame setup code, do not emit
1798   // any line record, as there is no correspondence with any user code.
1799   if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1800     return;
1801   const DebugLoc &DL = MI->getDebugLoc();
1802   // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1803   // the last line number actually emitted, to see if it was line 0.
1804   unsigned LastAsmLine =
1805       Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1806 
1807   // Request a label after the call in order to emit AT_return_pc information
1808   // in call site entries. TODO: Add support for targets with delay slots.
1809   if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot())
1810     requestLabelAfterInsn(MI);
1811 
1812   if (DL == PrevInstLoc) {
1813     // If we have an ongoing unspecified location, nothing to do here.
1814     if (!DL)
1815       return;
1816     // We have an explicit location, same as the previous location.
1817     // But we might be coming back to it after a line 0 record.
1818     if (LastAsmLine == 0 && DL.getLine() != 0) {
1819       // Reinstate the source location but not marked as a statement.
1820       const MDNode *Scope = DL.getScope();
1821       recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1822     }
1823     return;
1824   }
1825 
1826   if (!DL) {
1827     // We have an unspecified location, which might want to be line 0.
1828     // If we have already emitted a line-0 record, don't repeat it.
1829     if (LastAsmLine == 0)
1830       return;
1831     // If user said Don't Do That, don't do that.
1832     if (UnknownLocations == Disable)
1833       return;
1834     // See if we have a reason to emit a line-0 record now.
1835     // Reasons to emit a line-0 record include:
1836     // - User asked for it (UnknownLocations).
1837     // - Instruction has a label, so it's referenced from somewhere else,
1838     //   possibly debug information; we want it to have a source location.
1839     // - Instruction is at the top of a block; we don't want to inherit the
1840     //   location from the physically previous (maybe unrelated) block.
1841     if (UnknownLocations == Enable || PrevLabel ||
1842         (PrevInstBB && PrevInstBB != MI->getParent())) {
1843       // Preserve the file and column numbers, if we can, to save space in
1844       // the encoded line table.
1845       // Do not update PrevInstLoc, it remembers the last non-0 line.
1846       const MDNode *Scope = nullptr;
1847       unsigned Column = 0;
1848       if (PrevInstLoc) {
1849         Scope = PrevInstLoc.getScope();
1850         Column = PrevInstLoc.getCol();
1851       }
1852       recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1853     }
1854     return;
1855   }
1856 
1857   // We have an explicit location, different from the previous location.
1858   // Don't repeat a line-0 record, but otherwise emit the new location.
1859   // (The new location might be an explicit line 0, which we do emit.)
1860   if (DL.getLine() == 0 && LastAsmLine == 0)
1861     return;
1862   unsigned Flags = 0;
1863   if (DL == PrologEndLoc) {
1864     Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1865     PrologEndLoc = DebugLoc();
1866   }
1867   // If the line changed, we call that a new statement; unless we went to
1868   // line 0 and came back, in which case it is not a new statement.
1869   unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1870   if (DL.getLine() && DL.getLine() != OldLine)
1871     Flags |= DWARF2_FLAG_IS_STMT;
1872 
1873   const MDNode *Scope = DL.getScope();
1874   recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1875 
1876   // If we're not at line 0, remember this location.
1877   if (DL.getLine())
1878     PrevInstLoc = DL;
1879 }
1880 
1881 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1882   // First known non-DBG_VALUE and non-frame setup location marks
1883   // the beginning of the function body.
1884   for (const auto &MBB : *MF)
1885     for (const auto &MI : MBB)
1886       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1887           MI.getDebugLoc())
1888         return MI.getDebugLoc();
1889   return DebugLoc();
1890 }
1891 
1892 /// Register a source line with debug info. Returns the  unique label that was
1893 /// emitted and which provides correspondence to the source line list.
1894 static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
1895                              const MDNode *S, unsigned Flags, unsigned CUID,
1896                              uint16_t DwarfVersion,
1897                              ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
1898   StringRef Fn;
1899   unsigned FileNo = 1;
1900   unsigned Discriminator = 0;
1901   if (auto *Scope = cast_or_null<DIScope>(S)) {
1902     Fn = Scope->getFilename();
1903     if (Line != 0 && DwarfVersion >= 4)
1904       if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1905         Discriminator = LBF->getDiscriminator();
1906 
1907     FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
1908                  .getOrCreateSourceID(Scope->getFile());
1909   }
1910   Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
1911                                          Discriminator, Fn);
1912 }
1913 
1914 DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
1915                                              unsigned CUID) {
1916   // Get beginning of function.
1917   if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
1918     // Ensure the compile unit is created if the function is called before
1919     // beginFunction().
1920     (void)getOrCreateDwarfCompileUnit(
1921         MF.getFunction().getSubprogram()->getUnit());
1922     // We'd like to list the prologue as "not statements" but GDB behaves
1923     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1924     const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1925     ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
1926                        CUID, getDwarfVersion(), getUnits());
1927     return PrologEndLoc;
1928   }
1929   return DebugLoc();
1930 }
1931 
1932 // Gather pre-function debug information.  Assumes being called immediately
1933 // after the function entry point has been emitted.
1934 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1935   CurFn = MF;
1936 
1937   auto *SP = MF->getFunction().getSubprogram();
1938   assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1939   if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1940     return;
1941 
1942   DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1943 
1944   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1945   // belongs to so that we add to the correct per-cu line table in the
1946   // non-asm case.
1947   if (Asm->OutStreamer->hasRawTextSupport())
1948     // Use a single line table if we are generating assembly.
1949     Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1950   else
1951     Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1952 
1953   // Record beginning of function.
1954   PrologEndLoc = emitInitialLocDirective(
1955       *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
1956 }
1957 
1958 void DwarfDebug::skippedNonDebugFunction() {
1959   // If we don't have a subprogram for this function then there will be a hole
1960   // in the range information. Keep note of this by setting the previously used
1961   // section to nullptr.
1962   PrevCU = nullptr;
1963   CurFn = nullptr;
1964 }
1965 
1966 // Gather and emit post-function debug information.
1967 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1968   const DISubprogram *SP = MF->getFunction().getSubprogram();
1969 
1970   assert(CurFn == MF &&
1971       "endFunction should be called with the same function as beginFunction");
1972 
1973   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1974   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1975 
1976   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1977   assert(!FnScope || SP == FnScope->getScopeNode());
1978   DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1979   if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
1980     PrevLabel = nullptr;
1981     CurFn = nullptr;
1982     return;
1983   }
1984 
1985   DenseSet<InlinedEntity> Processed;
1986   collectEntityInfo(TheCU, SP, Processed);
1987 
1988   // Add the range of this function to the list of ranges for the CU.
1989   TheCU.addRange({Asm->getFunctionBegin(), Asm->getFunctionEnd()});
1990 
1991   // Under -gmlt, skip building the subprogram if there are no inlined
1992   // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1993   // is still needed as we need its source location.
1994   if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1995       TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1996       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1997     assert(InfoHolder.getScopeVariables().empty());
1998     PrevLabel = nullptr;
1999     CurFn = nullptr;
2000     return;
2001   }
2002 
2003 #ifndef NDEBUG
2004   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
2005 #endif
2006   // Construct abstract scopes.
2007   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
2008     auto *SP = cast<DISubprogram>(AScope->getScopeNode());
2009     for (const DINode *DN : SP->getRetainedNodes()) {
2010       if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
2011         continue;
2012 
2013       const MDNode *Scope = nullptr;
2014       if (auto *DV = dyn_cast<DILocalVariable>(DN))
2015         Scope = DV->getScope();
2016       else if (auto *DL = dyn_cast<DILabel>(DN))
2017         Scope = DL->getScope();
2018       else
2019         llvm_unreachable("Unexpected DI type!");
2020 
2021       // Collect info for variables/labels that were optimized out.
2022       ensureAbstractEntityIsCreated(TheCU, DN, Scope);
2023       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
2024              && "ensureAbstractEntityIsCreated inserted abstract scopes");
2025     }
2026     constructAbstractSubprogramScopeDIE(TheCU, AScope);
2027   }
2028 
2029   ProcessedSPNodes.insert(SP);
2030   DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
2031   if (auto *SkelCU = TheCU.getSkeleton())
2032     if (!LScopes.getAbstractScopesList().empty() &&
2033         TheCU.getCUNode()->getSplitDebugInlining())
2034       SkelCU->constructSubprogramScopeDIE(SP, FnScope);
2035 
2036   // Construct call site entries.
2037   constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
2038 
2039   // Clear debug info
2040   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
2041   // DbgVariables except those that are also in AbstractVariables (since they
2042   // can be used cross-function)
2043   InfoHolder.getScopeVariables().clear();
2044   InfoHolder.getScopeLabels().clear();
2045   PrevLabel = nullptr;
2046   CurFn = nullptr;
2047 }
2048 
2049 // Register a source line with debug info. Returns the  unique label that was
2050 // emitted and which provides correspondence to the source line list.
2051 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
2052                                   unsigned Flags) {
2053   ::recordSourceLine(*Asm, Line, Col, S, Flags,
2054                      Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
2055                      getDwarfVersion(), getUnits());
2056 }
2057 
2058 //===----------------------------------------------------------------------===//
2059 // Emit Methods
2060 //===----------------------------------------------------------------------===//
2061 
2062 // Emit the debug info section.
2063 void DwarfDebug::emitDebugInfo() {
2064   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2065   Holder.emitUnits(/* UseOffsets */ false);
2066 }
2067 
2068 // Emit the abbreviation section.
2069 void DwarfDebug::emitAbbreviations() {
2070   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2071 
2072   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2073 }
2074 
2075 void DwarfDebug::emitStringOffsetsTableHeader() {
2076   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2077   Holder.getStringPool().emitStringOffsetsTableHeader(
2078       *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
2079       Holder.getStringOffsetsStartSym());
2080 }
2081 
2082 template <typename AccelTableT>
2083 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
2084                            StringRef TableName) {
2085   Asm->OutStreamer->SwitchSection(Section);
2086 
2087   // Emit the full data.
2088   emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
2089 }
2090 
2091 void DwarfDebug::emitAccelDebugNames() {
2092   // Don't emit anything if we have no compilation units to index.
2093   if (getUnits().empty())
2094     return;
2095 
2096   emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
2097 }
2098 
2099 // Emit visible names into a hashed accelerator table section.
2100 void DwarfDebug::emitAccelNames() {
2101   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
2102             "Names");
2103 }
2104 
2105 // Emit objective C classes and categories into a hashed accelerator table
2106 // section.
2107 void DwarfDebug::emitAccelObjC() {
2108   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
2109             "ObjC");
2110 }
2111 
2112 // Emit namespace dies into a hashed accelerator table.
2113 void DwarfDebug::emitAccelNamespaces() {
2114   emitAccel(AccelNamespace,
2115             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
2116             "namespac");
2117 }
2118 
2119 // Emit type dies into a hashed accelerator table.
2120 void DwarfDebug::emitAccelTypes() {
2121   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
2122             "types");
2123 }
2124 
2125 // Public name handling.
2126 // The format for the various pubnames:
2127 //
2128 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2129 // for the DIE that is named.
2130 //
2131 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2132 // into the CU and the index value is computed according to the type of value
2133 // for the DIE that is named.
2134 //
2135 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2136 // it's the offset within the debug_info/debug_types dwo section, however, the
2137 // reference in the pubname header doesn't change.
2138 
2139 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2140 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2141                                                         const DIE *Die) {
2142   // Entities that ended up only in a Type Unit reference the CU instead (since
2143   // the pub entry has offsets within the CU there's no real offset that can be
2144   // provided anyway). As it happens all such entities (namespaces and types,
2145   // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2146   // not to be true it would be necessary to persist this information from the
2147   // point at which the entry is added to the index data structure - since by
2148   // the time the index is built from that, the original type/namespace DIE in a
2149   // type unit has already been destroyed so it can't be queried for properties
2150   // like tag, etc.
2151   if (Die->getTag() == dwarf::DW_TAG_compile_unit)
2152     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
2153                                           dwarf::GIEL_EXTERNAL);
2154   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2155 
2156   // We could have a specification DIE that has our most of our knowledge,
2157   // look for that now.
2158   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
2159     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
2160     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
2161       Linkage = dwarf::GIEL_EXTERNAL;
2162   } else if (Die->findAttribute(dwarf::DW_AT_external))
2163     Linkage = dwarf::GIEL_EXTERNAL;
2164 
2165   switch (Die->getTag()) {
2166   case dwarf::DW_TAG_class_type:
2167   case dwarf::DW_TAG_structure_type:
2168   case dwarf::DW_TAG_union_type:
2169   case dwarf::DW_TAG_enumeration_type:
2170     return dwarf::PubIndexEntryDescriptor(
2171         dwarf::GIEK_TYPE,
2172         dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
2173             ? dwarf::GIEL_EXTERNAL
2174             : dwarf::GIEL_STATIC);
2175   case dwarf::DW_TAG_typedef:
2176   case dwarf::DW_TAG_base_type:
2177   case dwarf::DW_TAG_subrange_type:
2178     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2179   case dwarf::DW_TAG_namespace:
2180     return dwarf::GIEK_TYPE;
2181   case dwarf::DW_TAG_subprogram:
2182     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2183   case dwarf::DW_TAG_variable:
2184     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2185   case dwarf::DW_TAG_enumerator:
2186     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2187                                           dwarf::GIEL_STATIC);
2188   default:
2189     return dwarf::GIEK_NONE;
2190   }
2191 }
2192 
2193 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
2194 /// pubtypes sections.
2195 void DwarfDebug::emitDebugPubSections() {
2196   for (const auto &NU : CUMap) {
2197     DwarfCompileUnit *TheU = NU.second;
2198     if (!TheU->hasDwarfPubSections())
2199       continue;
2200 
2201     bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
2202                     DICompileUnit::DebugNameTableKind::GNU;
2203 
2204     Asm->OutStreamer->SwitchSection(
2205         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2206                  : Asm->getObjFileLowering().getDwarfPubNamesSection());
2207     emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
2208 
2209     Asm->OutStreamer->SwitchSection(
2210         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2211                  : Asm->getObjFileLowering().getDwarfPubTypesSection());
2212     emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
2213   }
2214 }
2215 
2216 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
2217   if (useSectionsAsReferences())
2218     Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
2219                          CU.getDebugSectionOffset());
2220   else
2221     Asm->emitDwarfSymbolReference(CU.getLabelBegin());
2222 }
2223 
2224 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
2225                                      DwarfCompileUnit *TheU,
2226                                      const StringMap<const DIE *> &Globals) {
2227   if (auto *Skeleton = TheU->getSkeleton())
2228     TheU = Skeleton;
2229 
2230   // Emit the header.
2231   Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
2232   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
2233   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
2234   Asm->emitLabelDifference(EndLabel, BeginLabel, 4);
2235 
2236   Asm->OutStreamer->emitLabel(BeginLabel);
2237 
2238   Asm->OutStreamer->AddComment("DWARF Version");
2239   Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
2240 
2241   Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
2242   emitSectionReference(*TheU);
2243 
2244   Asm->OutStreamer->AddComment("Compilation Unit Length");
2245   Asm->emitInt32(TheU->getLength());
2246 
2247   // Emit the pubnames for this compilation unit.
2248   for (const auto &GI : Globals) {
2249     const char *Name = GI.getKeyData();
2250     const DIE *Entity = GI.second;
2251 
2252     Asm->OutStreamer->AddComment("DIE offset");
2253     Asm->emitInt32(Entity->getOffset());
2254 
2255     if (GnuStyle) {
2256       dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2257       Asm->OutStreamer->AddComment(
2258           Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
2259           ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2260       Asm->emitInt8(Desc.toBits());
2261     }
2262 
2263     Asm->OutStreamer->AddComment("External Name");
2264     Asm->OutStreamer->emitBytes(StringRef(Name, GI.getKeyLength() + 1));
2265   }
2266 
2267   Asm->OutStreamer->AddComment("End Mark");
2268   Asm->emitInt32(0);
2269   Asm->OutStreamer->emitLabel(EndLabel);
2270 }
2271 
2272 /// Emit null-terminated strings into a debug str section.
2273 void DwarfDebug::emitDebugStr() {
2274   MCSection *StringOffsetsSection = nullptr;
2275   if (useSegmentedStringOffsetsTable()) {
2276     emitStringOffsetsTableHeader();
2277     StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
2278   }
2279   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2280   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
2281                      StringOffsetsSection, /* UseRelativeOffsets = */ true);
2282 }
2283 
2284 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2285                                    const DebugLocStream::Entry &Entry,
2286                                    const DwarfCompileUnit *CU) {
2287   auto &&Comments = DebugLocs.getComments(Entry);
2288   auto Comment = Comments.begin();
2289   auto End = Comments.end();
2290 
2291   // The expressions are inserted into a byte stream rather early (see
2292   // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2293   // need to reference a base_type DIE the offset of that DIE is not yet known.
2294   // To deal with this we instead insert a placeholder early and then extract
2295   // it here and replace it with the real reference.
2296   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2297   DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
2298                                     DebugLocs.getBytes(Entry).size()),
2299                           Asm->getDataLayout().isLittleEndian(), PtrSize);
2300   DWARFExpression Expr(Data, PtrSize);
2301 
2302   using Encoding = DWARFExpression::Operation::Encoding;
2303   uint64_t Offset = 0;
2304   for (auto &Op : Expr) {
2305     assert(Op.getCode() != dwarf::DW_OP_const_type &&
2306            "3 operand ops not yet supported");
2307     Streamer.EmitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
2308     Offset++;
2309     for (unsigned I = 0; I < 2; ++I) {
2310       if (Op.getDescription().Op[I] == Encoding::SizeNA)
2311         continue;
2312       if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
2313         uint64_t Offset =
2314             CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset();
2315         assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit");
2316         Streamer.emitULEB128(Offset, "", ULEB128PadSize);
2317         // Make sure comments stay aligned.
2318         for (unsigned J = 0; J < ULEB128PadSize; ++J)
2319           if (Comment != End)
2320             Comment++;
2321       } else {
2322         for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2323           Streamer.EmitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
2324       }
2325       Offset = Op.getOperandEndOffset(I);
2326     }
2327     assert(Offset == Op.getEndOffset());
2328   }
2329 }
2330 
2331 void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
2332                                    const DbgValueLoc &Value,
2333                                    DwarfExpression &DwarfExpr) {
2334   auto *DIExpr = Value.getExpression();
2335   DIExpressionCursor ExprCursor(DIExpr);
2336   DwarfExpr.addFragmentOffset(DIExpr);
2337   // Regular entry.
2338   if (Value.isInt()) {
2339     if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
2340                BT->getEncoding() == dwarf::DW_ATE_signed_char))
2341       DwarfExpr.addSignedConstant(Value.getInt());
2342     else
2343       DwarfExpr.addUnsignedConstant(Value.getInt());
2344   } else if (Value.isLocation()) {
2345     MachineLocation Location = Value.getLoc();
2346     if (Location.isIndirect())
2347       DwarfExpr.setMemoryLocationKind();
2348     DIExpressionCursor Cursor(DIExpr);
2349 
2350     if (DIExpr->isEntryValue()) {
2351       DwarfExpr.setEntryValueFlag();
2352       DwarfExpr.beginEntryValueExpression(Cursor);
2353     }
2354 
2355     const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2356     if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2357       return;
2358     return DwarfExpr.addExpression(std::move(Cursor));
2359   } else if (Value.isTargetIndexLocation()) {
2360     TargetIndexLocation Loc = Value.getTargetIndexLocation();
2361     // TODO TargetIndexLocation is a target-independent. Currently only the WebAssembly-specific
2362     // encoding is supported.
2363     DwarfExpr.addWasmLocation(Loc.Index, Loc.Offset);
2364   } else if (Value.isConstantFP()) {
2365     APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
2366     DwarfExpr.addUnsignedConstant(RawBytes);
2367   }
2368   DwarfExpr.addExpression(std::move(ExprCursor));
2369 }
2370 
2371 void DebugLocEntry::finalize(const AsmPrinter &AP,
2372                              DebugLocStream::ListBuilder &List,
2373                              const DIBasicType *BT,
2374                              DwarfCompileUnit &TheCU) {
2375   assert(!Values.empty() &&
2376          "location list entries without values are redundant");
2377   assert(Begin != End && "unexpected location list entry with empty range");
2378   DebugLocStream::EntryBuilder Entry(List, Begin, End);
2379   BufferByteStreamer Streamer = Entry.getStreamer();
2380   DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2381   const DbgValueLoc &Value = Values[0];
2382   if (Value.isFragment()) {
2383     // Emit all fragments that belong to the same variable and range.
2384     assert(llvm::all_of(Values, [](DbgValueLoc P) {
2385           return P.isFragment();
2386         }) && "all values are expected to be fragments");
2387     assert(std::is_sorted(Values.begin(), Values.end()) &&
2388            "fragments are expected to be sorted");
2389 
2390     for (auto Fragment : Values)
2391       DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2392 
2393   } else {
2394     assert(Values.size() == 1 && "only fragments may have >1 value");
2395     DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
2396   }
2397   DwarfExpr.finalize();
2398   if (DwarfExpr.TagOffset)
2399     List.setTagOffset(*DwarfExpr.TagOffset);
2400 }
2401 
2402 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
2403                                            const DwarfCompileUnit *CU) {
2404   // Emit the size.
2405   Asm->OutStreamer->AddComment("Loc expr size");
2406   if (getDwarfVersion() >= 5)
2407     Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
2408   else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2409     Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2410   else {
2411     // The entry is too big to fit into 16 bit, drop it as there is nothing we
2412     // can do.
2413     Asm->emitInt16(0);
2414     return;
2415   }
2416   // Emit the entry.
2417   APByteStreamer Streamer(*Asm);
2418   emitDebugLocEntry(Streamer, Entry, CU);
2419 }
2420 
2421 // Emit the header of a DWARF 5 range list table list table. Returns the symbol
2422 // that designates the end of the table for the caller to emit when the table is
2423 // complete.
2424 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
2425                                          const DwarfFile &Holder) {
2426   MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2427 
2428   Asm->OutStreamer->AddComment("Offset entry count");
2429   Asm->emitInt32(Holder.getRangeLists().size());
2430   Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
2431 
2432   for (const RangeSpanList &List : Holder.getRangeLists())
2433     Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(), 4);
2434 
2435   return TableEnd;
2436 }
2437 
2438 // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2439 // designates the end of the table for the caller to emit when the table is
2440 // complete.
2441 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
2442                                          const DwarfDebug &DD) {
2443   MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2444 
2445   const auto &DebugLocs = DD.getDebugLocs();
2446 
2447   Asm->OutStreamer->AddComment("Offset entry count");
2448   Asm->emitInt32(DebugLocs.getLists().size());
2449   Asm->OutStreamer->emitLabel(DebugLocs.getSym());
2450 
2451   for (const auto &List : DebugLocs.getLists())
2452     Asm->emitLabelDifference(List.Label, DebugLocs.getSym(), 4);
2453 
2454   return TableEnd;
2455 }
2456 
2457 template <typename Ranges, typename PayloadEmitter>
2458 static void emitRangeList(
2459     DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
2460     const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
2461     unsigned StartxLength, unsigned EndOfList,
2462     StringRef (*StringifyEnum)(unsigned),
2463     bool ShouldUseBaseAddress,
2464     PayloadEmitter EmitPayload) {
2465 
2466   auto Size = Asm->MAI->getCodePointerSize();
2467   bool UseDwarf5 = DD.getDwarfVersion() >= 5;
2468 
2469   // Emit our symbol so we can find the beginning of the range.
2470   Asm->OutStreamer->emitLabel(Sym);
2471 
2472   // Gather all the ranges that apply to the same section so they can share
2473   // a base address entry.
2474   MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
2475 
2476   for (const auto &Range : R)
2477     SectionRanges[&Range.Begin->getSection()].push_back(&Range);
2478 
2479   const MCSymbol *CUBase = CU.getBaseAddress();
2480   bool BaseIsSet = false;
2481   for (const auto &P : SectionRanges) {
2482     auto *Base = CUBase;
2483     if (!Base && ShouldUseBaseAddress) {
2484       const MCSymbol *Begin = P.second.front()->Begin;
2485       const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
2486       if (!UseDwarf5) {
2487         Base = NewBase;
2488         BaseIsSet = true;
2489         Asm->OutStreamer->emitIntValue(-1, Size);
2490         Asm->OutStreamer->AddComment("  base address");
2491         Asm->OutStreamer->emitSymbolValue(Base, Size);
2492       } else if (NewBase != Begin || P.second.size() > 1) {
2493         // Only use a base address if
2494         //  * the existing pool address doesn't match (NewBase != Begin)
2495         //  * or, there's more than one entry to share the base address
2496         Base = NewBase;
2497         BaseIsSet = true;
2498         Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
2499         Asm->emitInt8(BaseAddressx);
2500         Asm->OutStreamer->AddComment("  base address index");
2501         Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
2502       }
2503     } else if (BaseIsSet && !UseDwarf5) {
2504       BaseIsSet = false;
2505       assert(!Base);
2506       Asm->OutStreamer->emitIntValue(-1, Size);
2507       Asm->OutStreamer->emitIntValue(0, Size);
2508     }
2509 
2510     for (const auto *RS : P.second) {
2511       const MCSymbol *Begin = RS->Begin;
2512       const MCSymbol *End = RS->End;
2513       assert(Begin && "Range without a begin symbol?");
2514       assert(End && "Range without an end symbol?");
2515       if (Base) {
2516         if (UseDwarf5) {
2517           // Emit offset_pair when we have a base.
2518           Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
2519           Asm->emitInt8(OffsetPair);
2520           Asm->OutStreamer->AddComment("  starting offset");
2521           Asm->emitLabelDifferenceAsULEB128(Begin, Base);
2522           Asm->OutStreamer->AddComment("  ending offset");
2523           Asm->emitLabelDifferenceAsULEB128(End, Base);
2524         } else {
2525           Asm->emitLabelDifference(Begin, Base, Size);
2526           Asm->emitLabelDifference(End, Base, Size);
2527         }
2528       } else if (UseDwarf5) {
2529         Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
2530         Asm->emitInt8(StartxLength);
2531         Asm->OutStreamer->AddComment("  start index");
2532         Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
2533         Asm->OutStreamer->AddComment("  length");
2534         Asm->emitLabelDifferenceAsULEB128(End, Begin);
2535       } else {
2536         Asm->OutStreamer->emitSymbolValue(Begin, Size);
2537         Asm->OutStreamer->emitSymbolValue(End, Size);
2538       }
2539       EmitPayload(*RS);
2540     }
2541   }
2542 
2543   if (UseDwarf5) {
2544     Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
2545     Asm->emitInt8(EndOfList);
2546   } else {
2547     // Terminate the list with two 0 values.
2548     Asm->OutStreamer->emitIntValue(0, Size);
2549     Asm->OutStreamer->emitIntValue(0, Size);
2550   }
2551 }
2552 
2553 // Handles emission of both debug_loclist / debug_loclist.dwo
2554 static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
2555   emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2556                 *List.CU, dwarf::DW_LLE_base_addressx,
2557                 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2558                 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
2559                 /* ShouldUseBaseAddress */ true,
2560                 [&](const DebugLocStream::Entry &E) {
2561                   DD.emitDebugLocEntryLocation(E, List.CU);
2562                 });
2563 }
2564 
2565 void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
2566   if (DebugLocs.getLists().empty())
2567     return;
2568 
2569   Asm->OutStreamer->SwitchSection(Sec);
2570 
2571   MCSymbol *TableEnd = nullptr;
2572   if (getDwarfVersion() >= 5)
2573     TableEnd = emitLoclistsTableHeader(Asm, *this);
2574 
2575   for (const auto &List : DebugLocs.getLists())
2576     emitLocList(*this, Asm, List);
2577 
2578   if (TableEnd)
2579     Asm->OutStreamer->emitLabel(TableEnd);
2580 }
2581 
2582 // Emit locations into the .debug_loc/.debug_loclists section.
2583 void DwarfDebug::emitDebugLoc() {
2584   emitDebugLocImpl(
2585       getDwarfVersion() >= 5
2586           ? Asm->getObjFileLowering().getDwarfLoclistsSection()
2587           : Asm->getObjFileLowering().getDwarfLocSection());
2588 }
2589 
2590 // Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
2591 void DwarfDebug::emitDebugLocDWO() {
2592   if (getDwarfVersion() >= 5) {
2593     emitDebugLocImpl(
2594         Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
2595 
2596     return;
2597   }
2598 
2599   for (const auto &List : DebugLocs.getLists()) {
2600     Asm->OutStreamer->SwitchSection(
2601         Asm->getObjFileLowering().getDwarfLocDWOSection());
2602     Asm->OutStreamer->emitLabel(List.Label);
2603 
2604     for (const auto &Entry : DebugLocs.getEntries(List)) {
2605       // GDB only supports startx_length in pre-standard split-DWARF.
2606       // (in v5 standard loclists, it currently* /only/ supports base_address +
2607       // offset_pair, so the implementations can't really share much since they
2608       // need to use different representations)
2609       // * as of October 2018, at least
2610       //
2611       // In v5 (see emitLocList), this uses SectionLabels to reuse existing
2612       // addresses in the address pool to minimize object size/relocations.
2613       Asm->emitInt8(dwarf::DW_LLE_startx_length);
2614       unsigned idx = AddrPool.getIndex(Entry.Begin);
2615       Asm->emitULEB128(idx);
2616       // Also the pre-standard encoding is slightly different, emitting this as
2617       // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
2618       Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
2619       emitDebugLocEntryLocation(Entry, List.CU);
2620     }
2621     Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2622   }
2623 }
2624 
2625 struct ArangeSpan {
2626   const MCSymbol *Start, *End;
2627 };
2628 
2629 // Emit a debug aranges section, containing a CU lookup for any
2630 // address we can tie back to a CU.
2631 void DwarfDebug::emitDebugARanges() {
2632   // Provides a unique id per text section.
2633   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2634 
2635   // Filter labels by section.
2636   for (const SymbolCU &SCU : ArangeLabels) {
2637     if (SCU.Sym->isInSection()) {
2638       // Make a note of this symbol and it's section.
2639       MCSection *Section = &SCU.Sym->getSection();
2640       if (!Section->getKind().isMetadata())
2641         SectionMap[Section].push_back(SCU);
2642     } else {
2643       // Some symbols (e.g. common/bss on mach-o) can have no section but still
2644       // appear in the output. This sucks as we rely on sections to build
2645       // arange spans. We can do it without, but it's icky.
2646       SectionMap[nullptr].push_back(SCU);
2647     }
2648   }
2649 
2650   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2651 
2652   for (auto &I : SectionMap) {
2653     MCSection *Section = I.first;
2654     SmallVector<SymbolCU, 8> &List = I.second;
2655     if (List.size() < 1)
2656       continue;
2657 
2658     // If we have no section (e.g. common), just write out
2659     // individual spans for each symbol.
2660     if (!Section) {
2661       for (const SymbolCU &Cur : List) {
2662         ArangeSpan Span;
2663         Span.Start = Cur.Sym;
2664         Span.End = nullptr;
2665         assert(Cur.CU);
2666         Spans[Cur.CU].push_back(Span);
2667       }
2668       continue;
2669     }
2670 
2671     // Sort the symbols by offset within the section.
2672     llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
2673       unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
2674       unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
2675 
2676       // Symbols with no order assigned should be placed at the end.
2677       // (e.g. section end labels)
2678       if (IA == 0)
2679         return false;
2680       if (IB == 0)
2681         return true;
2682       return IA < IB;
2683     });
2684 
2685     // Insert a final terminator.
2686     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2687 
2688     // Build spans between each label.
2689     const MCSymbol *StartSym = List[0].Sym;
2690     for (size_t n = 1, e = List.size(); n < e; n++) {
2691       const SymbolCU &Prev = List[n - 1];
2692       const SymbolCU &Cur = List[n];
2693 
2694       // Try and build the longest span we can within the same CU.
2695       if (Cur.CU != Prev.CU) {
2696         ArangeSpan Span;
2697         Span.Start = StartSym;
2698         Span.End = Cur.Sym;
2699         assert(Prev.CU);
2700         Spans[Prev.CU].push_back(Span);
2701         StartSym = Cur.Sym;
2702       }
2703     }
2704   }
2705 
2706   // Start the dwarf aranges section.
2707   Asm->OutStreamer->SwitchSection(
2708       Asm->getObjFileLowering().getDwarfARangesSection());
2709 
2710   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2711 
2712   // Build a list of CUs used.
2713   std::vector<DwarfCompileUnit *> CUs;
2714   for (const auto &it : Spans) {
2715     DwarfCompileUnit *CU = it.first;
2716     CUs.push_back(CU);
2717   }
2718 
2719   // Sort the CU list (again, to ensure consistent output order).
2720   llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2721     return A->getUniqueID() < B->getUniqueID();
2722   });
2723 
2724   // Emit an arange table for each CU we used.
2725   for (DwarfCompileUnit *CU : CUs) {
2726     std::vector<ArangeSpan> &List = Spans[CU];
2727 
2728     // Describe the skeleton CU's offset and length, not the dwo file's.
2729     if (auto *Skel = CU->getSkeleton())
2730       CU = Skel;
2731 
2732     // Emit size of content not including length itself.
2733     unsigned ContentSize =
2734         sizeof(int16_t) + // DWARF ARange version number
2735         sizeof(int32_t) + // Offset of CU in the .debug_info section
2736         sizeof(int8_t) +  // Pointer Size (in bytes)
2737         sizeof(int8_t);   // Segment Size (in bytes)
2738 
2739     unsigned TupleSize = PtrSize * 2;
2740 
2741     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2742     unsigned Padding =
2743         offsetToAlignment(sizeof(int32_t) + ContentSize, Align(TupleSize));
2744 
2745     ContentSize += Padding;
2746     ContentSize += (List.size() + 1) * TupleSize;
2747 
2748     // For each compile unit, write the list of spans it covers.
2749     Asm->OutStreamer->AddComment("Length of ARange Set");
2750     Asm->emitInt32(ContentSize);
2751     Asm->OutStreamer->AddComment("DWARF Arange version number");
2752     Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
2753     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
2754     emitSectionReference(*CU);
2755     Asm->OutStreamer->AddComment("Address Size (in bytes)");
2756     Asm->emitInt8(PtrSize);
2757     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
2758     Asm->emitInt8(0);
2759 
2760     Asm->OutStreamer->emitFill(Padding, 0xff);
2761 
2762     for (const ArangeSpan &Span : List) {
2763       Asm->emitLabelReference(Span.Start, PtrSize);
2764 
2765       // Calculate the size as being from the span start to it's end.
2766       if (Span.End) {
2767         Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
2768       } else {
2769         // For symbols without an end marker (e.g. common), we
2770         // write a single arange entry containing just that one symbol.
2771         uint64_t Size = SymSize[Span.Start];
2772         if (Size == 0)
2773           Size = 1;
2774 
2775         Asm->OutStreamer->emitIntValue(Size, PtrSize);
2776       }
2777     }
2778 
2779     Asm->OutStreamer->AddComment("ARange terminator");
2780     Asm->OutStreamer->emitIntValue(0, PtrSize);
2781     Asm->OutStreamer->emitIntValue(0, PtrSize);
2782   }
2783 }
2784 
2785 /// Emit a single range list. We handle both DWARF v5 and earlier.
2786 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
2787                           const RangeSpanList &List) {
2788   emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
2789                 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
2790                 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
2791                 llvm::dwarf::RangeListEncodingString,
2792                 List.CU->getCUNode()->getRangesBaseAddress() ||
2793                     DD.getDwarfVersion() >= 5,
2794                 [](auto) {});
2795 }
2796 
2797 void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
2798   if (Holder.getRangeLists().empty())
2799     return;
2800 
2801   assert(useRangesSection());
2802   assert(!CUMap.empty());
2803   assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2804     return !Pair.second->getCUNode()->isDebugDirectivesOnly();
2805   }));
2806 
2807   Asm->OutStreamer->SwitchSection(Section);
2808 
2809   MCSymbol *TableEnd = nullptr;
2810   if (getDwarfVersion() >= 5)
2811     TableEnd = emitRnglistsTableHeader(Asm, Holder);
2812 
2813   for (const RangeSpanList &List : Holder.getRangeLists())
2814     emitRangeList(*this, Asm, List);
2815 
2816   if (TableEnd)
2817     Asm->OutStreamer->emitLabel(TableEnd);
2818 }
2819 
2820 /// Emit address ranges into the .debug_ranges section or into the DWARF v5
2821 /// .debug_rnglists section.
2822 void DwarfDebug::emitDebugRanges() {
2823   const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2824 
2825   emitDebugRangesImpl(Holder,
2826                       getDwarfVersion() >= 5
2827                           ? Asm->getObjFileLowering().getDwarfRnglistsSection()
2828                           : Asm->getObjFileLowering().getDwarfRangesSection());
2829 }
2830 
2831 void DwarfDebug::emitDebugRangesDWO() {
2832   emitDebugRangesImpl(InfoHolder,
2833                       Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
2834 }
2835 
2836 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
2837   for (auto *MN : Nodes) {
2838     if (auto *M = dyn_cast<DIMacro>(MN))
2839       emitMacro(*M);
2840     else if (auto *F = dyn_cast<DIMacroFile>(MN))
2841       emitMacroFile(*F, U);
2842     else
2843       llvm_unreachable("Unexpected DI type!");
2844   }
2845 }
2846 
2847 void DwarfDebug::emitMacro(DIMacro &M) {
2848   Asm->emitULEB128(M.getMacinfoType());
2849   Asm->emitULEB128(M.getLine());
2850   StringRef Name = M.getName();
2851   StringRef Value = M.getValue();
2852   Asm->OutStreamer->emitBytes(Name);
2853   if (!Value.empty()) {
2854     // There should be one space between macro name and macro value.
2855     Asm->emitInt8(' ');
2856     Asm->OutStreamer->emitBytes(Value);
2857   }
2858   Asm->emitInt8('\0');
2859 }
2860 
2861 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
2862   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
2863   Asm->emitULEB128(dwarf::DW_MACINFO_start_file);
2864   Asm->emitULEB128(F.getLine());
2865   Asm->emitULEB128(U.getOrCreateSourceID(F.getFile()));
2866   handleMacroNodes(F.getElements(), U);
2867   Asm->emitULEB128(dwarf::DW_MACINFO_end_file);
2868 }
2869 
2870 void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
2871   for (const auto &P : CUMap) {
2872     auto &TheCU = *P.second;
2873     auto *SkCU = TheCU.getSkeleton();
2874     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2875     auto *CUNode = cast<DICompileUnit>(P.first);
2876     DIMacroNodeArray Macros = CUNode->getMacros();
2877     if (Macros.empty())
2878       continue;
2879     Asm->OutStreamer->SwitchSection(Section);
2880     Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
2881     handleMacroNodes(Macros, U);
2882     Asm->OutStreamer->AddComment("End Of Macro List Mark");
2883     Asm->emitInt8(0);
2884   }
2885 }
2886 
2887 /// Emit macros into a debug macinfo section.
2888 void DwarfDebug::emitDebugMacinfo() {
2889   emitDebugMacinfoImpl(Asm->getObjFileLowering().getDwarfMacinfoSection());
2890 }
2891 
2892 void DwarfDebug::emitDebugMacinfoDWO() {
2893   emitDebugMacinfoImpl(Asm->getObjFileLowering().getDwarfMacinfoDWOSection());
2894 }
2895 
2896 // DWARF5 Experimental Separate Dwarf emitters.
2897 
2898 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2899                                   std::unique_ptr<DwarfCompileUnit> NewU) {
2900 
2901   if (!CompilationDir.empty())
2902     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2903   addGnuPubAttributes(*NewU, Die);
2904 
2905   SkeletonHolder.addUnit(std::move(NewU));
2906 }
2907 
2908 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2909 
2910   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
2911       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
2912       UnitKind::Skeleton);
2913   DwarfCompileUnit &NewCU = *OwnedUnit;
2914   NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2915 
2916   NewCU.initStmtList();
2917 
2918   if (useSegmentedStringOffsetsTable())
2919     NewCU.addStringOffsetsStart();
2920 
2921   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2922 
2923   return NewCU;
2924 }
2925 
2926 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2927 // compile units that would normally be in debug_info.
2928 void DwarfDebug::emitDebugInfoDWO() {
2929   assert(useSplitDwarf() && "No split dwarf debug info?");
2930   // Don't emit relocations into the dwo file.
2931   InfoHolder.emitUnits(/* UseOffsets */ true);
2932 }
2933 
2934 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2935 // abbreviations for the .debug_info.dwo section.
2936 void DwarfDebug::emitDebugAbbrevDWO() {
2937   assert(useSplitDwarf() && "No split dwarf?");
2938   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2939 }
2940 
2941 void DwarfDebug::emitDebugLineDWO() {
2942   assert(useSplitDwarf() && "No split dwarf?");
2943   SplitTypeUnitFileTable.Emit(
2944       *Asm->OutStreamer, MCDwarfLineTableParams(),
2945       Asm->getObjFileLowering().getDwarfLineDWOSection());
2946 }
2947 
2948 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2949   assert(useSplitDwarf() && "No split dwarf?");
2950   InfoHolder.getStringPool().emitStringOffsetsTableHeader(
2951       *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
2952       InfoHolder.getStringOffsetsStartSym());
2953 }
2954 
2955 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2956 // string section and is identical in format to traditional .debug_str
2957 // sections.
2958 void DwarfDebug::emitDebugStrDWO() {
2959   if (useSegmentedStringOffsetsTable())
2960     emitStringOffsetsTableHeaderDWO();
2961   assert(useSplitDwarf() && "No split dwarf?");
2962   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2963   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2964                          OffSec, /* UseRelativeOffsets = */ false);
2965 }
2966 
2967 // Emit address pool.
2968 void DwarfDebug::emitDebugAddr() {
2969   AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
2970 }
2971 
2972 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2973   if (!useSplitDwarf())
2974     return nullptr;
2975   const DICompileUnit *DIUnit = CU.getCUNode();
2976   SplitTypeUnitFileTable.maybeSetRootFile(
2977       DIUnit->getDirectory(), DIUnit->getFilename(),
2978       CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
2979   return &SplitTypeUnitFileTable;
2980 }
2981 
2982 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2983   MD5 Hash;
2984   Hash.update(Identifier);
2985   // ... take the least significant 8 bytes and return those. Our MD5
2986   // implementation always returns its results in little endian, so we actually
2987   // need the "high" word.
2988   MD5::MD5Result Result;
2989   Hash.final(Result);
2990   return Result.high();
2991 }
2992 
2993 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2994                                       StringRef Identifier, DIE &RefDie,
2995                                       const DICompositeType *CTy) {
2996   // Fast path if we're building some type units and one has already used the
2997   // address pool we know we're going to throw away all this work anyway, so
2998   // don't bother building dependent types.
2999   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
3000     return;
3001 
3002   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
3003   if (!Ins.second) {
3004     CU.addDIETypeSignature(RefDie, Ins.first->second);
3005     return;
3006   }
3007 
3008   bool TopLevelType = TypeUnitsUnderConstruction.empty();
3009   AddrPool.resetUsedFlag();
3010 
3011   auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
3012                                                     getDwoLineTable(CU));
3013   DwarfTypeUnit &NewTU = *OwnedUnit;
3014   DIE &UnitDie = NewTU.getUnitDie();
3015   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
3016 
3017   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3018                 CU.getLanguage());
3019 
3020   uint64_t Signature = makeTypeSignature(Identifier);
3021   NewTU.setTypeSignature(Signature);
3022   Ins.first->second = Signature;
3023 
3024   if (useSplitDwarf()) {
3025     MCSection *Section =
3026         getDwarfVersion() <= 4
3027             ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
3028             : Asm->getObjFileLowering().getDwarfInfoDWOSection();
3029     NewTU.setSection(Section);
3030   } else {
3031     MCSection *Section =
3032         getDwarfVersion() <= 4
3033             ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
3034             : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
3035     NewTU.setSection(Section);
3036     // Non-split type units reuse the compile unit's line table.
3037     CU.applyStmtList(UnitDie);
3038   }
3039 
3040   // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
3041   // units.
3042   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
3043     NewTU.addStringOffsetsStart();
3044 
3045   NewTU.setType(NewTU.createTypeDIE(CTy));
3046 
3047   if (TopLevelType) {
3048     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
3049     TypeUnitsUnderConstruction.clear();
3050 
3051     // Types referencing entries in the address table cannot be placed in type
3052     // units.
3053     if (AddrPool.hasBeenUsed()) {
3054 
3055       // Remove all the types built while building this type.
3056       // This is pessimistic as some of these types might not be dependent on
3057       // the type that used an address.
3058       for (const auto &TU : TypeUnitsToAdd)
3059         TypeSignatures.erase(TU.second);
3060 
3061       // Construct this type in the CU directly.
3062       // This is inefficient because all the dependent types will be rebuilt
3063       // from scratch, including building them in type units, discovering that
3064       // they depend on addresses, throwing them out and rebuilding them.
3065       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
3066       return;
3067     }
3068 
3069     // If the type wasn't dependent on fission addresses, finish adding the type
3070     // and all its dependent types.
3071     for (auto &TU : TypeUnitsToAdd) {
3072       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
3073       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
3074     }
3075   }
3076   CU.addDIETypeSignature(RefDie, Signature);
3077 }
3078 
3079 DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD)
3080     : DD(DD),
3081       TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)) {
3082   DD->TypeUnitsUnderConstruction.clear();
3083   assert(TypeUnitsUnderConstruction.empty() || !DD->AddrPool.hasBeenUsed());
3084 }
3085 
3086 DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() {
3087   DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction);
3088   DD->AddrPool.resetUsedFlag();
3089 }
3090 
3091 DwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() {
3092   return NonTypeUnitContext(this);
3093 }
3094 
3095 // Add the Name along with its companion DIE to the appropriate accelerator
3096 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3097 // AccelTableKind::Apple, we use the table we got as an argument). If
3098 // accelerator tables are disabled, this function does nothing.
3099 template <typename DataT>
3100 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
3101                                   AccelTable<DataT> &AppleAccel, StringRef Name,
3102                                   const DIE &Die) {
3103   if (getAccelTableKind() == AccelTableKind::None)
3104     return;
3105 
3106   if (getAccelTableKind() != AccelTableKind::Apple &&
3107       CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
3108     return;
3109 
3110   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3111   DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
3112 
3113   switch (getAccelTableKind()) {
3114   case AccelTableKind::Apple:
3115     AppleAccel.addName(Ref, Die);
3116     break;
3117   case AccelTableKind::Dwarf:
3118     AccelDebugNames.addName(Ref, Die);
3119     break;
3120   case AccelTableKind::Default:
3121     llvm_unreachable("Default should have already been resolved.");
3122   case AccelTableKind::None:
3123     llvm_unreachable("None handled above");
3124   }
3125 }
3126 
3127 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
3128                               const DIE &Die) {
3129   addAccelNameImpl(CU, AccelNames, Name, Die);
3130 }
3131 
3132 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
3133                               const DIE &Die) {
3134   // ObjC names go only into the Apple accelerator tables.
3135   if (getAccelTableKind() == AccelTableKind::Apple)
3136     addAccelNameImpl(CU, AccelObjC, Name, Die);
3137 }
3138 
3139 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
3140                                    const DIE &Die) {
3141   addAccelNameImpl(CU, AccelNamespace, Name, Die);
3142 }
3143 
3144 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
3145                               const DIE &Die, char Flags) {
3146   addAccelNameImpl(CU, AccelTypes, Name, Die);
3147 }
3148 
3149 uint16_t DwarfDebug::getDwarfVersion() const {
3150   return Asm->OutStreamer->getContext().getDwarfVersion();
3151 }
3152 
3153 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
3154   return SectionLabels.find(S)->second;
3155 }
3156 void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
3157   SectionLabels.insert(std::make_pair(&S->getSection(), S));
3158 }
3159