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