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