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