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