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