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