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