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