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