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