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