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