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