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