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             break;
599           }
600         }
601       }
602     }
603   };
604 
605   auto finishCallSiteParam = [&](DbgValueLoc DbgLocVal, unsigned Reg) {
606     unsigned FwdReg = Reg;
607     if (ShouldTryEmitEntryVals) {
608       auto EntryValReg = RegsForEntryValues.find(Reg);
609       if (EntryValReg != RegsForEntryValues.end())
610         FwdReg = EntryValReg->second;
611     }
612 
613     DbgCallSiteParam CSParm(FwdReg, DbgLocVal);
614     Params.push_back(CSParm);
615     ++NumCSParams;
616   };
617 
618   // Search for a loading value in forwarding registers.
619   for (; I != MBB->rend(); ++I) {
620     // If the next instruction is a call we can not interpret parameter's
621     // forwarding registers or we finished the interpretation of all parameters.
622     if (I->isCall())
623       return;
624 
625     if (ForwardedRegWorklist.empty())
626       return;
627 
628     SmallVector<unsigned, 4> ExplicitFwdRegDefs;
629     SmallVector<unsigned, 4> ImplicitFwdRegDefs;
630     getForwardingRegsDefinedByMI(*I, ExplicitFwdRegDefs, ImplicitFwdRegDefs);
631     if (ExplicitFwdRegDefs.empty() && ImplicitFwdRegDefs.empty())
632       continue;
633 
634     // If the MI clobbers more then one forwarding register we must remove
635     // all of them from the working list.
636     for (auto Reg : concat<unsigned>(ExplicitFwdRegDefs, ImplicitFwdRegDefs))
637       ForwardedRegWorklist.erase(Reg);
638 
639     // The describeLoadedValue() hook currently does not have any information
640     // about which register it should describe in case of multiple defines, so
641     // for now we only handle instructions where a forwarded register is (at
642     // least partially) defined by the instruction's single explicit define.
643     if (I->getNumExplicitDefs() != 1 || ExplicitFwdRegDefs.empty())
644       continue;
645     unsigned ParamFwdReg = ExplicitFwdRegDefs[0];
646 
647     if (auto ParamValue = TII->describeLoadedValue(*I)) {
648       if (ParamValue->first.isImm()) {
649         int64_t Val = ParamValue->first.getImm();
650         DbgValueLoc DbgLocVal(ParamValue->second, Val);
651         finishCallSiteParam(DbgLocVal, ParamFwdReg);
652       } else if (ParamValue->first.isReg()) {
653         Register RegLoc = ParamValue->first.getReg();
654        // TODO: For now, there is no use of describing the value loaded into the
655        //       register that is also the source registers (e.g. $r0 = add $r0, x).
656        if (ParamFwdReg == RegLoc)
657          continue;
658 
659         unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
660         Register FP = TRI->getFrameRegister(*MF);
661         bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
662         if (TRI->isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP) {
663           DbgValueLoc DbgLocVal(ParamValue->second,
664                                 MachineLocation(RegLoc,
665                                                 /*IsIndirect=*/IsSPorFP));
666           finishCallSiteParam(DbgLocVal, ParamFwdReg);
667         // TODO: Add support for entry value plus an expression.
668         } else if (ShouldTryEmitEntryVals &&
669                    ParamValue->second->getNumElements() == 0) {
670           ForwardedRegWorklist.insert(RegLoc);
671           RegsForEntryValues[RegLoc] = ParamFwdReg;
672         }
673       }
674     }
675   }
676 
677   // Emit the call site parameter's value as an entry value.
678   if (ShouldTryEmitEntryVals) {
679     // Create an expression where the register's entry value is used.
680     DIExpression *EntryExpr = DIExpression::get(
681         MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
682     for (auto RegEntry : ForwardedRegWorklist) {
683       unsigned FwdReg = RegEntry;
684       auto EntryValReg = RegsForEntryValues.find(RegEntry);
685         if (EntryValReg != RegsForEntryValues.end())
686           FwdReg = EntryValReg->second;
687 
688       DbgValueLoc DbgLocVal(EntryExpr, MachineLocation(RegEntry));
689       DbgCallSiteParam CSParm(FwdReg, DbgLocVal);
690       Params.push_back(CSParm);
691       ++NumCSParams;
692     }
693   }
694 }
695 
696 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
697                                             DwarfCompileUnit &CU, DIE &ScopeDIE,
698                                             const MachineFunction &MF) {
699   // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
700   // the subprogram is required to have one.
701   if (!SP.areAllCallsDescribed() || !SP.isDefinition())
702     return;
703 
704   // Use DW_AT_call_all_calls to express that call site entries are present
705   // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
706   // because one of its requirements is not met: call site entries for
707   // optimized-out calls are elided.
708   CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
709 
710   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
711   assert(TII && "TargetInstrInfo not found: cannot label tail calls");
712   bool ApplyGNUExtensions = getDwarfVersion() == 4 && tuneForGDB();
713 
714   // Emit call site entries for each call or tail call in the function.
715   for (const MachineBasicBlock &MBB : MF) {
716     for (const MachineInstr &MI : MBB.instrs()) {
717       // Bundles with call in them will pass the isCall() test below but do not
718       // have callee operand information so skip them here. Iterator will
719       // eventually reach the call MI.
720       if (MI.isBundle())
721         continue;
722 
723       // Skip instructions which aren't calls. Both calls and tail-calling jump
724       // instructions (e.g TAILJMPd64) are classified correctly here.
725       if (!MI.isCall())
726         continue;
727 
728       // TODO: Add support for targets with delay slots (see: beginInstruction).
729       if (MI.hasDelaySlot())
730         return;
731 
732       // If this is a direct call, find the callee's subprogram.
733       // In the case of an indirect call find the register that holds
734       // the callee.
735       const MachineOperand &CalleeOp = MI.getOperand(0);
736       if (!CalleeOp.isGlobal() && !CalleeOp.isReg())
737         continue;
738 
739       unsigned CallReg = 0;
740       const DISubprogram *CalleeSP = nullptr;
741       const Function *CalleeDecl = nullptr;
742       if (CalleeOp.isReg()) {
743         CallReg = CalleeOp.getReg();
744         if (!CallReg)
745           continue;
746       } else {
747         CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
748         if (!CalleeDecl || !CalleeDecl->getSubprogram())
749           continue;
750         CalleeSP = CalleeDecl->getSubprogram();
751       }
752 
753       // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
754 
755       bool IsTail = TII->isTailCall(MI);
756 
757       // If MI is in a bundle, the label was created after the bundle since
758       // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
759       // to search for that label below.
760       const MachineInstr *TopLevelCallMI =
761           MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
762 
763       // For tail calls, for non-gdb tuning, no return PC information is needed.
764       // For regular calls (and tail calls in GDB tuning), the return PC
765       // is needed to disambiguate paths in the call graph which could lead to
766       // some target function.
767       const MCExpr *PCOffset =
768           (IsTail && !tuneForGDB())
769               ? nullptr
770               : getFunctionLocalOffsetAfterInsn(TopLevelCallMI);
771 
772       // Return address of a call-like instruction for a normal call or a
773       // jump-like instruction for a tail call. This is needed for
774       // GDB + DWARF 4 tuning.
775       const MCSymbol *PCAddr =
776           ApplyGNUExtensions
777               ? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
778               : nullptr;
779 
780       assert((IsTail || PCOffset || PCAddr) &&
781              "Call without return PC information");
782 
783       LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
784                         << (CalleeDecl ? CalleeDecl->getName()
785                                        : StringRef(MF.getSubtarget()
786                                                        .getRegisterInfo()
787                                                        ->getName(CallReg)))
788                         << (IsTail ? " [IsTail]" : "") << "\n");
789 
790       DIE &CallSiteDIE =
791             CU.constructCallSiteEntryDIE(ScopeDIE, CalleeSP, IsTail, PCAddr,
792                                          PCOffset, CallReg);
793 
794       // GDB and LLDB support call site parameter debug info.
795       if (Asm->TM.Options.EnableDebugEntryValues &&
796           (tuneForGDB() || tuneForLLDB())) {
797         ParamSet Params;
798         // Try to interpret values of call site parameters.
799         collectCallSiteParameters(&MI, Params);
800         CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
801       }
802     }
803   }
804 }
805 
806 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
807   if (!U.hasDwarfPubSections())
808     return;
809 
810   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
811 }
812 
813 void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
814                                       DwarfCompileUnit &NewCU) {
815   DIE &Die = NewCU.getUnitDie();
816   StringRef FN = DIUnit->getFilename();
817 
818   StringRef Producer = DIUnit->getProducer();
819   StringRef Flags = DIUnit->getFlags();
820   if (!Flags.empty() && !useAppleExtensionAttributes()) {
821     std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
822     NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
823   } else
824     NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
825 
826   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
827                 DIUnit->getSourceLanguage());
828   NewCU.addString(Die, dwarf::DW_AT_name, FN);
829 
830   // Add DW_str_offsets_base to the unit DIE, except for split units.
831   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
832     NewCU.addStringOffsetsStart();
833 
834   if (!useSplitDwarf()) {
835     NewCU.initStmtList();
836 
837     // If we're using split dwarf the compilation dir is going to be in the
838     // skeleton CU and so we don't need to duplicate it here.
839     if (!CompilationDir.empty())
840       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
841 
842     addGnuPubAttributes(NewCU, Die);
843   }
844 
845   if (useAppleExtensionAttributes()) {
846     if (DIUnit->isOptimized())
847       NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
848 
849     StringRef Flags = DIUnit->getFlags();
850     if (!Flags.empty())
851       NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
852 
853     if (unsigned RVer = DIUnit->getRuntimeVersion())
854       NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
855                     dwarf::DW_FORM_data1, RVer);
856   }
857 
858   if (DIUnit->getDWOId()) {
859     // This CU is either a clang module DWO or a skeleton CU.
860     NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
861                   DIUnit->getDWOId());
862     if (!DIUnit->getSplitDebugFilename().empty())
863       // This is a prefabricated skeleton CU.
864       NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
865                       DIUnit->getSplitDebugFilename());
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 
1000   for (DICompileUnit *CUNode : M->debug_compile_units()) {
1001     // FIXME: Move local imported entities into a list attached to the
1002     // subprogram, then this search won't be needed and a
1003     // getImportedEntities().empty() test should go below with the rest.
1004     bool HasNonLocalImportedEntities = llvm::any_of(
1005         CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
1006           return !isa<DILocalScope>(IE->getScope());
1007         });
1008 
1009     if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
1010         CUNode->getRetainedTypes().empty() &&
1011         CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1012       continue;
1013 
1014     DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1015 
1016     // Global Variables.
1017     for (auto *GVE : CUNode->getGlobalVariables()) {
1018       // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1019       // already know about the variable and it isn't adding a constant
1020       // expression.
1021       auto &GVMapEntry = GVMap[GVE->getVariable()];
1022       auto *Expr = GVE->getExpression();
1023       if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1024         GVMapEntry.push_back({nullptr, Expr});
1025     }
1026     DenseSet<DIGlobalVariable *> Processed;
1027     for (auto *GVE : CUNode->getGlobalVariables()) {
1028       DIGlobalVariable *GV = GVE->getVariable();
1029       if (Processed.insert(GV).second)
1030         CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1031     }
1032 
1033     for (auto *Ty : CUNode->getEnumTypes()) {
1034       // The enum types array by design contains pointers to
1035       // MDNodes rather than DIRefs. Unique them here.
1036       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1037     }
1038     for (auto *Ty : CUNode->getRetainedTypes()) {
1039       // The retained types array by design contains pointers to
1040       // MDNodes rather than DIRefs. Unique them here.
1041       if (DIType *RT = dyn_cast<DIType>(Ty))
1042           // There is no point in force-emitting a forward declaration.
1043           CU.getOrCreateTypeDIE(RT);
1044     }
1045     // Emit imported_modules last so that the relevant context is already
1046     // available.
1047     for (auto *IE : CUNode->getImportedEntities())
1048       constructAndAddImportedEntityDIE(CU, IE);
1049   }
1050 }
1051 
1052 void DwarfDebug::finishEntityDefinitions() {
1053   for (const auto &Entity : ConcreteEntities) {
1054     DIE *Die = Entity->getDIE();
1055     assert(Die);
1056     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1057     // in the ConcreteEntities list, rather than looking it up again here.
1058     // DIE::getUnit isn't simple - it walks parent pointers, etc.
1059     DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
1060     assert(Unit);
1061     Unit->finishEntityDefinition(Entity.get());
1062   }
1063 }
1064 
1065 void DwarfDebug::finishSubprogramDefinitions() {
1066   for (const DISubprogram *SP : ProcessedSPNodes) {
1067     assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1068     forBothCUs(
1069         getOrCreateDwarfCompileUnit(SP->getUnit()),
1070         [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1071   }
1072 }
1073 
1074 void DwarfDebug::finalizeModuleInfo() {
1075   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1076 
1077   finishSubprogramDefinitions();
1078 
1079   finishEntityDefinitions();
1080 
1081   // Include the DWO file name in the hash if there's more than one CU.
1082   // This handles ThinLTO's situation where imported CUs may very easily be
1083   // duplicate with the same CU partially imported into another ThinLTO unit.
1084   StringRef DWOName;
1085   if (CUMap.size() > 1)
1086     DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
1087 
1088   // Handle anything that needs to be done on a per-unit basis after
1089   // all other generation.
1090   for (const auto &P : CUMap) {
1091     auto &TheCU = *P.second;
1092     if (TheCU.getCUNode()->isDebugDirectivesOnly())
1093       continue;
1094     // Emit DW_AT_containing_type attribute to connect types with their
1095     // vtable holding type.
1096     TheCU.constructContainingTypeDIEs();
1097 
1098     // Add CU specific attributes if we need to add any.
1099     // If we're splitting the dwarf out now that we've got the entire
1100     // CU then add the dwo id to it.
1101     auto *SkCU = TheCU.getSkeleton();
1102     if (useSplitDwarf() && !TheCU.getUnitDie().children().empty()) {
1103       finishUnitAttributes(TheCU.getCUNode(), TheCU);
1104       TheCU.addString(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
1105                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1106       SkCU->addString(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
1107                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1108       // Emit a unique identifier for this CU.
1109       uint64_t ID =
1110           DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
1111       if (getDwarfVersion() >= 5) {
1112         TheCU.setDWOId(ID);
1113         SkCU->setDWOId(ID);
1114       } else {
1115         TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1116                       dwarf::DW_FORM_data8, ID);
1117         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1118                       dwarf::DW_FORM_data8, ID);
1119       }
1120 
1121       if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1122         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
1123         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1124                               Sym, Sym);
1125       }
1126     } else if (SkCU) {
1127       finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1128     }
1129 
1130     // If we have code split among multiple sections or non-contiguous
1131     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1132     // remain in the .o file, otherwise add a DW_AT_low_pc.
1133     // FIXME: We should use ranges allow reordering of code ala
1134     // .subsections_via_symbols in mach-o. This would mean turning on
1135     // ranges for all subprogram DIEs for mach-o.
1136     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1137 
1138     if (unsigned NumRanges = TheCU.getRanges().size()) {
1139       if (NumRanges > 1 && useRangesSection())
1140         // A DW_AT_low_pc attribute may also be specified in combination with
1141         // DW_AT_ranges to specify the default base address for use in
1142         // location lists (see Section 2.6.2) and range lists (see Section
1143         // 2.17.3).
1144         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
1145       else
1146         U.setBaseAddress(TheCU.getRanges().front().Begin);
1147       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1148     }
1149 
1150     // We don't keep track of which addresses are used in which CU so this
1151     // is a bit pessimistic under LTO.
1152     if (!AddrPool.isEmpty() &&
1153         (getDwarfVersion() >= 5 ||
1154          (SkCU && !TheCU.getUnitDie().children().empty())))
1155       U.addAddrTableBase();
1156 
1157     if (getDwarfVersion() >= 5) {
1158       if (U.hasRangeLists())
1159         U.addRnglistsBase();
1160 
1161       if (!DebugLocs.getLists().empty()) {
1162         DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1163         if (!useSplitDwarf())
1164           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
1165                             DebugLocs.getSym(),
1166                             TLOF.getDwarfLoclistsSection()->getBeginSymbol());
1167       }
1168     }
1169 
1170     auto *CUNode = cast<DICompileUnit>(P.first);
1171     // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
1172     if (CUNode->getMacros() && !useSplitDwarf())
1173       U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
1174                         U.getMacroLabelBegin(),
1175                         TLOF.getDwarfMacinfoSection()->getBeginSymbol());
1176   }
1177 
1178   // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1179   for (auto *CUNode : MMI->getModule()->debug_compile_units())
1180     if (CUNode->getDWOId())
1181       getOrCreateDwarfCompileUnit(CUNode);
1182 
1183   // Compute DIE offsets and sizes.
1184   InfoHolder.computeSizeAndOffsets();
1185   if (useSplitDwarf())
1186     SkeletonHolder.computeSizeAndOffsets();
1187 }
1188 
1189 // Emit all Dwarf sections that should come after the content.
1190 void DwarfDebug::endModule() {
1191   assert(CurFn == nullptr);
1192   assert(CurMI == nullptr);
1193 
1194   for (const auto &P : CUMap) {
1195     auto &CU = *P.second;
1196     CU.createBaseTypeDIEs();
1197   }
1198 
1199   // If we aren't actually generating debug info (check beginModule -
1200   // conditionalized on !DisableDebugInfoPrinting and the presence of the
1201   // llvm.dbg.cu metadata node)
1202   if (!MMI->hasDebugInfo())
1203     return;
1204 
1205   // Finalize the debug info for the module.
1206   finalizeModuleInfo();
1207 
1208   emitDebugStr();
1209 
1210   if (useSplitDwarf())
1211     // Emit debug_loc.dwo/debug_loclists.dwo section.
1212     emitDebugLocDWO();
1213   else
1214     // Emit debug_loc/debug_loclists section.
1215     emitDebugLoc();
1216 
1217   // Corresponding abbreviations into a abbrev section.
1218   emitAbbreviations();
1219 
1220   // Emit all the DIEs into a debug info section.
1221   emitDebugInfo();
1222 
1223   // Emit info into a debug aranges section.
1224   if (GenerateARangeSection)
1225     emitDebugARanges();
1226 
1227   // Emit info into a debug ranges section.
1228   emitDebugRanges();
1229 
1230   if (useSplitDwarf())
1231   // Emit info into a debug macinfo.dwo section.
1232     emitDebugMacinfoDWO();
1233   else
1234   // Emit info into a debug macinfo section.
1235     emitDebugMacinfo();
1236 
1237   if (useSplitDwarf()) {
1238     emitDebugStrDWO();
1239     emitDebugInfoDWO();
1240     emitDebugAbbrevDWO();
1241     emitDebugLineDWO();
1242     emitDebugRangesDWO();
1243   }
1244 
1245   emitDebugAddr();
1246 
1247   // Emit info into the dwarf accelerator table sections.
1248   switch (getAccelTableKind()) {
1249   case AccelTableKind::Apple:
1250     emitAccelNames();
1251     emitAccelObjC();
1252     emitAccelNamespaces();
1253     emitAccelTypes();
1254     break;
1255   case AccelTableKind::Dwarf:
1256     emitAccelDebugNames();
1257     break;
1258   case AccelTableKind::None:
1259     break;
1260   case AccelTableKind::Default:
1261     llvm_unreachable("Default should have already been resolved.");
1262   }
1263 
1264   // Emit the pubnames and pubtypes sections if requested.
1265   emitDebugPubSections();
1266 
1267   // clean up.
1268   // FIXME: AbstractVariables.clear();
1269 }
1270 
1271 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1272                                                const DINode *Node,
1273                                                const MDNode *ScopeNode) {
1274   if (CU.getExistingAbstractEntity(Node))
1275     return;
1276 
1277   CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
1278                                        cast<DILocalScope>(ScopeNode)));
1279 }
1280 
1281 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1282     const DINode *Node, const MDNode *ScopeNode) {
1283   if (CU.getExistingAbstractEntity(Node))
1284     return;
1285 
1286   if (LexicalScope *Scope =
1287           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1288     CU.createAbstractEntity(Node, Scope);
1289 }
1290 
1291 // Collect variable information from side table maintained by MF.
1292 void DwarfDebug::collectVariableInfoFromMFTable(
1293     DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1294   SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1295   for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1296     if (!VI.Var)
1297       continue;
1298     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1299            "Expected inlined-at fields to agree");
1300 
1301     InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1302     Processed.insert(Var);
1303     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1304 
1305     // If variable scope is not found then skip this variable.
1306     if (!Scope)
1307       continue;
1308 
1309     ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1310     auto RegVar = std::make_unique<DbgVariable>(
1311                     cast<DILocalVariable>(Var.first), Var.second);
1312     RegVar->initializeMMI(VI.Expr, VI.Slot);
1313     if (DbgVariable *DbgVar = MFVars.lookup(Var))
1314       DbgVar->addMMIEntry(*RegVar);
1315     else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1316       MFVars.insert({Var, RegVar.get()});
1317       ConcreteEntities.push_back(std::move(RegVar));
1318     }
1319   }
1320 }
1321 
1322 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1323 /// enclosing lexical scope. The check ensures there are no other instructions
1324 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1325 /// either open or otherwise rolls off the end of the scope.
1326 static bool validThroughout(LexicalScopes &LScopes,
1327                             const MachineInstr *DbgValue,
1328                             const MachineInstr *RangeEnd) {
1329   assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1330   auto MBB = DbgValue->getParent();
1331   auto DL = DbgValue->getDebugLoc();
1332   auto *LScope = LScopes.findLexicalScope(DL);
1333   // Scope doesn't exist; this is a dead DBG_VALUE.
1334   if (!LScope)
1335     return false;
1336   auto &LSRange = LScope->getRanges();
1337   if (LSRange.size() == 0)
1338     return false;
1339 
1340   // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1341   const MachineInstr *LScopeBegin = LSRange.front().first;
1342   // Early exit if the lexical scope begins outside of the current block.
1343   if (LScopeBegin->getParent() != MBB)
1344     return false;
1345   MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1346   for (++Pred; Pred != MBB->rend(); ++Pred) {
1347     if (Pred->getFlag(MachineInstr::FrameSetup))
1348       break;
1349     auto PredDL = Pred->getDebugLoc();
1350     if (!PredDL || Pred->isMetaInstruction())
1351       continue;
1352     // Check whether the instruction preceding the DBG_VALUE is in the same
1353     // (sub)scope as the DBG_VALUE.
1354     if (DL->getScope() == PredDL->getScope())
1355       return false;
1356     auto *PredScope = LScopes.findLexicalScope(PredDL);
1357     if (!PredScope || LScope->dominates(PredScope))
1358       return false;
1359   }
1360 
1361   // If the range of the DBG_VALUE is open-ended, report success.
1362   if (!RangeEnd)
1363     return true;
1364 
1365   // Fail if there are instructions belonging to our scope in another block.
1366   const MachineInstr *LScopeEnd = LSRange.back().second;
1367   if (LScopeEnd->getParent() != MBB)
1368     return false;
1369 
1370   // Single, constant DBG_VALUEs in the prologue are promoted to be live
1371   // throughout the function. This is a hack, presumably for DWARF v2 and not
1372   // necessarily correct. It would be much better to use a dbg.declare instead
1373   // if we know the constant is live throughout the scope.
1374   if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1375     return true;
1376 
1377   return false;
1378 }
1379 
1380 /// Build the location list for all DBG_VALUEs in the function that
1381 /// describe the same variable. The resulting DebugLocEntries will have
1382 /// strict monotonically increasing begin addresses and will never
1383 /// overlap. If the resulting list has only one entry that is valid
1384 /// throughout variable's scope return true.
1385 //
1386 // See the definition of DbgValueHistoryMap::Entry for an explanation of the
1387 // different kinds of history map entries. One thing to be aware of is that if
1388 // a debug value is ended by another entry (rather than being valid until the
1389 // end of the function), that entry's instruction may or may not be included in
1390 // the range, depending on if the entry is a clobbering entry (it has an
1391 // instruction that clobbers one or more preceding locations), or if it is an
1392 // (overlapping) debug value entry. This distinction can be seen in the example
1393 // below. The first debug value is ended by the clobbering entry 2, and the
1394 // second and third debug values are ended by the overlapping debug value entry
1395 // 4.
1396 //
1397 // Input:
1398 //
1399 //   History map entries [type, end index, mi]
1400 //
1401 // 0 |      [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1402 // 1 | |    [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1403 // 2 | |    [Clobber, $reg0 = [...], -, -]
1404 // 3   | |  [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1405 // 4        [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1406 //
1407 // Output [start, end) [Value...]:
1408 //
1409 // [0-1)    [(reg0, fragment 0, 32)]
1410 // [1-3)    [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1411 // [3-4)    [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1412 // [4-)     [(@g, fragment 0, 96)]
1413 bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1414                                    const DbgValueHistoryMap::Entries &Entries) {
1415   using OpenRange =
1416       std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1417   SmallVector<OpenRange, 4> OpenRanges;
1418   bool isSafeForSingleLocation = true;
1419   const MachineInstr *StartDebugMI = nullptr;
1420   const MachineInstr *EndMI = nullptr;
1421 
1422   for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1423     const MachineInstr *Instr = EI->getInstr();
1424 
1425     // Remove all values that are no longer live.
1426     size_t Index = std::distance(EB, EI);
1427     auto Last =
1428         remove_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1429     OpenRanges.erase(Last, OpenRanges.end());
1430 
1431     // If we are dealing with a clobbering entry, this iteration will result in
1432     // a location list entry starting after the clobbering instruction.
1433     const MCSymbol *StartLabel =
1434         EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1435     assert(StartLabel &&
1436            "Forgot label before/after instruction starting a range!");
1437 
1438     const MCSymbol *EndLabel;
1439     if (std::next(EI) == Entries.end()) {
1440       EndLabel = Asm->getFunctionEnd();
1441       if (EI->isClobber())
1442         EndMI = EI->getInstr();
1443     }
1444     else if (std::next(EI)->isClobber())
1445       EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1446     else
1447       EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1448     assert(EndLabel && "Forgot label after instruction ending a range!");
1449 
1450     if (EI->isDbgValue())
1451       LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1452 
1453     // If this history map entry has a debug value, add that to the list of
1454     // open ranges and check if its location is valid for a single value
1455     // location.
1456     if (EI->isDbgValue()) {
1457       // Do not add undef debug values, as they are redundant information in
1458       // the location list entries. An undef debug results in an empty location
1459       // description. If there are any non-undef fragments then padding pieces
1460       // with empty location descriptions will automatically be inserted, and if
1461       // all fragments are undef then the whole location list entry is
1462       // redundant.
1463       if (!Instr->isUndefDebugValue()) {
1464         auto Value = getDebugLocValue(Instr);
1465         OpenRanges.emplace_back(EI->getEndIndex(), Value);
1466 
1467         // TODO: Add support for single value fragment locations.
1468         if (Instr->getDebugExpression()->isFragment())
1469           isSafeForSingleLocation = false;
1470 
1471         if (!StartDebugMI)
1472           StartDebugMI = Instr;
1473       } else {
1474         isSafeForSingleLocation = false;
1475       }
1476     }
1477 
1478     // Location list entries with empty location descriptions are redundant
1479     // information in DWARF, so do not emit those.
1480     if (OpenRanges.empty())
1481       continue;
1482 
1483     // Omit entries with empty ranges as they do not have any effect in DWARF.
1484     if (StartLabel == EndLabel) {
1485       LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1486       continue;
1487     }
1488 
1489     SmallVector<DbgValueLoc, 4> Values;
1490     for (auto &R : OpenRanges)
1491       Values.push_back(R.second);
1492     DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1493 
1494     // Attempt to coalesce the ranges of two otherwise identical
1495     // DebugLocEntries.
1496     auto CurEntry = DebugLoc.rbegin();
1497     LLVM_DEBUG({
1498       dbgs() << CurEntry->getValues().size() << " Values:\n";
1499       for (auto &Value : CurEntry->getValues())
1500         Value.dump();
1501       dbgs() << "-----\n";
1502     });
1503 
1504     auto PrevEntry = std::next(CurEntry);
1505     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1506       DebugLoc.pop_back();
1507   }
1508 
1509   return DebugLoc.size() == 1 && isSafeForSingleLocation &&
1510          validThroughout(LScopes, StartDebugMI, EndMI);
1511 }
1512 
1513 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1514                                             LexicalScope &Scope,
1515                                             const DINode *Node,
1516                                             const DILocation *Location,
1517                                             const MCSymbol *Sym) {
1518   ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1519   if (isa<const DILocalVariable>(Node)) {
1520     ConcreteEntities.push_back(
1521         std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1522                                        Location));
1523     InfoHolder.addScopeVariable(&Scope,
1524         cast<DbgVariable>(ConcreteEntities.back().get()));
1525   } else if (isa<const DILabel>(Node)) {
1526     ConcreteEntities.push_back(
1527         std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1528                                     Location, Sym));
1529     InfoHolder.addScopeLabel(&Scope,
1530         cast<DbgLabel>(ConcreteEntities.back().get()));
1531   }
1532   return ConcreteEntities.back().get();
1533 }
1534 
1535 // Find variables for each lexical scope.
1536 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1537                                    const DISubprogram *SP,
1538                                    DenseSet<InlinedEntity> &Processed) {
1539   // Grab the variable info that was squirreled away in the MMI side-table.
1540   collectVariableInfoFromMFTable(TheCU, Processed);
1541 
1542   for (const auto &I : DbgValues) {
1543     InlinedEntity IV = I.first;
1544     if (Processed.count(IV))
1545       continue;
1546 
1547     // Instruction ranges, specifying where IV is accessible.
1548     const auto &HistoryMapEntries = I.second;
1549     if (HistoryMapEntries.empty())
1550       continue;
1551 
1552     LexicalScope *Scope = nullptr;
1553     const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1554     if (const DILocation *IA = IV.second)
1555       Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1556     else
1557       Scope = LScopes.findLexicalScope(LocalVar->getScope());
1558     // If variable scope is not found then skip this variable.
1559     if (!Scope)
1560       continue;
1561 
1562     Processed.insert(IV);
1563     DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1564                                             *Scope, LocalVar, IV.second));
1565 
1566     const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1567     assert(MInsn->isDebugValue() && "History must begin with debug value");
1568 
1569     // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1570     // If the history map contains a single debug value, there may be an
1571     // additional entry which clobbers the debug value.
1572     size_t HistSize = HistoryMapEntries.size();
1573     bool SingleValueWithClobber =
1574         HistSize == 2 && HistoryMapEntries[1].isClobber();
1575     if (HistSize == 1 || SingleValueWithClobber) {
1576       const auto *End =
1577           SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1578       if (validThroughout(LScopes, MInsn, End)) {
1579         RegVar->initializeDbgValue(MInsn);
1580         continue;
1581       }
1582     }
1583 
1584     // Do not emit location lists if .debug_loc secton is disabled.
1585     if (!useLocSection())
1586       continue;
1587 
1588     // Handle multiple DBG_VALUE instructions describing one variable.
1589     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1590 
1591     // Build the location list for this variable.
1592     SmallVector<DebugLocEntry, 8> Entries;
1593     bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1594 
1595     // Check whether buildLocationList managed to merge all locations to one
1596     // that is valid throughout the variable's scope. If so, produce single
1597     // value location.
1598     if (isValidSingleLocation) {
1599       RegVar->initializeDbgValue(Entries[0].getValues()[0]);
1600       continue;
1601     }
1602 
1603     // If the variable has a DIBasicType, extract it.  Basic types cannot have
1604     // unique identifiers, so don't bother resolving the type with the
1605     // identifier map.
1606     const DIBasicType *BT = dyn_cast<DIBasicType>(
1607         static_cast<const Metadata *>(LocalVar->getType()));
1608 
1609     // Finalize the entry by lowering it into a DWARF bytestream.
1610     for (auto &Entry : Entries)
1611       Entry.finalize(*Asm, List, BT, TheCU);
1612   }
1613 
1614   // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1615   // DWARF-related DbgLabel.
1616   for (const auto &I : DbgLabels) {
1617     InlinedEntity IL = I.first;
1618     const MachineInstr *MI = I.second;
1619     if (MI == nullptr)
1620       continue;
1621 
1622     LexicalScope *Scope = nullptr;
1623     const DILabel *Label = cast<DILabel>(IL.first);
1624     // The scope could have an extra lexical block file.
1625     const DILocalScope *LocalScope =
1626         Label->getScope()->getNonLexicalBlockFileScope();
1627     // Get inlined DILocation if it is inlined label.
1628     if (const DILocation *IA = IL.second)
1629       Scope = LScopes.findInlinedScope(LocalScope, IA);
1630     else
1631       Scope = LScopes.findLexicalScope(LocalScope);
1632     // If label scope is not found then skip this label.
1633     if (!Scope)
1634       continue;
1635 
1636     Processed.insert(IL);
1637     /// At this point, the temporary label is created.
1638     /// Save the temporary label to DbgLabel entity to get the
1639     /// actually address when generating Dwarf DIE.
1640     MCSymbol *Sym = getLabelBeforeInsn(MI);
1641     createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1642   }
1643 
1644   // Collect info for variables/labels that were optimized out.
1645   for (const DINode *DN : SP->getRetainedNodes()) {
1646     if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1647       continue;
1648     LexicalScope *Scope = nullptr;
1649     if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1650       Scope = LScopes.findLexicalScope(DV->getScope());
1651     } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1652       Scope = LScopes.findLexicalScope(DL->getScope());
1653     }
1654 
1655     if (Scope)
1656       createConcreteEntity(TheCU, *Scope, DN, nullptr);
1657   }
1658 }
1659 
1660 // Process beginning of an instruction.
1661 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1662   DebugHandlerBase::beginInstruction(MI);
1663   assert(CurMI);
1664 
1665   const auto *SP = MI->getMF()->getFunction().getSubprogram();
1666   if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1667     return;
1668 
1669   // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1670   // If the instruction is part of the function frame setup code, do not emit
1671   // any line record, as there is no correspondence with any user code.
1672   if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1673     return;
1674   const DebugLoc &DL = MI->getDebugLoc();
1675   // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1676   // the last line number actually emitted, to see if it was line 0.
1677   unsigned LastAsmLine =
1678       Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1679 
1680   // Request a label after the call in order to emit AT_return_pc information
1681   // in call site entries. TODO: Add support for targets with delay slots.
1682   if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot())
1683     requestLabelAfterInsn(MI);
1684 
1685   if (DL == PrevInstLoc) {
1686     // If we have an ongoing unspecified location, nothing to do here.
1687     if (!DL)
1688       return;
1689     // We have an explicit location, same as the previous location.
1690     // But we might be coming back to it after a line 0 record.
1691     if (LastAsmLine == 0 && DL.getLine() != 0) {
1692       // Reinstate the source location but not marked as a statement.
1693       const MDNode *Scope = DL.getScope();
1694       recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1695     }
1696     return;
1697   }
1698 
1699   if (!DL) {
1700     // We have an unspecified location, which might want to be line 0.
1701     // If we have already emitted a line-0 record, don't repeat it.
1702     if (LastAsmLine == 0)
1703       return;
1704     // If user said Don't Do That, don't do that.
1705     if (UnknownLocations == Disable)
1706       return;
1707     // See if we have a reason to emit a line-0 record now.
1708     // Reasons to emit a line-0 record include:
1709     // - User asked for it (UnknownLocations).
1710     // - Instruction has a label, so it's referenced from somewhere else,
1711     //   possibly debug information; we want it to have a source location.
1712     // - Instruction is at the top of a block; we don't want to inherit the
1713     //   location from the physically previous (maybe unrelated) block.
1714     if (UnknownLocations == Enable || PrevLabel ||
1715         (PrevInstBB && PrevInstBB != MI->getParent())) {
1716       // Preserve the file and column numbers, if we can, to save space in
1717       // the encoded line table.
1718       // Do not update PrevInstLoc, it remembers the last non-0 line.
1719       const MDNode *Scope = nullptr;
1720       unsigned Column = 0;
1721       if (PrevInstLoc) {
1722         Scope = PrevInstLoc.getScope();
1723         Column = PrevInstLoc.getCol();
1724       }
1725       recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1726     }
1727     return;
1728   }
1729 
1730   // We have an explicit location, different from the previous location.
1731   // Don't repeat a line-0 record, but otherwise emit the new location.
1732   // (The new location might be an explicit line 0, which we do emit.)
1733   if (DL.getLine() == 0 && LastAsmLine == 0)
1734     return;
1735   unsigned Flags = 0;
1736   if (DL == PrologEndLoc) {
1737     Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1738     PrologEndLoc = DebugLoc();
1739   }
1740   // If the line changed, we call that a new statement; unless we went to
1741   // line 0 and came back, in which case it is not a new statement.
1742   unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1743   if (DL.getLine() && DL.getLine() != OldLine)
1744     Flags |= DWARF2_FLAG_IS_STMT;
1745 
1746   const MDNode *Scope = DL.getScope();
1747   recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1748 
1749   // If we're not at line 0, remember this location.
1750   if (DL.getLine())
1751     PrevInstLoc = DL;
1752 }
1753 
1754 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1755   // First known non-DBG_VALUE and non-frame setup location marks
1756   // the beginning of the function body.
1757   for (const auto &MBB : *MF)
1758     for (const auto &MI : MBB)
1759       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1760           MI.getDebugLoc())
1761         return MI.getDebugLoc();
1762   return DebugLoc();
1763 }
1764 
1765 /// Register a source line with debug info. Returns the  unique label that was
1766 /// emitted and which provides correspondence to the source line list.
1767 static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
1768                              const MDNode *S, unsigned Flags, unsigned CUID,
1769                              uint16_t DwarfVersion,
1770                              ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
1771   StringRef Fn;
1772   unsigned FileNo = 1;
1773   unsigned Discriminator = 0;
1774   if (auto *Scope = cast_or_null<DIScope>(S)) {
1775     Fn = Scope->getFilename();
1776     if (Line != 0 && DwarfVersion >= 4)
1777       if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1778         Discriminator = LBF->getDiscriminator();
1779 
1780     FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
1781                  .getOrCreateSourceID(Scope->getFile());
1782   }
1783   Asm.OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
1784                                          Discriminator, Fn);
1785 }
1786 
1787 DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
1788                                              unsigned CUID) {
1789   // Get beginning of function.
1790   if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
1791     // Ensure the compile unit is created if the function is called before
1792     // beginFunction().
1793     (void)getOrCreateDwarfCompileUnit(
1794         MF.getFunction().getSubprogram()->getUnit());
1795     // We'd like to list the prologue as "not statements" but GDB behaves
1796     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1797     const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1798     ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
1799                        CUID, getDwarfVersion(), getUnits());
1800     return PrologEndLoc;
1801   }
1802   return DebugLoc();
1803 }
1804 
1805 // Gather pre-function debug information.  Assumes being called immediately
1806 // after the function entry point has been emitted.
1807 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1808   CurFn = MF;
1809 
1810   auto *SP = MF->getFunction().getSubprogram();
1811   assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1812   if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1813     return;
1814 
1815   SectionLabels.insert(std::make_pair(&Asm->getFunctionBegin()->getSection(),
1816                                       Asm->getFunctionBegin()));
1817 
1818   DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1819 
1820   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1821   // belongs to so that we add to the correct per-cu line table in the
1822   // non-asm case.
1823   if (Asm->OutStreamer->hasRawTextSupport())
1824     // Use a single line table if we are generating assembly.
1825     Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1826   else
1827     Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1828 
1829   // Record beginning of function.
1830   PrologEndLoc = emitInitialLocDirective(
1831       *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
1832 }
1833 
1834 void DwarfDebug::skippedNonDebugFunction() {
1835   // If we don't have a subprogram for this function then there will be a hole
1836   // in the range information. Keep note of this by setting the previously used
1837   // section to nullptr.
1838   PrevCU = nullptr;
1839   CurFn = nullptr;
1840 }
1841 
1842 // Gather and emit post-function debug information.
1843 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1844   const DISubprogram *SP = MF->getFunction().getSubprogram();
1845 
1846   assert(CurFn == MF &&
1847       "endFunction should be called with the same function as beginFunction");
1848 
1849   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1850   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1851 
1852   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1853   assert(!FnScope || SP == FnScope->getScopeNode());
1854   DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1855   if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
1856     PrevLabel = nullptr;
1857     CurFn = nullptr;
1858     return;
1859   }
1860 
1861   DenseSet<InlinedEntity> Processed;
1862   collectEntityInfo(TheCU, SP, Processed);
1863 
1864   // Add the range of this function to the list of ranges for the CU.
1865   TheCU.addRange({Asm->getFunctionBegin(), Asm->getFunctionEnd()});
1866 
1867   // Under -gmlt, skip building the subprogram if there are no inlined
1868   // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1869   // is still needed as we need its source location.
1870   if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1871       TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1872       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1873     assert(InfoHolder.getScopeVariables().empty());
1874     PrevLabel = nullptr;
1875     CurFn = nullptr;
1876     return;
1877   }
1878 
1879 #ifndef NDEBUG
1880   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1881 #endif
1882   // Construct abstract scopes.
1883   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1884     auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1885     for (const DINode *DN : SP->getRetainedNodes()) {
1886       if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1887         continue;
1888 
1889       const MDNode *Scope = nullptr;
1890       if (auto *DV = dyn_cast<DILocalVariable>(DN))
1891         Scope = DV->getScope();
1892       else if (auto *DL = dyn_cast<DILabel>(DN))
1893         Scope = DL->getScope();
1894       else
1895         llvm_unreachable("Unexpected DI type!");
1896 
1897       // Collect info for variables/labels that were optimized out.
1898       ensureAbstractEntityIsCreated(TheCU, DN, Scope);
1899       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1900              && "ensureAbstractEntityIsCreated inserted abstract scopes");
1901     }
1902     constructAbstractSubprogramScopeDIE(TheCU, AScope);
1903   }
1904 
1905   ProcessedSPNodes.insert(SP);
1906   DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
1907   if (auto *SkelCU = TheCU.getSkeleton())
1908     if (!LScopes.getAbstractScopesList().empty() &&
1909         TheCU.getCUNode()->getSplitDebugInlining())
1910       SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1911 
1912   // Construct call site entries.
1913   constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
1914 
1915   // Clear debug info
1916   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1917   // DbgVariables except those that are also in AbstractVariables (since they
1918   // can be used cross-function)
1919   InfoHolder.getScopeVariables().clear();
1920   InfoHolder.getScopeLabels().clear();
1921   PrevLabel = nullptr;
1922   CurFn = nullptr;
1923 }
1924 
1925 // Register a source line with debug info. Returns the  unique label that was
1926 // emitted and which provides correspondence to the source line list.
1927 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1928                                   unsigned Flags) {
1929   ::recordSourceLine(*Asm, Line, Col, S, Flags,
1930                      Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
1931                      getDwarfVersion(), getUnits());
1932 }
1933 
1934 //===----------------------------------------------------------------------===//
1935 // Emit Methods
1936 //===----------------------------------------------------------------------===//
1937 
1938 // Emit the debug info section.
1939 void DwarfDebug::emitDebugInfo() {
1940   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1941   Holder.emitUnits(/* UseOffsets */ false);
1942 }
1943 
1944 // Emit the abbreviation section.
1945 void DwarfDebug::emitAbbreviations() {
1946   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1947 
1948   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1949 }
1950 
1951 void DwarfDebug::emitStringOffsetsTableHeader() {
1952   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1953   Holder.getStringPool().emitStringOffsetsTableHeader(
1954       *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
1955       Holder.getStringOffsetsStartSym());
1956 }
1957 
1958 template <typename AccelTableT>
1959 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
1960                            StringRef TableName) {
1961   Asm->OutStreamer->SwitchSection(Section);
1962 
1963   // Emit the full data.
1964   emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
1965 }
1966 
1967 void DwarfDebug::emitAccelDebugNames() {
1968   // Don't emit anything if we have no compilation units to index.
1969   if (getUnits().empty())
1970     return;
1971 
1972   emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
1973 }
1974 
1975 // Emit visible names into a hashed accelerator table section.
1976 void DwarfDebug::emitAccelNames() {
1977   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1978             "Names");
1979 }
1980 
1981 // Emit objective C classes and categories into a hashed accelerator table
1982 // section.
1983 void DwarfDebug::emitAccelObjC() {
1984   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1985             "ObjC");
1986 }
1987 
1988 // Emit namespace dies into a hashed accelerator table.
1989 void DwarfDebug::emitAccelNamespaces() {
1990   emitAccel(AccelNamespace,
1991             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1992             "namespac");
1993 }
1994 
1995 // Emit type dies into a hashed accelerator table.
1996 void DwarfDebug::emitAccelTypes() {
1997   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1998             "types");
1999 }
2000 
2001 // Public name handling.
2002 // The format for the various pubnames:
2003 //
2004 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2005 // for the DIE that is named.
2006 //
2007 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2008 // into the CU and the index value is computed according to the type of value
2009 // for the DIE that is named.
2010 //
2011 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2012 // it's the offset within the debug_info/debug_types dwo section, however, the
2013 // reference in the pubname header doesn't change.
2014 
2015 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2016 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2017                                                         const DIE *Die) {
2018   // Entities that ended up only in a Type Unit reference the CU instead (since
2019   // the pub entry has offsets within the CU there's no real offset that can be
2020   // provided anyway). As it happens all such entities (namespaces and types,
2021   // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2022   // not to be true it would be necessary to persist this information from the
2023   // point at which the entry is added to the index data structure - since by
2024   // the time the index is built from that, the original type/namespace DIE in a
2025   // type unit has already been destroyed so it can't be queried for properties
2026   // like tag, etc.
2027   if (Die->getTag() == dwarf::DW_TAG_compile_unit)
2028     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
2029                                           dwarf::GIEL_EXTERNAL);
2030   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2031 
2032   // We could have a specification DIE that has our most of our knowledge,
2033   // look for that now.
2034   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
2035     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
2036     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
2037       Linkage = dwarf::GIEL_EXTERNAL;
2038   } else if (Die->findAttribute(dwarf::DW_AT_external))
2039     Linkage = dwarf::GIEL_EXTERNAL;
2040 
2041   switch (Die->getTag()) {
2042   case dwarf::DW_TAG_class_type:
2043   case dwarf::DW_TAG_structure_type:
2044   case dwarf::DW_TAG_union_type:
2045   case dwarf::DW_TAG_enumeration_type:
2046     return dwarf::PubIndexEntryDescriptor(
2047         dwarf::GIEK_TYPE,
2048         dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
2049             ? dwarf::GIEL_EXTERNAL
2050             : dwarf::GIEL_STATIC);
2051   case dwarf::DW_TAG_typedef:
2052   case dwarf::DW_TAG_base_type:
2053   case dwarf::DW_TAG_subrange_type:
2054     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2055   case dwarf::DW_TAG_namespace:
2056     return dwarf::GIEK_TYPE;
2057   case dwarf::DW_TAG_subprogram:
2058     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2059   case dwarf::DW_TAG_variable:
2060     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2061   case dwarf::DW_TAG_enumerator:
2062     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2063                                           dwarf::GIEL_STATIC);
2064   default:
2065     return dwarf::GIEK_NONE;
2066   }
2067 }
2068 
2069 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
2070 /// pubtypes sections.
2071 void DwarfDebug::emitDebugPubSections() {
2072   for (const auto &NU : CUMap) {
2073     DwarfCompileUnit *TheU = NU.second;
2074     if (!TheU->hasDwarfPubSections())
2075       continue;
2076 
2077     bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
2078                     DICompileUnit::DebugNameTableKind::GNU;
2079 
2080     Asm->OutStreamer->SwitchSection(
2081         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2082                  : Asm->getObjFileLowering().getDwarfPubNamesSection());
2083     emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
2084 
2085     Asm->OutStreamer->SwitchSection(
2086         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2087                  : Asm->getObjFileLowering().getDwarfPubTypesSection());
2088     emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
2089   }
2090 }
2091 
2092 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
2093   if (useSectionsAsReferences())
2094     Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(),
2095                          CU.getDebugSectionOffset());
2096   else
2097     Asm->emitDwarfSymbolReference(CU.getLabelBegin());
2098 }
2099 
2100 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
2101                                      DwarfCompileUnit *TheU,
2102                                      const StringMap<const DIE *> &Globals) {
2103   if (auto *Skeleton = TheU->getSkeleton())
2104     TheU = Skeleton;
2105 
2106   // Emit the header.
2107   Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
2108   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
2109   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
2110   Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2111 
2112   Asm->OutStreamer->EmitLabel(BeginLabel);
2113 
2114   Asm->OutStreamer->AddComment("DWARF Version");
2115   Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
2116 
2117   Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
2118   emitSectionReference(*TheU);
2119 
2120   Asm->OutStreamer->AddComment("Compilation Unit Length");
2121   Asm->emitInt32(TheU->getLength());
2122 
2123   // Emit the pubnames for this compilation unit.
2124   for (const auto &GI : Globals) {
2125     const char *Name = GI.getKeyData();
2126     const DIE *Entity = GI.second;
2127 
2128     Asm->OutStreamer->AddComment("DIE offset");
2129     Asm->emitInt32(Entity->getOffset());
2130 
2131     if (GnuStyle) {
2132       dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2133       Asm->OutStreamer->AddComment(
2134           Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
2135           ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2136       Asm->emitInt8(Desc.toBits());
2137     }
2138 
2139     Asm->OutStreamer->AddComment("External Name");
2140     Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2141   }
2142 
2143   Asm->OutStreamer->AddComment("End Mark");
2144   Asm->emitInt32(0);
2145   Asm->OutStreamer->EmitLabel(EndLabel);
2146 }
2147 
2148 /// Emit null-terminated strings into a debug str section.
2149 void DwarfDebug::emitDebugStr() {
2150   MCSection *StringOffsetsSection = nullptr;
2151   if (useSegmentedStringOffsetsTable()) {
2152     emitStringOffsetsTableHeader();
2153     StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
2154   }
2155   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2156   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
2157                      StringOffsetsSection, /* UseRelativeOffsets = */ true);
2158 }
2159 
2160 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2161                                    const DebugLocStream::Entry &Entry,
2162                                    const DwarfCompileUnit *CU) {
2163   auto &&Comments = DebugLocs.getComments(Entry);
2164   auto Comment = Comments.begin();
2165   auto End = Comments.end();
2166 
2167   // The expressions are inserted into a byte stream rather early (see
2168   // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2169   // need to reference a base_type DIE the offset of that DIE is not yet known.
2170   // To deal with this we instead insert a placeholder early and then extract
2171   // it here and replace it with the real reference.
2172   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2173   DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
2174                                     DebugLocs.getBytes(Entry).size()),
2175                           Asm->getDataLayout().isLittleEndian(), PtrSize);
2176   DWARFExpression Expr(Data, getDwarfVersion(), PtrSize);
2177 
2178   using Encoding = DWARFExpression::Operation::Encoding;
2179   uint64_t Offset = 0;
2180   for (auto &Op : Expr) {
2181     assert(Op.getCode() != dwarf::DW_OP_const_type &&
2182            "3 operand ops not yet supported");
2183     Streamer.EmitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
2184     Offset++;
2185     for (unsigned I = 0; I < 2; ++I) {
2186       if (Op.getDescription().Op[I] == Encoding::SizeNA)
2187         continue;
2188       if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
2189           if (CU) {
2190             uint64_t Offset = CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset();
2191             assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit");
2192             Asm->EmitULEB128(Offset, nullptr, ULEB128PadSize);
2193           } else {
2194             // Emit a reference to the 'generic type'.
2195             Asm->EmitULEB128(0, nullptr, ULEB128PadSize);
2196           }
2197           // Make sure comments stay aligned.
2198           for (unsigned J = 0; J < ULEB128PadSize; ++J)
2199             if (Comment != End)
2200               Comment++;
2201       } else {
2202         for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2203           Streamer.EmitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
2204       }
2205       Offset = Op.getOperandEndOffset(I);
2206     }
2207     assert(Offset == Op.getEndOffset());
2208   }
2209 }
2210 
2211 void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
2212                                    const DbgValueLoc &Value,
2213                                    DwarfExpression &DwarfExpr) {
2214   auto *DIExpr = Value.getExpression();
2215   DIExpressionCursor ExprCursor(DIExpr);
2216   DwarfExpr.addFragmentOffset(DIExpr);
2217   // Regular entry.
2218   if (Value.isInt()) {
2219     if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
2220                BT->getEncoding() == dwarf::DW_ATE_signed_char))
2221       DwarfExpr.addSignedConstant(Value.getInt());
2222     else
2223       DwarfExpr.addUnsignedConstant(Value.getInt());
2224   } else if (Value.isLocation()) {
2225     MachineLocation Location = Value.getLoc();
2226     if (Location.isIndirect())
2227       DwarfExpr.setMemoryLocationKind();
2228     DIExpressionCursor Cursor(DIExpr);
2229 
2230     if (DIExpr->isEntryValue()) {
2231       DwarfExpr.setEntryValueFlag();
2232       DwarfExpr.beginEntryValueExpression(Cursor);
2233     }
2234 
2235     const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2236     if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2237       return;
2238     return DwarfExpr.addExpression(std::move(Cursor));
2239   } else if (Value.isConstantFP()) {
2240     APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
2241     DwarfExpr.addUnsignedConstant(RawBytes);
2242   }
2243   DwarfExpr.addExpression(std::move(ExprCursor));
2244 }
2245 
2246 void DebugLocEntry::finalize(const AsmPrinter &AP,
2247                              DebugLocStream::ListBuilder &List,
2248                              const DIBasicType *BT,
2249                              DwarfCompileUnit &TheCU) {
2250   assert(!Values.empty() &&
2251          "location list entries without values are redundant");
2252   assert(Begin != End && "unexpected location list entry with empty range");
2253   DebugLocStream::EntryBuilder Entry(List, Begin, End);
2254   BufferByteStreamer Streamer = Entry.getStreamer();
2255   DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2256   const DbgValueLoc &Value = Values[0];
2257   if (Value.isFragment()) {
2258     // Emit all fragments that belong to the same variable and range.
2259     assert(llvm::all_of(Values, [](DbgValueLoc P) {
2260           return P.isFragment();
2261         }) && "all values are expected to be fragments");
2262     assert(std::is_sorted(Values.begin(), Values.end()) &&
2263            "fragments are expected to be sorted");
2264 
2265     for (auto Fragment : Values)
2266       DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2267 
2268   } else {
2269     assert(Values.size() == 1 && "only fragments may have >1 value");
2270     DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
2271   }
2272   DwarfExpr.finalize();
2273 }
2274 
2275 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
2276                                            const DwarfCompileUnit *CU) {
2277   // Emit the size.
2278   Asm->OutStreamer->AddComment("Loc expr size");
2279   if (getDwarfVersion() >= 5)
2280     Asm->EmitULEB128(DebugLocs.getBytes(Entry).size());
2281   else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2282     Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2283   else {
2284     // The entry is too big to fit into 16 bit, drop it as there is nothing we
2285     // can do.
2286     Asm->emitInt16(0);
2287     return;
2288   }
2289   // Emit the entry.
2290   APByteStreamer Streamer(*Asm);
2291   emitDebugLocEntry(Streamer, Entry, CU);
2292 }
2293 
2294 // Emit the common part of the DWARF 5 range/locations list tables header.
2295 static void emitListsTableHeaderStart(AsmPrinter *Asm,
2296                                       MCSymbol *TableStart,
2297                                       MCSymbol *TableEnd) {
2298   // Build the table header, which starts with the length field.
2299   Asm->OutStreamer->AddComment("Length");
2300   Asm->EmitLabelDifference(TableEnd, TableStart, 4);
2301   Asm->OutStreamer->EmitLabel(TableStart);
2302   // Version number (DWARF v5 and later).
2303   Asm->OutStreamer->AddComment("Version");
2304   Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion());
2305   // Address size.
2306   Asm->OutStreamer->AddComment("Address size");
2307   Asm->emitInt8(Asm->MAI->getCodePointerSize());
2308   // Segment selector size.
2309   Asm->OutStreamer->AddComment("Segment selector size");
2310   Asm->emitInt8(0);
2311 }
2312 
2313 // Emit the header of a DWARF 5 range list table list table. Returns the symbol
2314 // that designates the end of the table for the caller to emit when the table is
2315 // complete.
2316 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
2317                                          const DwarfFile &Holder) {
2318   MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start");
2319   MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end");
2320   emitListsTableHeaderStart(Asm, TableStart, TableEnd);
2321 
2322   Asm->OutStreamer->AddComment("Offset entry count");
2323   Asm->emitInt32(Holder.getRangeLists().size());
2324   Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym());
2325 
2326   for (const RangeSpanList &List : Holder.getRangeLists())
2327     Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(),
2328                              4);
2329 
2330   return TableEnd;
2331 }
2332 
2333 // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2334 // designates the end of the table for the caller to emit when the table is
2335 // complete.
2336 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
2337                                          const DwarfDebug &DD) {
2338   MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start");
2339   MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end");
2340   emitListsTableHeaderStart(Asm, TableStart, TableEnd);
2341 
2342   const auto &DebugLocs = DD.getDebugLocs();
2343 
2344   Asm->OutStreamer->AddComment("Offset entry count");
2345   Asm->emitInt32(DebugLocs.getLists().size());
2346   Asm->OutStreamer->EmitLabel(DebugLocs.getSym());
2347 
2348   for (const auto &List : DebugLocs.getLists())
2349     Asm->EmitLabelDifference(List.Label, DebugLocs.getSym(), 4);
2350 
2351   return TableEnd;
2352 }
2353 
2354 template <typename Ranges, typename PayloadEmitter>
2355 static void emitRangeList(
2356     DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
2357     const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
2358     unsigned StartxLength, unsigned EndOfList,
2359     StringRef (*StringifyEnum)(unsigned),
2360     bool ShouldUseBaseAddress,
2361     PayloadEmitter EmitPayload) {
2362 
2363   auto Size = Asm->MAI->getCodePointerSize();
2364   bool UseDwarf5 = DD.getDwarfVersion() >= 5;
2365 
2366   // Emit our symbol so we can find the beginning of the range.
2367   Asm->OutStreamer->EmitLabel(Sym);
2368 
2369   // Gather all the ranges that apply to the same section so they can share
2370   // a base address entry.
2371   MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
2372 
2373   for (const auto &Range : R)
2374     SectionRanges[&Range.Begin->getSection()].push_back(&Range);
2375 
2376   const MCSymbol *CUBase = CU.getBaseAddress();
2377   bool BaseIsSet = false;
2378   for (const auto &P : SectionRanges) {
2379     auto *Base = CUBase;
2380     if (!Base && ShouldUseBaseAddress) {
2381       const MCSymbol *Begin = P.second.front()->Begin;
2382       const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
2383       if (!UseDwarf5) {
2384         Base = NewBase;
2385         BaseIsSet = true;
2386         Asm->OutStreamer->EmitIntValue(-1, Size);
2387         Asm->OutStreamer->AddComment("  base address");
2388         Asm->OutStreamer->EmitSymbolValue(Base, Size);
2389       } else if (NewBase != Begin || P.second.size() > 1) {
2390         // Only use a base address if
2391         //  * the existing pool address doesn't match (NewBase != Begin)
2392         //  * or, there's more than one entry to share the base address
2393         Base = NewBase;
2394         BaseIsSet = true;
2395         Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
2396         Asm->emitInt8(BaseAddressx);
2397         Asm->OutStreamer->AddComment("  base address index");
2398         Asm->EmitULEB128(DD.getAddressPool().getIndex(Base));
2399       }
2400     } else if (BaseIsSet && !UseDwarf5) {
2401       BaseIsSet = false;
2402       assert(!Base);
2403       Asm->OutStreamer->EmitIntValue(-1, Size);
2404       Asm->OutStreamer->EmitIntValue(0, Size);
2405     }
2406 
2407     for (const auto *RS : P.second) {
2408       const MCSymbol *Begin = RS->Begin;
2409       const MCSymbol *End = RS->End;
2410       assert(Begin && "Range without a begin symbol?");
2411       assert(End && "Range without an end symbol?");
2412       if (Base) {
2413         if (UseDwarf5) {
2414           // Emit offset_pair when we have a base.
2415           Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
2416           Asm->emitInt8(OffsetPair);
2417           Asm->OutStreamer->AddComment("  starting offset");
2418           Asm->EmitLabelDifferenceAsULEB128(Begin, Base);
2419           Asm->OutStreamer->AddComment("  ending offset");
2420           Asm->EmitLabelDifferenceAsULEB128(End, Base);
2421         } else {
2422           Asm->EmitLabelDifference(Begin, Base, Size);
2423           Asm->EmitLabelDifference(End, Base, Size);
2424         }
2425       } else if (UseDwarf5) {
2426         Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
2427         Asm->emitInt8(StartxLength);
2428         Asm->OutStreamer->AddComment("  start index");
2429         Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin));
2430         Asm->OutStreamer->AddComment("  length");
2431         Asm->EmitLabelDifferenceAsULEB128(End, Begin);
2432       } else {
2433         Asm->OutStreamer->EmitSymbolValue(Begin, Size);
2434         Asm->OutStreamer->EmitSymbolValue(End, Size);
2435       }
2436       EmitPayload(*RS);
2437     }
2438   }
2439 
2440   if (UseDwarf5) {
2441     Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
2442     Asm->emitInt8(EndOfList);
2443   } else {
2444     // Terminate the list with two 0 values.
2445     Asm->OutStreamer->EmitIntValue(0, Size);
2446     Asm->OutStreamer->EmitIntValue(0, Size);
2447   }
2448 }
2449 
2450 // Handles emission of both debug_loclist / debug_loclist.dwo
2451 static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
2452   emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2453                 *List.CU, dwarf::DW_LLE_base_addressx,
2454                 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2455                 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
2456                 /* ShouldUseBaseAddress */ true,
2457                 [&](const DebugLocStream::Entry &E) {
2458                   DD.emitDebugLocEntryLocation(E, List.CU);
2459                 });
2460 }
2461 
2462 // Emit locations into the .debug_loc/.debug_loclists section.
2463 void DwarfDebug::emitDebugLoc() {
2464   if (DebugLocs.getLists().empty())
2465     return;
2466 
2467   MCSymbol *TableEnd = nullptr;
2468   if (getDwarfVersion() >= 5) {
2469 
2470     Asm->OutStreamer->SwitchSection(
2471         Asm->getObjFileLowering().getDwarfLoclistsSection());
2472 
2473     TableEnd = emitLoclistsTableHeader(Asm, *this);
2474   } else {
2475     Asm->OutStreamer->SwitchSection(
2476         Asm->getObjFileLowering().getDwarfLocSection());
2477   }
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.dwo/.debug_loclists.dwo section.
2487 void DwarfDebug::emitDebugLocDWO() {
2488   if (DebugLocs.getLists().empty())
2489     return;
2490 
2491   if (getDwarfVersion() >= 5) {
2492     MCSymbol *TableEnd = nullptr;
2493     Asm->OutStreamer->SwitchSection(
2494         Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
2495     TableEnd = emitLoclistsTableHeader(Asm, *this);
2496     for (const auto &List : DebugLocs.getLists())
2497       emitLocList(*this, Asm, List);
2498 
2499     if (TableEnd)
2500       Asm->OutStreamer->EmitLabel(TableEnd);
2501     return;
2502   }
2503 
2504   for (const auto &List : DebugLocs.getLists()) {
2505     Asm->OutStreamer->SwitchSection(
2506         Asm->getObjFileLowering().getDwarfLocDWOSection());
2507     Asm->OutStreamer->EmitLabel(List.Label);
2508 
2509     for (const auto &Entry : DebugLocs.getEntries(List)) {
2510       // GDB only supports startx_length in pre-standard split-DWARF.
2511       // (in v5 standard loclists, it currently* /only/ supports base_address +
2512       // offset_pair, so the implementations can't really share much since they
2513       // need to use different representations)
2514       // * as of October 2018, at least
2515       // Ideally/in v5, this could use SectionLabels to reuse existing addresses
2516       // in the address pool to minimize object size/relocations.
2517       Asm->emitInt8(dwarf::DW_LLE_startx_length);
2518       unsigned idx = AddrPool.getIndex(Entry.Begin);
2519       Asm->EmitULEB128(idx);
2520       Asm->EmitLabelDifference(Entry.End, Entry.Begin, 4);
2521       emitDebugLocEntryLocation(Entry, List.CU);
2522     }
2523     Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2524   }
2525 }
2526 
2527 struct ArangeSpan {
2528   const MCSymbol *Start, *End;
2529 };
2530 
2531 // Emit a debug aranges section, containing a CU lookup for any
2532 // address we can tie back to a CU.
2533 void DwarfDebug::emitDebugARanges() {
2534   // Provides a unique id per text section.
2535   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2536 
2537   // Filter labels by section.
2538   for (const SymbolCU &SCU : ArangeLabels) {
2539     if (SCU.Sym->isInSection()) {
2540       // Make a note of this symbol and it's section.
2541       MCSection *Section = &SCU.Sym->getSection();
2542       if (!Section->getKind().isMetadata())
2543         SectionMap[Section].push_back(SCU);
2544     } else {
2545       // Some symbols (e.g. common/bss on mach-o) can have no section but still
2546       // appear in the output. This sucks as we rely on sections to build
2547       // arange spans. We can do it without, but it's icky.
2548       SectionMap[nullptr].push_back(SCU);
2549     }
2550   }
2551 
2552   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2553 
2554   for (auto &I : SectionMap) {
2555     MCSection *Section = I.first;
2556     SmallVector<SymbolCU, 8> &List = I.second;
2557     if (List.size() < 1)
2558       continue;
2559 
2560     // If we have no section (e.g. common), just write out
2561     // individual spans for each symbol.
2562     if (!Section) {
2563       for (const SymbolCU &Cur : List) {
2564         ArangeSpan Span;
2565         Span.Start = Cur.Sym;
2566         Span.End = nullptr;
2567         assert(Cur.CU);
2568         Spans[Cur.CU].push_back(Span);
2569       }
2570       continue;
2571     }
2572 
2573     // Sort the symbols by offset within the section.
2574     llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
2575       unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
2576       unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
2577 
2578       // Symbols with no order assigned should be placed at the end.
2579       // (e.g. section end labels)
2580       if (IA == 0)
2581         return false;
2582       if (IB == 0)
2583         return true;
2584       return IA < IB;
2585     });
2586 
2587     // Insert a final terminator.
2588     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2589 
2590     // Build spans between each label.
2591     const MCSymbol *StartSym = List[0].Sym;
2592     for (size_t n = 1, e = List.size(); n < e; n++) {
2593       const SymbolCU &Prev = List[n - 1];
2594       const SymbolCU &Cur = List[n];
2595 
2596       // Try and build the longest span we can within the same CU.
2597       if (Cur.CU != Prev.CU) {
2598         ArangeSpan Span;
2599         Span.Start = StartSym;
2600         Span.End = Cur.Sym;
2601         assert(Prev.CU);
2602         Spans[Prev.CU].push_back(Span);
2603         StartSym = Cur.Sym;
2604       }
2605     }
2606   }
2607 
2608   // Start the dwarf aranges section.
2609   Asm->OutStreamer->SwitchSection(
2610       Asm->getObjFileLowering().getDwarfARangesSection());
2611 
2612   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2613 
2614   // Build a list of CUs used.
2615   std::vector<DwarfCompileUnit *> CUs;
2616   for (const auto &it : Spans) {
2617     DwarfCompileUnit *CU = it.first;
2618     CUs.push_back(CU);
2619   }
2620 
2621   // Sort the CU list (again, to ensure consistent output order).
2622   llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2623     return A->getUniqueID() < B->getUniqueID();
2624   });
2625 
2626   // Emit an arange table for each CU we used.
2627   for (DwarfCompileUnit *CU : CUs) {
2628     std::vector<ArangeSpan> &List = Spans[CU];
2629 
2630     // Describe the skeleton CU's offset and length, not the dwo file's.
2631     if (auto *Skel = CU->getSkeleton())
2632       CU = Skel;
2633 
2634     // Emit size of content not including length itself.
2635     unsigned ContentSize =
2636         sizeof(int16_t) + // DWARF ARange version number
2637         sizeof(int32_t) + // Offset of CU in the .debug_info section
2638         sizeof(int8_t) +  // Pointer Size (in bytes)
2639         sizeof(int8_t);   // Segment Size (in bytes)
2640 
2641     unsigned TupleSize = PtrSize * 2;
2642 
2643     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2644     unsigned Padding =
2645         offsetToAlignment(sizeof(int32_t) + ContentSize, Align(TupleSize));
2646 
2647     ContentSize += Padding;
2648     ContentSize += (List.size() + 1) * TupleSize;
2649 
2650     // For each compile unit, write the list of spans it covers.
2651     Asm->OutStreamer->AddComment("Length of ARange Set");
2652     Asm->emitInt32(ContentSize);
2653     Asm->OutStreamer->AddComment("DWARF Arange version number");
2654     Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
2655     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
2656     emitSectionReference(*CU);
2657     Asm->OutStreamer->AddComment("Address Size (in bytes)");
2658     Asm->emitInt8(PtrSize);
2659     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
2660     Asm->emitInt8(0);
2661 
2662     Asm->OutStreamer->emitFill(Padding, 0xff);
2663 
2664     for (const ArangeSpan &Span : List) {
2665       Asm->EmitLabelReference(Span.Start, PtrSize);
2666 
2667       // Calculate the size as being from the span start to it's end.
2668       if (Span.End) {
2669         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2670       } else {
2671         // For symbols without an end marker (e.g. common), we
2672         // write a single arange entry containing just that one symbol.
2673         uint64_t Size = SymSize[Span.Start];
2674         if (Size == 0)
2675           Size = 1;
2676 
2677         Asm->OutStreamer->EmitIntValue(Size, PtrSize);
2678       }
2679     }
2680 
2681     Asm->OutStreamer->AddComment("ARange terminator");
2682     Asm->OutStreamer->EmitIntValue(0, PtrSize);
2683     Asm->OutStreamer->EmitIntValue(0, PtrSize);
2684   }
2685 }
2686 
2687 /// Emit a single range list. We handle both DWARF v5 and earlier.
2688 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
2689                           const RangeSpanList &List) {
2690   emitRangeList(DD, Asm, List.getSym(), List.getRanges(), List.getCU(),
2691                 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
2692                 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
2693                 llvm::dwarf::RangeListEncodingString,
2694                 List.getCU().getCUNode()->getRangesBaseAddress() ||
2695                     DD.getDwarfVersion() >= 5,
2696                 [](auto) {});
2697 }
2698 
2699 void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
2700   if (Holder.getRangeLists().empty())
2701     return;
2702 
2703   assert(useRangesSection());
2704   assert(!CUMap.empty());
2705   assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2706     return !Pair.second->getCUNode()->isDebugDirectivesOnly();
2707   }));
2708 
2709   Asm->OutStreamer->SwitchSection(Section);
2710 
2711   MCSymbol *TableEnd =
2712       getDwarfVersion() < 5 ? nullptr : emitRnglistsTableHeader(Asm, Holder);
2713 
2714   for (const RangeSpanList &List : Holder.getRangeLists())
2715     emitRangeList(*this, Asm, List);
2716 
2717   if (TableEnd)
2718     Asm->OutStreamer->EmitLabel(TableEnd);
2719 }
2720 
2721 /// Emit address ranges into the .debug_ranges section or into the DWARF v5
2722 /// .debug_rnglists section.
2723 void DwarfDebug::emitDebugRanges() {
2724   const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2725 
2726   emitDebugRangesImpl(Holder,
2727                       getDwarfVersion() >= 5
2728                           ? Asm->getObjFileLowering().getDwarfRnglistsSection()
2729                           : Asm->getObjFileLowering().getDwarfRangesSection());
2730 }
2731 
2732 void DwarfDebug::emitDebugRangesDWO() {
2733   emitDebugRangesImpl(InfoHolder,
2734                       Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
2735 }
2736 
2737 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
2738   for (auto *MN : Nodes) {
2739     if (auto *M = dyn_cast<DIMacro>(MN))
2740       emitMacro(*M);
2741     else if (auto *F = dyn_cast<DIMacroFile>(MN))
2742       emitMacroFile(*F, U);
2743     else
2744       llvm_unreachable("Unexpected DI type!");
2745   }
2746 }
2747 
2748 void DwarfDebug::emitMacro(DIMacro &M) {
2749   Asm->EmitULEB128(M.getMacinfoType());
2750   Asm->EmitULEB128(M.getLine());
2751   StringRef Name = M.getName();
2752   StringRef Value = M.getValue();
2753   Asm->OutStreamer->EmitBytes(Name);
2754   if (!Value.empty()) {
2755     // There should be one space between macro name and macro value.
2756     Asm->emitInt8(' ');
2757     Asm->OutStreamer->EmitBytes(Value);
2758   }
2759   Asm->emitInt8('\0');
2760 }
2761 
2762 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
2763   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
2764   Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
2765   Asm->EmitULEB128(F.getLine());
2766   Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
2767   handleMacroNodes(F.getElements(), U);
2768   Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
2769 }
2770 
2771 /// Emit macros into a debug macinfo section.
2772 void DwarfDebug::emitDebugMacinfo() {
2773   for (const auto &P : CUMap) {
2774     auto &TheCU = *P.second;
2775     auto *SkCU = TheCU.getSkeleton();
2776     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2777     auto *CUNode = cast<DICompileUnit>(P.first);
2778     DIMacroNodeArray Macros = CUNode->getMacros();
2779     if (Macros.empty())
2780       continue;
2781     Asm->OutStreamer->SwitchSection(
2782         Asm->getObjFileLowering().getDwarfMacinfoSection());
2783     Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2784     handleMacroNodes(Macros, U);
2785     Asm->OutStreamer->AddComment("End Of Macro List Mark");
2786     Asm->emitInt8(0);
2787   }
2788 }
2789 
2790 void DwarfDebug::emitDebugMacinfoDWO() {
2791   for (const auto &P : CUMap) {
2792     auto &TheCU = *P.second;
2793     auto *SkCU = TheCU.getSkeleton();
2794     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2795     auto *CUNode = cast<DICompileUnit>(P.first);
2796     DIMacroNodeArray Macros = CUNode->getMacros();
2797     if (Macros.empty())
2798       continue;
2799     Asm->OutStreamer->SwitchSection(
2800         Asm->getObjFileLowering().getDwarfMacinfoDWOSection());
2801     Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2802     handleMacroNodes(Macros, U);
2803     Asm->OutStreamer->AddComment("End Of Macro List Mark");
2804     Asm->emitInt8(0);
2805   }
2806 }
2807 
2808 // DWARF5 Experimental Separate Dwarf emitters.
2809 
2810 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2811                                   std::unique_ptr<DwarfCompileUnit> NewU) {
2812 
2813   if (!CompilationDir.empty())
2814     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2815 
2816   addGnuPubAttributes(*NewU, Die);
2817 
2818   SkeletonHolder.addUnit(std::move(NewU));
2819 }
2820 
2821 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2822 
2823   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
2824       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
2825       UnitKind::Skeleton);
2826   DwarfCompileUnit &NewCU = *OwnedUnit;
2827   NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2828 
2829   NewCU.initStmtList();
2830 
2831   if (useSegmentedStringOffsetsTable())
2832     NewCU.addStringOffsetsStart();
2833 
2834   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2835 
2836   return NewCU;
2837 }
2838 
2839 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2840 // compile units that would normally be in debug_info.
2841 void DwarfDebug::emitDebugInfoDWO() {
2842   assert(useSplitDwarf() && "No split dwarf debug info?");
2843   // Don't emit relocations into the dwo file.
2844   InfoHolder.emitUnits(/* UseOffsets */ true);
2845 }
2846 
2847 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2848 // abbreviations for the .debug_info.dwo section.
2849 void DwarfDebug::emitDebugAbbrevDWO() {
2850   assert(useSplitDwarf() && "No split dwarf?");
2851   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2852 }
2853 
2854 void DwarfDebug::emitDebugLineDWO() {
2855   assert(useSplitDwarf() && "No split dwarf?");
2856   SplitTypeUnitFileTable.Emit(
2857       *Asm->OutStreamer, MCDwarfLineTableParams(),
2858       Asm->getObjFileLowering().getDwarfLineDWOSection());
2859 }
2860 
2861 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2862   assert(useSplitDwarf() && "No split dwarf?");
2863   InfoHolder.getStringPool().emitStringOffsetsTableHeader(
2864       *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
2865       InfoHolder.getStringOffsetsStartSym());
2866 }
2867 
2868 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2869 // string section and is identical in format to traditional .debug_str
2870 // sections.
2871 void DwarfDebug::emitDebugStrDWO() {
2872   if (useSegmentedStringOffsetsTable())
2873     emitStringOffsetsTableHeaderDWO();
2874   assert(useSplitDwarf() && "No split dwarf?");
2875   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2876   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2877                          OffSec, /* UseRelativeOffsets = */ false);
2878 }
2879 
2880 // Emit address pool.
2881 void DwarfDebug::emitDebugAddr() {
2882   AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
2883 }
2884 
2885 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2886   if (!useSplitDwarf())
2887     return nullptr;
2888   const DICompileUnit *DIUnit = CU.getCUNode();
2889   SplitTypeUnitFileTable.maybeSetRootFile(
2890       DIUnit->getDirectory(), DIUnit->getFilename(),
2891       CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
2892   return &SplitTypeUnitFileTable;
2893 }
2894 
2895 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2896   MD5 Hash;
2897   Hash.update(Identifier);
2898   // ... take the least significant 8 bytes and return those. Our MD5
2899   // implementation always returns its results in little endian, so we actually
2900   // need the "high" word.
2901   MD5::MD5Result Result;
2902   Hash.final(Result);
2903   return Result.high();
2904 }
2905 
2906 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2907                                       StringRef Identifier, DIE &RefDie,
2908                                       const DICompositeType *CTy) {
2909   // Fast path if we're building some type units and one has already used the
2910   // address pool we know we're going to throw away all this work anyway, so
2911   // don't bother building dependent types.
2912   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2913     return;
2914 
2915   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2916   if (!Ins.second) {
2917     CU.addDIETypeSignature(RefDie, Ins.first->second);
2918     return;
2919   }
2920 
2921   bool TopLevelType = TypeUnitsUnderConstruction.empty();
2922   AddrPool.resetUsedFlag();
2923 
2924   auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2925                                                     getDwoLineTable(CU));
2926   DwarfTypeUnit &NewTU = *OwnedUnit;
2927   DIE &UnitDie = NewTU.getUnitDie();
2928   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
2929 
2930   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2931                 CU.getLanguage());
2932 
2933   uint64_t Signature = makeTypeSignature(Identifier);
2934   NewTU.setTypeSignature(Signature);
2935   Ins.first->second = Signature;
2936 
2937   if (useSplitDwarf()) {
2938     MCSection *Section =
2939         getDwarfVersion() <= 4
2940             ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
2941             : Asm->getObjFileLowering().getDwarfInfoDWOSection();
2942     NewTU.setSection(Section);
2943   } else {
2944     MCSection *Section =
2945         getDwarfVersion() <= 4
2946             ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
2947             : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
2948     NewTU.setSection(Section);
2949     // Non-split type units reuse the compile unit's line table.
2950     CU.applyStmtList(UnitDie);
2951   }
2952 
2953   // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2954   // units.
2955   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
2956     NewTU.addStringOffsetsStart();
2957 
2958   NewTU.setType(NewTU.createTypeDIE(CTy));
2959 
2960   if (TopLevelType) {
2961     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2962     TypeUnitsUnderConstruction.clear();
2963 
2964     // Types referencing entries in the address table cannot be placed in type
2965     // units.
2966     if (AddrPool.hasBeenUsed()) {
2967 
2968       // Remove all the types built while building this type.
2969       // This is pessimistic as some of these types might not be dependent on
2970       // the type that used an address.
2971       for (const auto &TU : TypeUnitsToAdd)
2972         TypeSignatures.erase(TU.second);
2973 
2974       // Construct this type in the CU directly.
2975       // This is inefficient because all the dependent types will be rebuilt
2976       // from scratch, including building them in type units, discovering that
2977       // they depend on addresses, throwing them out and rebuilding them.
2978       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2979       return;
2980     }
2981 
2982     // If the type wasn't dependent on fission addresses, finish adding the type
2983     // and all its dependent types.
2984     for (auto &TU : TypeUnitsToAdd) {
2985       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2986       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2987     }
2988   }
2989   CU.addDIETypeSignature(RefDie, Signature);
2990 }
2991 
2992 DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD)
2993     : DD(DD),
2994       TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)) {
2995   DD->TypeUnitsUnderConstruction.clear();
2996   assert(TypeUnitsUnderConstruction.empty() || !DD->AddrPool.hasBeenUsed());
2997 }
2998 
2999 DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() {
3000   DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction);
3001   DD->AddrPool.resetUsedFlag();
3002 }
3003 
3004 DwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() {
3005   return NonTypeUnitContext(this);
3006 }
3007 
3008 // Add the Name along with its companion DIE to the appropriate accelerator
3009 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3010 // AccelTableKind::Apple, we use the table we got as an argument). If
3011 // accelerator tables are disabled, this function does nothing.
3012 template <typename DataT>
3013 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
3014                                   AccelTable<DataT> &AppleAccel, StringRef Name,
3015                                   const DIE &Die) {
3016   if (getAccelTableKind() == AccelTableKind::None)
3017     return;
3018 
3019   if (getAccelTableKind() != AccelTableKind::Apple &&
3020       CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
3021     return;
3022 
3023   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3024   DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
3025 
3026   switch (getAccelTableKind()) {
3027   case AccelTableKind::Apple:
3028     AppleAccel.addName(Ref, Die);
3029     break;
3030   case AccelTableKind::Dwarf:
3031     AccelDebugNames.addName(Ref, Die);
3032     break;
3033   case AccelTableKind::Default:
3034     llvm_unreachable("Default should have already been resolved.");
3035   case AccelTableKind::None:
3036     llvm_unreachable("None handled above");
3037   }
3038 }
3039 
3040 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
3041                               const DIE &Die) {
3042   addAccelNameImpl(CU, AccelNames, Name, Die);
3043 }
3044 
3045 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
3046                               const DIE &Die) {
3047   // ObjC names go only into the Apple accelerator tables.
3048   if (getAccelTableKind() == AccelTableKind::Apple)
3049     addAccelNameImpl(CU, AccelObjC, Name, Die);
3050 }
3051 
3052 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
3053                                    const DIE &Die) {
3054   addAccelNameImpl(CU, AccelNamespace, Name, Die);
3055 }
3056 
3057 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
3058                               const DIE &Die, char Flags) {
3059   addAccelNameImpl(CU, AccelTypes, Name, Die);
3060 }
3061 
3062 uint16_t DwarfDebug::getDwarfVersion() const {
3063   return Asm->OutStreamer->getContext().getDwarfVersion();
3064 }
3065 
3066 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
3067   return SectionLabels.find(S)->second;
3068 }
3069