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