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