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