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