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