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