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