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