LLVM 23.0.0git
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 "DwarfCompileUnit.h"
17#include "DwarfExpression.h"
18#include "DwarfUnit.h"
19#include "llvm/ADT/APInt.h"
20#include "llvm/ADT/Statistic.h"
22#include "llvm/ADT/Twine.h"
24#include "llvm/CodeGen/DIE.h"
36#include "llvm/IR/Constants.h"
38#include "llvm/IR/Function.h"
40#include "llvm/IR/Module.h"
41#include "llvm/MC/MCAsmInfo.h"
42#include "llvm/MC/MCContext.h"
43#include "llvm/MC/MCSection.h"
44#include "llvm/MC/MCStreamer.h"
45#include "llvm/MC/MCSymbol.h"
50#include "llvm/Support/Debug.h"
52#include "llvm/Support/MD5.h"
57#include <cstddef>
58#include <iterator>
59#include <optional>
60#include <string>
61
62using namespace llvm;
63
64#define DEBUG_TYPE "dwarfdebug"
65
66STATISTIC(NumCSParams, "Number of dbg call site params created");
67
69 "use-dwarf-ranges-base-address-specifier", cl::Hidden,
70 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
71
72static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::desc("Generate dwarf aranges"),
75 cl::init(false));
76
77static cl::opt<bool>
78 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
79 cl::desc("Generate DWARF4 type units."),
80 cl::init(false));
81
83 "split-dwarf-cross-cu-references", cl::Hidden,
84 cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
85
87
89 "use-unknown-locations", cl::Hidden,
90 cl::desc("Make an absence of debug location information explicit."),
91 cl::values(clEnumVal(Default, "At top of block or after label"),
92 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
94
96 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
98 "Default for platform"),
99 clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
100 clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
101 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
103
105DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
106 cl::desc("Use inlined strings rather than string section."),
107 cl::values(clEnumVal(Default, "Default for platform"),
108 clEnumVal(Enable, "Enabled"),
109 clEnumVal(Disable, "Disabled")),
111
112static cl::opt<bool>
113 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
114 cl::desc("Disable emission .debug_ranges section."),
115 cl::init(false));
116
118 "dwarf-sections-as-references", cl::Hidden,
119 cl::desc("Use sections+offset as references rather than labels."),
120 cl::values(clEnumVal(Default, "Default for platform"),
121 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
123
124static cl::opt<bool>
125 UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden,
126 cl::desc("Emit the GNU .debug_macro format with DWARF <5"),
127 cl::init(false));
128
130 "dwarf-op-convert", cl::Hidden,
131 cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"),
132 cl::values(clEnumVal(Default, "Default for platform"),
133 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
135
141
143 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
144 cl::desc("Which DWARF linkage-name attributes to emit."),
146 "Default for platform"),
147 clEnumValN(AllLinkageNames, "All", "All"),
149 "Abstract subprograms")),
151
153 "minimize-addr-in-v5", cl::Hidden,
154 cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more "
155 "address pool entry sharing to reduce relocations/object size"),
157 "Default address minimization strategy"),
159 "Use rnglists for contiguous ranges if that allows "
160 "using a pre-existing base address"),
162 "Expressions",
163 "Use exprloc addrx+offset expressions for any "
164 "address with a prior base address"),
166 "Use addrx+offset extension form for any address "
167 "with a prior base address"),
169 "Stuff")),
171
172/// Set to false to ignore Key Instructions metadata.
174 "dwarf-use-key-instructions", cl::Hidden, cl::init(true),
175 cl::desc("Set to false to ignore Key Instructions metadata"));
176
177static constexpr unsigned ULEB128PadSize = 4;
178
179void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
180 getActiveStreamer().emitInt8(
181 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
183}
184
185void DebugLocDwarfExpression::emitSigned(int64_t Value) {
186 getActiveStreamer().emitSLEB128(Value, Twine(Value));
187}
188
189void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
190 getActiveStreamer().emitULEB128(Value, Twine(Value));
191}
192
193void DebugLocDwarfExpression::emitData1(uint8_t Value) {
194 getActiveStreamer().emitInt8(Value, Twine(Value));
195}
196
197void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
198 assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
199 getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
200}
201
202bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
203 llvm::Register MachineReg) {
204 // This information is not available while emitting .debug_loc entries.
205 return false;
206}
207
209 assert(!IsBuffering && "Already buffering?");
210 if (!TmpBuf)
211 TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
212 IsBuffering = true;
213}
214
215void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
216
218 return TmpBuf ? TmpBuf->Bytes.size() : 0;
219}
220
222 if (!TmpBuf)
223 return;
224 for (auto Byte : enumerate(TmpBuf->Bytes)) {
225 const char *Comment = (Byte.index() < TmpBuf->Comments.size())
226 ? TmpBuf->Comments[Byte.index()].c_str()
227 : "";
228 OutBS.emitInt8(Byte.value(), Comment);
229 }
230 TmpBuf->Bytes.clear();
231 TmpBuf->Comments.clear();
232}
233
235 return getVariable()->getType();
236}
237
238/// Get .debug_loc entry for the instruction range starting at MI.
240 const DIExpression *Expr = MI->getDebugExpression();
241 auto SingleLocExprOpt = DIExpression::convertToNonVariadicExpression(Expr);
242 const bool IsVariadic = !SingleLocExprOpt;
243 // If we have a variadic debug value instruction that is equivalent to a
244 // non-variadic instruction, then convert it to non-variadic form here.
245 if (!IsVariadic && !MI->isNonListDebugValue()) {
246 assert(MI->getNumDebugOperands() == 1 &&
247 "Mismatched DIExpression and debug operands for debug instruction.");
248 Expr = *SingleLocExprOpt;
249 }
250 assert(MI->getNumOperands() >= 3);
251 SmallVector<DbgValueLocEntry, 4> DbgValueLocEntries;
252 for (const MachineOperand &Op : MI->debug_operands()) {
253 if (Op.isReg()) {
254 MachineLocation MLoc(Op.getReg(),
255 MI->isNonListDebugValue() && MI->isDebugOffsetImm());
256 DbgValueLocEntries.push_back(DbgValueLocEntry(MLoc));
257 } else if (Op.isTargetIndex()) {
258 DbgValueLocEntries.push_back(
259 DbgValueLocEntry(TargetIndexLocation(Op.getIndex(), Op.getOffset())));
260 } else if (Op.isImm())
261 DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getImm()));
262 else if (Op.isFPImm())
263 DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getFPImm()));
264 else if (Op.isCImm())
265 DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getCImm()));
266 else
267 llvm_unreachable("Unexpected debug operand in DBG_VALUE* instruction!");
268 }
269 return DbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);
270}
271
273 std::optional<DIExpression::FragmentInfo> Fragment = Expr.getFragmentInfo();
274 return Fragment ? Fragment->OffsetInBits : 0;
275}
276
278 return getFragmentOffsetInBits(*LHS.Expr) <
280}
281
284}
285
287 : ValueLoc(std::make_unique<DbgValueLoc>(ValueLoc)),
288 Expr(ValueLoc.getExpression()) {
289 if (!Expr->getNumElements())
290 Expr = nullptr;
291}
292
295
296const std::set<FrameIndexExpr> &Loc::MMI::getFrameIndexExprs() const {
297 return FrameIndexExprs;
298}
299
300void Loc::MMI::addFrameIndexExpr(const DIExpression *Expr, int FI) {
301 FrameIndexExprs.insert({FI, Expr});
302 assert((FrameIndexExprs.size() == 1 ||
304 [](const FrameIndexExpr &FIE) {
305 return FIE.Expr && FIE.Expr->isFragment();
306 })) &&
307 "conflicting locations for variable");
308}
309
310static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
311 bool GenerateTypeUnits,
312 DebuggerKind Tuning,
313 const Triple &TT) {
314 // Honor an explicit request.
316 return AccelTables;
317
318 // Generating DWARF5 acceleration table.
319 // Currently Split dwarf and non ELF format is not supported.
320 if (GenerateTypeUnits && (DwarfVersion < 5 || !TT.isOSBinFormatELF()))
322
323 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
324 // always implies debug_names. For lower standard versions we use apple
325 // accelerator tables on apple platforms and debug_names elsewhere.
326 if (DwarfVersion >= 5)
328 if (Tuning == DebuggerKind::LLDB)
329 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
332}
333
335 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
336 SkeletonHolder(A, "skel_string", DIEValueAllocator),
337 IsDarwin(A->TM.getTargetTriple().isOSDarwin()),
338 InfoHolder(A, "info_string", DIEValueAllocator) {
339 const Triple &TT = Asm->TM.getTargetTriple();
340
341 // Make sure we know our "debugger tuning". The target option takes
342 // precedence; fall back to triple-based defaults.
343 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
344 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
345 else if (IsDarwin)
346 DebuggerTuning = DebuggerKind::LLDB;
347 else if (TT.isPS())
348 DebuggerTuning = DebuggerKind::SCE;
349 else if (TT.isOSAIX())
350 DebuggerTuning = DebuggerKind::DBX;
351 else
352 DebuggerTuning = DebuggerKind::GDB;
353
355 UseInlineStrings = tuneForDBX();
356 else
357 UseInlineStrings = DwarfInlinedStrings == Enable;
358
359 // Always emit .debug_aranges for SCE tuning.
360 UseARangesSection = GenerateARangeSection || tuneForSCE();
361
362 HasAppleExtensionAttributes = tuneForLLDB();
363
364 // Handle split DWARF.
365 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
366
367 // SCE defaults to linkage names only for abstract subprograms.
369 UseAllLinkageNames = !tuneForSCE();
370 else
371 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
372
373 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
374 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
375 : MMI->getModule()->getDwarfVersion();
376 if (!DwarfVersion)
377 DwarfVersion = dwarf::DWARF_VERSION;
378
379 bool Dwarf64 = DwarfVersion >= 3 && // DWARF64 was introduced in DWARFv3.
380 TT.isArch64Bit(); // DWARF64 requires 64-bit relocations.
381
382 // Support DWARF64
383 // 1: For ELF when requested.
384 // 2: For XCOFF64: the AIX assembler will fill in debug section lengths
385 // according to the DWARF64 format for 64-bit assembly, so we must use
386 // DWARF64 in the compiler too for 64-bit mode.
387 Dwarf64 &=
388 ((Asm->TM.Options.MCOptions.Dwarf64 || MMI->getModule()->isDwarf64()) &&
389 TT.isOSBinFormatELF()) ||
390 TT.isOSBinFormatXCOFF();
391
392 if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())
393 report_fatal_error("XCOFF requires DWARF64 for 64-bit mode!");
394
395 UseRangesSection = !NoDwarfRangesSection;
396
398 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
399
400 // Don't generate type units for unsupported object file formats.
401 GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() ||
402 A->TM.getTargetTriple().isOSBinFormatWasm()) &&
404
405 TheAccelTableKind = computeAccelTableKind(
406 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
407
408 // Work around a GDB bug. GDB doesn't support the standard opcode;
409 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
410 // is defined as of DWARF 3.
411 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
412 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
413 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
414
415 UseDWARF2Bitfields = DwarfVersion < 4;
416
417 // The DWARF v5 string offsets table has - possibly shared - contributions
418 // from each compile and type unit each preceded by a header. The string
419 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
420 // a monolithic string offsets table without any header.
421 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
422
423 // Emit call-site-param debug info for GDB and LLDB, if the target supports
424 // the debug entry values feature. It can also be enabled explicitly.
425 EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();
426
427 // It is unclear if the GCC .debug_macro extension is well-specified
428 // for split DWARF. For now, do not allow LLVM to emit it.
429 UseDebugMacroSection =
430 DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());
431 if (DwarfOpConvert == Default)
432 EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO()));
433 else
434 EnableOpConvert = (DwarfOpConvert == Enable);
435
436 // Split DWARF would benefit object size significantly by trading reductions
437 // in address pool usage for slightly increased range list encodings.
438 if (DwarfVersion >= 5)
439 MinimizeAddr = MinimizeAddrInV5Option;
440
441 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
442 Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64
444}
445
446// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
447DwarfDebug::~DwarfDebug() = default;
448
449static bool isObjCClass(StringRef Name) {
450 return Name.starts_with("+") || Name.starts_with("-");
451}
452
453static bool hasObjCCategory(StringRef Name) {
454 if (!isObjCClass(Name))
455 return false;
456
457 return Name.contains(") ");
458}
459
461 StringRef &Category) {
462 if (!hasObjCCategory(In)) {
463 Class = In.slice(In.find('[') + 1, In.find(' '));
464 Category = "";
465 return;
466 }
467
468 Class = In.slice(In.find('[') + 1, In.find('('));
469 Category = In.slice(In.find('[') + 1, In.find(' '));
470}
471
473 return In.slice(In.find(' ') + 1, In.find(']'));
474}
475
476// Add the various names to the Dwarf accelerator table names.
478 const DwarfUnit &Unit,
479 const DICompileUnit::DebugNameTableKind NameTableKind,
480 const DISubprogram *SP, DIE &Die) {
484 return;
485
486 if (!SP->isDefinition())
487 return;
488
489 if (SP->getName() != "")
490 addAccelName(Unit, NameTableKind, SP->getName(), Die);
491
492 // We drop the mangling escape prefix when emitting the DW_AT_linkage_name. So
493 // ensure we don't include it when inserting into the accelerator tables.
495 GlobalValue::dropLLVMManglingEscape(SP->getLinkageName());
496
497 // If the linkage name is different than the name, go ahead and output that as
498 // well into the name table. Only do that if we are going to actually emit
499 // that name.
500 if (LinkageName != "" && SP->getName() != LinkageName &&
501 (useAllLinkageNames() || InfoHolder.getAbstractScopeDIEs().lookup(SP)))
502 addAccelName(Unit, NameTableKind, LinkageName, Die);
503
504 // If this is an Objective-C selector name add it to the ObjC accelerator
505 // too.
506 if (isObjCClass(SP->getName())) {
507 StringRef Class, Category;
508 getObjCClassCategory(SP->getName(), Class, Category);
509 addAccelObjC(Unit, NameTableKind, Class, Die);
510 if (Category != "")
511 addAccelObjC(Unit, NameTableKind, Category, Die);
512 // Also add the base method name to the name table.
513 addAccelName(Unit, NameTableKind, getObjCMethodName(SP->getName()), Die);
514 }
515}
516
517/// Check whether we should create a DIE for the given Scope, return true
518/// if we don't create a DIE (the corresponding DIE is null).
520 if (Scope->isAbstractScope())
521 return false;
522
523 // We don't create a DIE if there is no Range.
524 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
525 if (Ranges.empty())
526 return true;
527
528 if (Ranges.size() > 1)
529 return false;
530
531 // We don't create a DIE if we have a single Range and the end label
532 // is null.
533 return !getLabelAfterInsn(Ranges.front().second);
534}
535
536template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
537 F(CU);
538 if (auto *SkelCU = CU.getSkeleton())
539 if (CU.getCUNode()->getSplitDebugInlining())
540 F(*SkelCU);
541}
542
546
549 DwarfCompileUnit &SrcCU) {
550 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
551 if (CU.getSkeleton())
552 return shareAcrossDWOCUs() ? CU : SrcCU;
553
554 return CU;
555}
556
557void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
558 LexicalScope *Scope) {
559 assert(Scope && Scope->getScopeNode());
560 assert(Scope->isAbstractScope());
561 assert(!Scope->getInlinedAt());
562
563 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
564
565 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
566 // was inlined from another compile unit.
567 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
568 auto &TargetCU = getOrCreateAbstractSubprogramCU(SP, SrcCU);
569 TargetCU.constructAbstractSubprogramScopeDIE(Scope);
570 if (auto *SkelCU = CU.getSkeleton())
571 if (CU.getCUNode()->getSplitDebugInlining())
572 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
573}
574
575/// Represents a parameter whose call site value can be described by applying a
576/// debug expression to a register in the forwarded register worklist.
578 /// The described parameter register.
580
581 /// Debug expression that has been built up when walking through the
582 /// instruction chain that produces the parameter's value.
584};
585
586/// Register worklist for finding call site values.
588/// Container for the set of register units known to be clobbered on the path
589/// to a call site.
591
592/// Append the expression \p Addition to \p Original and return the result.
593static const DIExpression *combineDIExpressions(const DIExpression *Original,
594 const DIExpression *Addition) {
595 std::vector<uint64_t> Elts = Addition->getElements().vec();
596 // Avoid multiple DW_OP_stack_values.
597 if (Original->isImplicit() && Addition->isImplicit())
598 llvm::erase(Elts, dwarf::DW_OP_stack_value);
599 const DIExpression *CombinedExpr =
600 (Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;
601 return CombinedExpr;
602}
603
604/// Emit call site parameter entries that are described by the given value and
605/// debug expression.
606template <typename ValT>
607static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
608 ArrayRef<FwdRegParamInfo> DescribedParams,
609 ParamSet &Params) {
610 for (auto Param : DescribedParams) {
611 bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
612
613 // If a parameter's call site value is produced by a chain of
614 // instructions we may have already created an expression for the
615 // parameter when walking through the instructions. Append that to the
616 // base expression.
617 const DIExpression *CombinedExpr =
618 ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)
619 : Expr;
620 assert((!CombinedExpr || CombinedExpr->isValid()) &&
621 "Combined debug expression is invalid");
622
623 DbgValueLoc DbgLocVal(CombinedExpr, DbgValueLocEntry(Val));
624 DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
625 Params.push_back(CSParm);
626 ++NumCSParams;
627 }
628}
629
630/// Add \p Reg to the worklist, if it's not already present, and mark that the
631/// given parameter registers' values can (potentially) be described using
632/// that register and an debug expression.
633static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
634 const DIExpression *Expr,
635 ArrayRef<FwdRegParamInfo> ParamsToAdd) {
636 auto &ParamsForFwdReg = Worklist[Reg];
637 for (auto Param : ParamsToAdd) {
638 assert(none_of(ParamsForFwdReg,
639 [Param](const FwdRegParamInfo &D) {
640 return D.ParamReg == Param.ParamReg;
641 }) &&
642 "Same parameter described twice by forwarding reg");
643
644 // If a parameter's call site value is produced by a chain of
645 // instructions we may have already created an expression for the
646 // parameter when walking through the instructions. Append that to the
647 // new expression.
648 const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);
649 ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
650 }
651}
652
653/// Interpret values loaded into registers by \p CurMI.
654static void interpretValues(const MachineInstr *CurMI,
655 FwdRegWorklist &ForwardedRegWorklist,
656 ParamSet &Params,
657 ClobberedRegUnitSet &ClobberedRegUnits) {
658
659 const MachineFunction *MF = CurMI->getMF();
660 const DIExpression *EmptyExpr =
662 const auto &TRI = *MF->getSubtarget().getRegisterInfo();
663 const auto &TII = *MF->getSubtarget().getInstrInfo();
664 const auto &TLI = *MF->getSubtarget().getTargetLowering();
665
666 // It's possible that we find a copy from a non-volatile register to the param
667 // register, which is clobbered in the meantime. Test for clobbered reg unit
668 // overlaps before completing.
669 auto IsRegClobberedInMeantime = [&](Register Reg) -> bool {
670 for (auto &RegUnit : ClobberedRegUnits)
671 if (TRI.hasRegUnit(Reg, RegUnit))
672 return true;
673 return false;
674 };
675
676 auto DescribeFwdRegsByCalleeSavedCopy = [&](const DestSourcePair &CopyInst) {
677 Register CopyDestReg = CopyInst.Destination->getReg();
678 Register CopySrcReg = CopyInst.Source->getReg();
679 if (IsRegClobberedInMeantime(CopyDestReg))
680 return;
681 // FIXME: This may be incorrect in cases where the caller and callee use
682 // different calling conventions.
683 if (!TRI.isCalleeSavedPhysReg(CopyDestReg, *MF))
684 return;
685 // Describe any forward registers matching the source register. If the
686 // forward register is a sub-register of the source, we describe it using
687 // the corresponding sub-register in the destination, if such a
688 // sub-register exists. The end iterator in the MapVector is invalidated at
689 // erase(), so it needs to be evaluated at each iteration.
690 for (auto FwdRegIt = ForwardedRegWorklist.begin();
691 FwdRegIt != ForwardedRegWorklist.end();) {
693 if (FwdRegIt->first == CopySrcReg)
694 CalleeSavedReg = CopyDestReg;
695 else if (unsigned SubRegIdx =
696 TRI.getSubRegIndex(CopySrcReg, FwdRegIt->first))
697 if (Register CopyDestSubReg = TRI.getSubReg(CopyDestReg, SubRegIdx))
698 CalleeSavedReg = CopyDestSubReg;
699
701 ++FwdRegIt;
702 continue;
703 }
704
705 MachineLocation MLoc(CalleeSavedReg, /*Indirect=*/false);
706 finishCallSiteParams(MLoc, EmptyExpr, FwdRegIt->second, Params);
707 FwdRegIt = ForwardedRegWorklist.erase(FwdRegIt);
708 }
709 };
710
711 // Detect if this is a copy instruction. If this saves any of the forward
712 // registers in callee-saved registers, we can finalize those parameters
713 // directly.
714 // TODO: Can we do something similar for stack saves?
715 if (auto CopyInst = TII.isCopyInstr(*CurMI))
716 DescribeFwdRegsByCalleeSavedCopy(*CopyInst);
717
718 // If an instruction defines more than one item in the worklist, we may run
719 // into situations where a worklist register's value is (potentially)
720 // described by the previous value of another register that is also defined
721 // by that instruction.
722 //
723 // This can for example occur in cases like this:
724 //
725 // $r1 = mov 123
726 // $r0, $r1 = mvrr $r1, 456
727 // call @foo, $r0, $r1
728 //
729 // When describing $r1's value for the mvrr instruction, we need to make sure
730 // that we don't finalize an entry value for $r0, as that is dependent on the
731 // previous value of $r1 (123 rather than 456).
732 //
733 // In order to not have to distinguish between those cases when finalizing
734 // entry values, we simply postpone adding new parameter registers to the
735 // worklist, by first keeping them in this temporary container until the
736 // instruction has been handled.
737 FwdRegWorklist TmpWorklistItems;
738
739 // If the MI is an instruction defining one or more parameters' forwarding
740 // registers, add those defines.
741 ClobberedRegUnitSet NewClobberedRegUnits;
742 auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
744 if (MI.isDebugInstr())
745 return;
746
747 for (const MachineOperand &MO : MI.all_defs()) {
748 if (MO.getReg().isPhysical()) {
749 for (auto &FwdReg : ForwardedRegWorklist)
750 if (TRI.regsOverlap(FwdReg.first, MO.getReg()))
751 Defs.insert(FwdReg.first);
752 NewClobberedRegUnits.insert_range(TRI.regunits(MO.getReg()));
753 }
754 }
755 };
756
757 // Set of worklist registers that are defined by this instruction.
759
760 getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
761 if (FwdRegDefs.empty()) {
762 // Any definitions by this instruction will clobber earlier reg movements.
763 ClobberedRegUnits.insert_range(NewClobberedRegUnits);
764 return;
765 }
766
767 for (auto ParamFwdReg : FwdRegDefs) {
768 if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
769 if (ParamValue->first.isImm()) {
770 int64_t Val = ParamValue->first.getImm();
771 finishCallSiteParams(Val, ParamValue->second,
772 ForwardedRegWorklist[ParamFwdReg], Params);
773 } else if (ParamValue->first.isReg()) {
774 Register RegLoc = ParamValue->first.getReg();
775 Register SP = TLI.getStackPointerRegisterToSaveRestore();
776 Register FP = TRI.getFrameRegister(*MF);
777 bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
778 // FIXME: This may be incorrect in cases where the caller and callee use
779 // different calling conventions.
780 if (!IsRegClobberedInMeantime(RegLoc) &&
781 (TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP)) {
782 MachineLocation MLoc(RegLoc, /*Indirect=*/IsSPorFP);
783 finishCallSiteParams(MLoc, ParamValue->second,
784 ForwardedRegWorklist[ParamFwdReg], Params);
785 } else {
786 // ParamFwdReg was described by the non-callee saved register
787 // RegLoc. Mark that the call site values for the parameters are
788 // dependent on that register instead of ParamFwdReg. Since RegLoc
789 // may be a register that will be handled in this iteration, we
790 // postpone adding the items to the worklist, and instead keep them
791 // in a temporary container.
792 addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second,
793 ForwardedRegWorklist[ParamFwdReg]);
794 }
795 }
796 }
797 }
798
799 // Remove all registers that this instruction defines from the worklist.
800 for (auto ParamFwdReg : FwdRegDefs)
801 ForwardedRegWorklist.erase(ParamFwdReg);
802
803 // Any definitions by this instruction will clobber earlier reg movements.
804 ClobberedRegUnits.insert_range(NewClobberedRegUnits);
805
806 // Now that we are done handling this instruction, add items from the
807 // temporary worklist to the real one.
808 for (auto &New : TmpWorklistItems)
809 addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second);
810 TmpWorklistItems.clear();
811}
812
813static bool interpretNextInstr(const MachineInstr *CurMI,
814 FwdRegWorklist &ForwardedRegWorklist,
815 ParamSet &Params,
816 ClobberedRegUnitSet &ClobberedRegUnits) {
817 // Skip bundle headers.
818 if (CurMI->isBundle())
819 return true;
820
821 // If the next instruction is a call we can not interpret parameter's
822 // forwarding registers or we finished the interpretation of all
823 // parameters.
824 if (CurMI->isCall())
825 return false;
826
827 if (ForwardedRegWorklist.empty())
828 return false;
829
830 // Avoid NOP description.
831 if (CurMI->getNumOperands() == 0)
832 return true;
833
834 interpretValues(CurMI, ForwardedRegWorklist, Params, ClobberedRegUnits);
835
836 return true;
837}
838
839/// Try to interpret values loaded into registers that forward parameters
840/// for \p CallMI. Store parameters with interpreted value into \p Params.
841static void collectCallSiteParameters(const MachineInstr *CallMI,
842 ParamSet &Params) {
843 const MachineFunction *MF = CallMI->getMF();
844 const auto &CalleesMap = MF->getCallSitesInfo();
845 auto CSInfo = CalleesMap.find(CallMI);
846
847 // There is no information for the call instruction.
848 if (CSInfo == CalleesMap.end())
849 return;
850
851 const MachineBasicBlock *MBB = CallMI->getParent();
852
853 // Skip the call instruction.
854 auto I = std::next(CallMI->getReverseIterator());
855
856 FwdRegWorklist ForwardedRegWorklist;
857
858 const DIExpression *EmptyExpr =
860
861 // Add all the forwarding registers into the ForwardedRegWorklist.
862 for (const auto &ArgReg : CSInfo->second.ArgRegPairs) {
863 bool InsertedReg =
864 ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
865 .second;
866 assert(InsertedReg && "Single register used to forward two arguments?");
867 (void)InsertedReg;
868 }
869
870 // Do not emit CSInfo for undef forwarding registers.
871 for (const auto &MO : CallMI->uses())
872 if (MO.isReg() && MO.isUndef())
873 ForwardedRegWorklist.erase(MO.getReg());
874
875 // We erase, from the ForwardedRegWorklist, those forwarding registers for
876 // which we successfully describe a loaded value (by using
877 // the describeLoadedValue()). For those remaining arguments in the working
878 // list, for which we do not describe a loaded value by
879 // the describeLoadedValue(), we try to generate an entry value expression
880 // for their call site value description, if the call is within the entry MBB.
881 // TODO: Handle situations when call site parameter value can be described
882 // as the entry value within basic blocks other than the first one.
883 bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
884
885 // Search for a loading value in forwarding registers inside call delay slot.
886 ClobberedRegUnitSet ClobberedRegUnits;
887 if (CallMI->hasDelaySlot()) {
888 auto Suc = std::next(CallMI->getIterator());
889 // Only one-instruction delay slot is supported.
890 auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator());
891 (void)BundleEnd;
892 assert(std::next(Suc) == BundleEnd &&
893 "More than one instruction in call delay slot");
894 // Try to interpret value loaded by instruction.
895 if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params, ClobberedRegUnits))
896 return;
897 }
898
899 // Search for a loading value in forwarding registers.
900 for (; I != MBB->rend(); ++I) {
901 // Try to interpret values loaded by instruction.
902 if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params, ClobberedRegUnits))
903 return;
904 }
905
906 // Emit the call site parameter's value as an entry value.
907 if (ShouldTryEmitEntryVals) {
908 // Create an expression where the register's entry value is used.
909 DIExpression *EntryExpr = DIExpression::get(
910 MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
911 for (auto &RegEntry : ForwardedRegWorklist) {
912 MachineLocation MLoc(RegEntry.first);
913 finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
914 }
915 }
916}
917
918void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
919 DwarfCompileUnit &CU, DIE &ScopeDIE,
920 const MachineFunction &MF) {
921 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
922 // the subprogram is required to have one.
923 if (!SP.areAllCallsDescribed() || !SP.isDefinition())
924 return;
925
926 // Use DW_AT_call_all_calls to express that call site entries are present
927 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
928 // because one of its requirements is not met: call site entries for
929 // optimized-out calls are elided.
930 CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
931
932 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
933 assert(TII && "TargetInstrInfo not found: cannot label tail calls");
934
935 // Delay slot support check.
936 auto delaySlotSupported = [&](const MachineInstr &MI) {
937 if (!MI.isBundledWithSucc())
938 return false;
939 auto Suc = std::next(MI.getIterator());
940 auto CallInstrBundle = getBundleStart(MI.getIterator());
941 (void)CallInstrBundle;
942 auto DelaySlotBundle = getBundleStart(Suc);
943 (void)DelaySlotBundle;
944 // Ensure that label after call is following delay slot instruction.
945 // Ex. CALL_INSTRUCTION {
946 // DELAY_SLOT_INSTRUCTION }
947 // LABEL_AFTER_CALL
948 assert(getLabelAfterInsn(&*CallInstrBundle) ==
949 getLabelAfterInsn(&*DelaySlotBundle) &&
950 "Call and its successor instruction don't have same label after.");
951 return true;
952 };
953
954 // Create call_target connections for indirect calls.
955 auto addCallSiteTargetForIndirectCalls = [&](const MachineInstr *MI,
956 DIE &CallSiteDIE) {
957 const MachineFunction *MF = MI->getMF();
958 const auto &CalleesMap = MF->getCallSitesInfo();
959 auto CSInfo = CalleesMap.find(MI);
960 // Get the information for the call instruction.
961 if (CSInfo == CalleesMap.end() || !CSInfo->second.CallTarget)
962 return;
963
964 MDNode *CallTarget = CSInfo->second.CallTarget;
965 // Add DW_AT_LLVM_virtual_call_origin with the 'call_target' metadata.
966 assert(!CallSiteDIE.findAttribute(dwarf::DW_AT_LLVM_virtual_call_origin) &&
967 "DW_AT_LLVM_virtual_call_origin already exists");
968 const DISubprogram *CalleeSP = dyn_cast<DISubprogram>(CallTarget);
969 DIE *CalleeDIE = CU.getOrCreateSubprogramDIE(CalleeSP, nullptr);
970 assert(CalleeDIE && "Could not create DIE for call site entry origin");
971 CU.addDIEEntry(CallSiteDIE,
972 CU.getDwarf5OrGNUAttr(dwarf::DW_AT_LLVM_virtual_call_origin),
973 *CalleeDIE);
974 // Add DW_AT_linkage_name to the method declaration if needed.
975 CU.addLinkageNamesToDeclarations(*this, *CalleeSP, *CalleeDIE);
976 };
977
978 // Emit call site entries for each call or tail call in the function.
979 for (const MachineBasicBlock &MBB : MF) {
980 for (const MachineInstr &MI : MBB.instrs()) {
981 // Bundles with call in them will pass the isCall() test below but do not
982 // have callee operand information so skip them here. Iterator will
983 // eventually reach the call MI.
984 if (MI.isBundle())
985 continue;
986
987 // Skip instructions which aren't calls. Both calls and tail-calling jump
988 // instructions (e.g TAILJMPd64) are classified correctly here.
989 if (!MI.isCandidateForAdditionalCallInfo())
990 continue;
991
992 // Skip instructions marked as frame setup, as they are not interesting to
993 // the user.
994 if (MI.getFlag(MachineInstr::FrameSetup))
995 continue;
996
997 // Check if delay slot support is enabled.
998 if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))
999 return;
1000
1001 DIType *AllocSiteTy = dyn_cast_or_null<DIType>(MI.getHeapAllocMarker());
1002
1003 // If this is a direct call, find the callee's subprogram.
1004 // In the case of an indirect call find the register or memory location
1005 // that holds the callee address.
1006 const MachineOperand &CalleeOp = TII->getCalleeOperand(MI);
1007 bool PhysRegCalleeOperand =
1008 CalleeOp.isReg() && CalleeOp.getReg().isPhysical();
1009 MachineLocation CallTarget{0};
1010 int64_t Offset = 0;
1011 const DISubprogram *CalleeSP = nullptr;
1012 const Function *CalleeDecl = nullptr;
1013 if (PhysRegCalleeOperand) {
1014 bool Scalable = false;
1015 const MachineOperand *BaseOp = nullptr;
1016 const TargetRegisterInfo &TRI =
1017 *Asm->MF->getSubtarget().getRegisterInfo();
1018 if (TII->getMemOperandWithOffset(MI, BaseOp, Offset, Scalable, &TRI)) {
1019 if (BaseOp && BaseOp->isReg() && !Scalable)
1020 CallTarget = MachineLocation(BaseOp->getReg(), /*Indirect*/ true);
1021 }
1022
1023 if (!CallTarget.isIndirect())
1024 CallTarget = MachineLocation(CalleeOp.getReg()); // Might be zero.
1025 } else if (CalleeOp.isGlobal()) {
1026 CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
1027 if (CalleeDecl)
1028 CalleeSP = CalleeDecl->getSubprogram(); // might be nullptr
1029 }
1030
1031 // Omit DIE if we can't tell where the call goes *and* we don't want to
1032 // add metadata to it.
1033 if (CalleeSP == nullptr && CallTarget.getReg() == 0 &&
1034 AllocSiteTy == nullptr)
1035 continue;
1036
1037 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
1038
1039 bool IsTail = TII->isTailCall(MI);
1040
1041 // If MI is in a bundle, the label was created after the bundle since
1042 // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
1043 // to search for that label below.
1044 const MachineInstr *TopLevelCallMI =
1045 MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
1046
1047 // For non-tail calls, the return PC is needed to disambiguate paths in
1048 // the call graph which could lead to some target function. For tail
1049 // calls, no return PC information is needed, unless tuning for GDB in
1050 // DWARF4 mode in which case we fake a return PC for compatibility.
1051 const MCSymbol *PCAddr = (!IsTail || CU.useGNUAnalogForDwarf5Feature())
1052 ? getLabelAfterInsn(TopLevelCallMI)
1053 : nullptr;
1054
1055 // For tail calls, it's necessary to record the address of the branch
1056 // instruction so that the debugger can show where the tail call occurred.
1057 const MCSymbol *CallAddr =
1058 IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr;
1059
1060 assert((IsTail || PCAddr) && "Non-tail call without return PC");
1061
1062 LLVM_DEBUG(
1063 dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
1064 << (CalleeDecl
1065 ? CalleeDecl->getName()
1066 : StringRef(
1067 MF.getSubtarget().getRegisterInfo()->getName(
1068 CallTarget.getReg())))
1069 << (IsTail ? " [IsTail]" : "") << "\n");
1070
1071 DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(
1072 ScopeDIE, CalleeSP, CalleeDecl, IsTail, PCAddr, CallAddr, CallTarget,
1073 Offset, AllocSiteTy);
1074
1075 if (CallTarget.getReg())
1076 addCallSiteTargetForIndirectCalls(TopLevelCallMI, CallSiteDIE);
1077
1078 // Optionally emit call-site-param debug info.
1079 if (emitDebugEntryValues()) {
1080 ParamSet Params;
1081 // Try to interpret values of call site parameters.
1082 collectCallSiteParameters(&MI, Params);
1083 CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
1084 }
1085 }
1086 }
1087}
1088
1089void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
1090 if (!U.hasDwarfPubSections())
1091 return;
1092
1093 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
1094}
1095
1096void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
1097 DwarfCompileUnit &NewCU) {
1098 DIE &Die = NewCU.getUnitDie();
1099 StringRef FN = DIUnit->getFilename();
1100
1101 StringRef Producer = DIUnit->getProducer();
1102 StringRef Flags = DIUnit->getFlags();
1103 if (!Flags.empty() && !useAppleExtensionAttributes()) {
1104 std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
1105 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
1106 } else
1107 NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
1108
1109 if (auto Lang = DIUnit->getSourceLanguage(); Lang.hasVersionedName()) {
1110 NewCU.addUInt(Die, dwarf::DW_AT_language_name, dwarf::DW_FORM_data2,
1111 Lang.getName());
1112
1113 if (uint32_t LangVersion = Lang.getVersion(); LangVersion != 0)
1114 NewCU.addUInt(Die, dwarf::DW_AT_language_version, /*Form=*/std::nullopt,
1115 LangVersion);
1116 } else {
1117 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1118 Lang.getName());
1119 }
1120
1121 NewCU.addString(Die, dwarf::DW_AT_name, FN);
1122
1123 finishTargetUnitAttributes(*DIUnit, NewCU);
1124
1125 StringRef SysRoot = DIUnit->getSysRoot();
1126 if (!SysRoot.empty())
1127 NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
1128 StringRef SDK = DIUnit->getSDK();
1129 if (!SDK.empty())
1130 NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
1131
1132 if (!useSplitDwarf()) {
1133 // Add DW_str_offsets_base to the unit DIE, except for split units.
1135 NewCU.addStringOffsetsStart();
1136
1137 NewCU.initStmtList();
1138
1139 // If we're using split dwarf the compilation dir is going to be in the
1140 // skeleton CU and so we don't need to duplicate it here.
1141 if (!CompilationDir.empty())
1142 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1143 addGnuPubAttributes(NewCU, Die);
1144 }
1145
1147 if (DIUnit->isOptimized())
1148 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
1149
1150 StringRef Flags = DIUnit->getFlags();
1151 if (!Flags.empty())
1152 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
1153
1154 if (unsigned RVer = DIUnit->getRuntimeVersion())
1155 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1156 dwarf::DW_FORM_data1, RVer);
1157 }
1158
1159 if (DIUnit->getDWOId()) {
1160 // This CU is either a clang module DWO or a skeleton CU.
1161 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
1162 DIUnit->getDWOId());
1163 if (!DIUnit->getSplitDebugFilename().empty()) {
1164 // This is a prefabricated skeleton CU.
1165 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1166 ? dwarf::DW_AT_dwo_name
1167 : dwarf::DW_AT_GNU_dwo_name;
1168 NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
1169 }
1170 }
1171}
1172
1173DwarfCompileUnit *DwarfDebug::getDwarfCompileUnit(const DICompileUnit *DIUnit) {
1174 if (auto *CU = CUMap.lookup(DIUnit))
1175 return CU;
1176
1177 if (useSplitDwarf() && !shareAcrossDWOCUs() &&
1178 (!DIUnit->getSplitDebugInlining() ||
1180 !CUMap.empty())
1181 return CUMap.begin()->second;
1182
1183 return nullptr;
1184}
1185
1186// Create new DwarfCompileUnit for the given metadata node with tag
1187// DW_TAG_compile_unit.
1189DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
1190 if (auto *CU = getDwarfCompileUnit(DIUnit))
1191 return *CU;
1192
1193 CompilationDir = DIUnit->getDirectory();
1194
1195 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
1196 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
1197 DwarfCompileUnit &NewCU = *OwnedUnit;
1198 InfoHolder.addUnit(std::move(OwnedUnit));
1199
1200 // LTO with assembly output shares a single line table amongst multiple CUs.
1201 // To avoid the compilation directory being ambiguous, let the line table
1202 // explicitly describe the directory of all files, never relying on the
1203 // compilation directory.
1204 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
1205 Asm->OutStreamer->emitDwarfFile0Directive(
1206 CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()),
1207 DIUnit->getSource(), NewCU.getUniqueID());
1208
1209 if (useSplitDwarf()) {
1210 NewCU.setSkeleton(constructSkeletonCU(NewCU));
1211 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
1212 } else {
1213 finishUnitAttributes(DIUnit, NewCU);
1214 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
1215 }
1216
1217 CUMap.insert({DIUnit, &NewCU});
1218 CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
1219 return NewCU;
1220}
1221
1222/// Sort and unique GVEs by comparing their fragment offset.
1225 llvm::sort(
1227 // Sort order: first null exprs, then exprs without fragment
1228 // info, then sort by fragment offset in bits.
1229 // FIXME: Come up with a more comprehensive comparator so
1230 // the sorting isn't non-deterministic, and so the following
1231 // std::unique call works correctly.
1232 if (!A.Expr || !B.Expr)
1233 return !!B.Expr;
1234 auto FragmentA = A.Expr->getFragmentInfo();
1235 auto FragmentB = B.Expr->getFragmentInfo();
1236 if (!FragmentA || !FragmentB)
1237 return !!FragmentB;
1238 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
1239 });
1240 GVEs.erase(llvm::unique(GVEs,
1243 return A.Expr == B.Expr;
1244 }),
1245 GVEs.end());
1246 return GVEs;
1247}
1248
1249// Emit all Dwarf sections that should come prior to the content. Create
1250// global DIEs and emit initial debug info sections. This is invoked by
1251// the target AsmPrinter.
1254
1255 if (!Asm)
1256 return;
1257
1258 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
1259 M->debug_compile_units_end());
1260 if (NumDebugCUs == 0)
1261 return;
1262
1263 assert(NumDebugCUs > 0 && "Asm unexpectedly initialized");
1264 SingleCU = NumDebugCUs == 1;
1265
1266 // Create the symbol that designates the start of the unit's contribution
1267 // to the string offsets table. In a split DWARF scenario, only the skeleton
1268 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
1270 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
1271 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
1272
1273
1274 // Create the symbols that designates the start of the DWARF v5 range list
1275 // and locations list tables. They are located past the table headers.
1276 if (getDwarfVersion() >= 5) {
1277 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1279 Asm->createTempSymbol("rnglists_table_base"));
1280
1281 if (useSplitDwarf())
1282 InfoHolder.setRnglistsTableBaseSym(
1283 Asm->createTempSymbol("rnglists_dwo_table_base"));
1284 }
1285
1286 // Create the symbol that points to the first entry following the debug
1287 // address table (.debug_addr) header.
1288 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1289 DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1290
1291 for (DICompileUnit *CUNode : M->debug_compile_units()) {
1292 if (CUNode->getImportedEntities().empty() &&
1293 CUNode->getEnumTypes().empty() && CUNode->getRetainedTypes().empty() &&
1294 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1295 continue;
1296
1297 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1298
1299 for (auto *Ty : CUNode->getEnumTypes()) {
1300 assert(!isa_and_nonnull<DILocalScope>(Ty->getScope()) &&
1301 "Unexpected function-local entity in 'enums' CU field.");
1302 CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1303 }
1304
1305 for (auto *Ty : CUNode->getRetainedTypes()) {
1306 if (DIType *RT = dyn_cast<DIType>(Ty))
1307 // There is no point in force-emitting a forward declaration.
1308 CU.getOrCreateTypeDIE(RT);
1309 }
1310 }
1311}
1312
1313void DwarfDebug::finishEntityDefinitions() {
1314 for (const auto &Entity : ConcreteEntities) {
1315 DIE *Die = Entity->getDIE();
1316 assert(Die);
1317 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1318 // in the ConcreteEntities list, rather than looking it up again here.
1319 // DIE::getUnit isn't simple - it walks parent pointers, etc.
1320 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
1321 assert(Unit);
1322 Unit->finishEntityDefinition(Entity.get());
1323 }
1324}
1325
1326void DwarfDebug::finishSubprogramDefinitions() {
1327 for (const DISubprogram *SP : ProcessedSPNodes) {
1328 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1329 forBothCUs(
1330 getOrCreateDwarfCompileUnit(SP->getUnit()),
1331 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1332 }
1333}
1334
1335void DwarfDebug::finalizeModuleInfo() {
1336 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1337
1338 finishSubprogramDefinitions();
1339
1340 finishEntityDefinitions();
1341
1342 bool HasEmittedSplitCU = false;
1343
1344 // Handle anything that needs to be done on a per-unit basis after
1345 // all other generation.
1346 for (const auto &P : CUMap) {
1347 auto &TheCU = *P.second;
1348 if (TheCU.getCUNode()->isDebugDirectivesOnly())
1349 continue;
1350 TheCU.attachLexicalScopesAbstractOrigins();
1351 // Emit DW_AT_containing_type attribute to connect types with their
1352 // vtable holding type.
1353 TheCU.constructContainingTypeDIEs();
1354
1355 // Add CU specific attributes if we need to add any.
1356 // If we're splitting the dwarf out now that we've got the entire
1357 // CU then add the dwo id to it.
1358 auto *SkCU = TheCU.getSkeleton();
1359
1360 bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1361
1362 if (HasSplitUnit) {
1363 (void)HasEmittedSplitCU;
1364 assert((shareAcrossDWOCUs() || !HasEmittedSplitCU) &&
1365 "Multiple CUs emitted into a single dwo file");
1366 HasEmittedSplitCU = true;
1367 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1368 ? dwarf::DW_AT_dwo_name
1369 : dwarf::DW_AT_GNU_dwo_name;
1370 finishUnitAttributes(TheCU.getCUNode(), TheCU);
1371 StringRef DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
1372 TheCU.addString(TheCU.getUnitDie(), attrDWOName, DWOName);
1373 SkCU->addString(SkCU->getUnitDie(), attrDWOName, DWOName);
1374 // Emit a unique identifier for this CU. Include the DWO file name in the
1375 // hash to avoid the case where two (almost) empty compile units have the
1376 // same contents. This can happen if link-time optimization removes nearly
1377 // all (unused) code from a CU.
1378 uint64_t ID =
1379 DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());
1380 if (getDwarfVersion() >= 5) {
1381 TheCU.setDWOId(ID);
1382 SkCU->setDWOId(ID);
1383 } else {
1384 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1385 dwarf::DW_FORM_data8, ID);
1386 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1387 dwarf::DW_FORM_data8, ID);
1388 }
1389
1390 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1391 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
1392 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1393 Sym, Sym);
1394 }
1395 } else if (SkCU) {
1396 finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1397 }
1398
1399 // If we have code split among multiple sections or non-contiguous
1400 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1401 // remain in the .o file, otherwise add a DW_AT_low_pc.
1402 // FIXME: We should use ranges allow reordering of code ala
1403 // .subsections_via_symbols in mach-o. This would mean turning on
1404 // ranges for all subprogram DIEs for mach-o.
1405 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1406
1407 if (unsigned NumRanges = TheCU.getRanges().size()) {
1409 if (NumRanges > 1 && useRangesSection())
1410 // A DW_AT_low_pc attribute may also be specified in combination with
1411 // DW_AT_ranges to specify the default base address for use in
1412 // location lists (see Section 2.6.2) and range lists (see Section
1413 // 2.17.3).
1414 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1415 0);
1416 else
1417 U.setBaseAddress(TheCU.getRanges().front().Begin);
1418 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1419 }
1420 }
1421
1422 // We don't keep track of which addresses are used in which CU so this
1423 // is a bit pessimistic under LTO.
1424 if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
1425 U.addAddrTableBase();
1426
1427 if (getDwarfVersion() >= 5) {
1428 if (U.hasRangeLists())
1429 U.addRnglistsBase();
1430
1431 if (!DebugLocs.getLists().empty() && !useSplitDwarf()) {
1432 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
1433 DebugLocs.getSym(),
1435 }
1436 }
1437
1438 auto *CUNode = cast<DICompileUnit>(P.first);
1439 // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
1440 // attribute.
1441 if (CUNode->getMacros()) {
1442 if (UseDebugMacroSection) {
1443 if (useSplitDwarf())
1444 TheCU.addSectionDelta(
1445 TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
1447 else {
1448 dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5
1449 ? dwarf::DW_AT_macros
1450 : dwarf::DW_AT_GNU_macros;
1451 U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),
1453 }
1454 } else {
1455 if (useSplitDwarf())
1456 TheCU.addSectionDelta(
1457 TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1458 U.getMacroLabelBegin(),
1460 else
1461 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
1462 U.getMacroLabelBegin(),
1464 }
1465 }
1466 }
1467
1468 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1469 for (auto *CUNode : MMI->getModule()->debug_compile_units())
1470 if (CUNode->getDWOId())
1471 getOrCreateDwarfCompileUnit(CUNode);
1472
1473 // Compute DIE offsets and sizes.
1474 InfoHolder.computeSizeAndOffsets();
1475 if (useSplitDwarf())
1476 SkeletonHolder.computeSizeAndOffsets();
1477
1478 // Now that offsets are computed, can replace DIEs in debug_names Entry with
1479 // an actual offset.
1480 AccelDebugNames.convertDieToOffset();
1481}
1482
1483// Emit all Dwarf sections that should come after the content.
1485 // Terminate the pending line table.
1486 if (PrevCU)
1487 terminateLineTable(PrevCU);
1488 PrevCU = nullptr;
1489 assert(CurFn == nullptr);
1490 assert(CurMI == nullptr);
1491
1492 const Module *M = MMI->getModule();
1493
1494 // Collect global variables info.
1496 GVMap;
1497 for (const GlobalVariable &Global : M->globals()) {
1499 Global.getDebugInfo(GVs);
1500 for (auto *GVE : GVs)
1501 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
1502 }
1503
1504 for (DICompileUnit *CUNode : M->debug_compile_units()) {
1505 DwarfCompileUnit *CU = getDwarfCompileUnit(CUNode);
1506
1507 // If the CU hasn't been emitted yet, it must be empty. Skip it.
1508 if (!CU)
1509 continue;
1510
1511 // Emit Global Variables.
1512 for (auto *GVE : CUNode->getGlobalVariables()) {
1513 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1514 // already know about the variable and it isn't adding a constant
1515 // expression.
1516 auto &GVMapEntry = GVMap[GVE->getVariable()];
1517 auto *Expr = GVE->getExpression();
1518 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1519 GVMapEntry.push_back({nullptr, Expr});
1520 }
1522 for (auto *GVE : CUNode->getGlobalVariables()) {
1523 DIGlobalVariable *GV = GVE->getVariable();
1524 if (Processed.insert(GV).second)
1525 CU->getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1526 }
1527
1528 // Emit imported entities.
1529 for (auto *IE : CUNode->getImportedEntities()) {
1530 assert(!isa_and_nonnull<DILocalScope>(IE->getScope()) &&
1531 "Unexpected function-local entity in 'imports' CU field.");
1532 CU->getOrCreateImportedEntityDIE(IE);
1533 }
1534
1535 // Emit function-local entities.
1536 for (const auto *D : CU->getDeferredLocalDecls()) {
1537 if (auto *IE = dyn_cast<DIImportedEntity>(D))
1538 CU->getOrCreateImportedEntityDIE(IE);
1539 else if (auto *Ty = dyn_cast<DIType>(D))
1540 CU->getOrCreateTypeDIE(Ty);
1541 else
1542 llvm_unreachable("Unexpected local retained node!");
1543 }
1544
1545 // Emit base types.
1546 CU->createBaseTypeDIEs();
1547 }
1548
1549 // If we aren't actually generating debug info (check beginModule -
1550 // conditionalized on the presence of the llvm.dbg.cu metadata node)
1551 if (!Asm || !Asm->hasDebugInfo())
1552 return;
1553
1554 // Finalize the debug info for the module.
1555 finalizeModuleInfo();
1556
1557 if (useSplitDwarf())
1558 // Emit debug_loc.dwo/debug_loclists.dwo section.
1559 emitDebugLocDWO();
1560 else
1561 // Emit debug_loc/debug_loclists section.
1562 emitDebugLoc();
1563
1564 // Corresponding abbreviations into a abbrev section.
1565 emitAbbreviations();
1566
1567 // Emit all the DIEs into a debug info section.
1568 emitDebugInfo();
1569
1570 // Emit info into a debug aranges section.
1571 if (UseARangesSection)
1572 emitDebugARanges();
1573
1574 // Emit info into a debug ranges section.
1575 emitDebugRanges();
1576
1577 if (useSplitDwarf())
1578 // Emit info into a debug macinfo.dwo section.
1579 emitDebugMacinfoDWO();
1580 else
1581 // Emit info into a debug macinfo/macro section.
1582 emitDebugMacinfo();
1583
1584 emitDebugStr();
1585
1586 if (useSplitDwarf()) {
1587 emitDebugStrDWO();
1588 emitDebugInfoDWO();
1589 emitDebugAbbrevDWO();
1590 emitDebugLineDWO();
1591 emitDebugRangesDWO();
1592 }
1593
1594 emitDebugAddr();
1595
1596 // Emit info into the dwarf accelerator table sections.
1597 switch (getAccelTableKind()) {
1599 emitAccelNames();
1600 emitAccelObjC();
1601 emitAccelNamespaces();
1602 emitAccelTypes();
1603 break;
1605 emitAccelDebugNames();
1606 break;
1608 break;
1610 llvm_unreachable("Default should have already been resolved.");
1611 }
1612
1613 // Emit the pubnames and pubtypes sections if requested.
1614 emitDebugPubSections();
1615
1616 // clean up.
1617 // FIXME: AbstractVariables.clear();
1618}
1619
1620void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1621 const DINode *Node, const MDNode *ScopeNode) {
1622 if (CU.getExistingAbstractEntity(Node))
1623 return;
1624
1625 if (LexicalScope *Scope =
1627 CU.createAbstractEntity(Node, Scope);
1628}
1629
1631 // Ensure the scope is not a DILexicalBlockFile.
1633}
1634
1635// Collect variable information from side table maintained by MF.
1636void DwarfDebug::collectVariableInfoFromMFTable(
1637 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1638 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1639 LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
1640 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1641 if (!VI.Var)
1642 continue;
1643 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1644 "Expected inlined-at fields to agree");
1645
1646 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1647 Processed.insert(Var);
1648 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1649
1650 // If variable scope is not found then skip this variable.
1651 if (!Scope) {
1652 LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1653 << ", no variable scope found\n");
1654 continue;
1655 }
1656
1657 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1658
1659 // If we have already seen information for this variable, add to what we
1660 // already know.
1661 if (DbgVariable *PreviousLoc = MFVars.lookup(Var)) {
1662 auto *PreviousMMI = std::get_if<Loc::MMI>(PreviousLoc);
1663 auto *PreviousEntryValue = std::get_if<Loc::EntryValue>(PreviousLoc);
1664 // Previous and new locations are both stack slots (MMI).
1665 if (PreviousMMI && VI.inStackSlot())
1666 PreviousMMI->addFrameIndexExpr(VI.Expr, VI.getStackSlot());
1667 // Previous and new locations are both entry values.
1668 else if (PreviousEntryValue && VI.inEntryValueRegister())
1669 PreviousEntryValue->addExpr(VI.getEntryValueRegister(), *VI.Expr);
1670 else {
1671 // Locations differ, this should (rarely) happen in optimized async
1672 // coroutines.
1673 // Prefer whichever location has an EntryValue.
1674 if (PreviousLoc->holds<Loc::MMI>())
1675 PreviousLoc->emplace<Loc::EntryValue>(VI.getEntryValueRegister(),
1676 *VI.Expr);
1677 LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1678 << ", conflicting fragment location types\n");
1679 }
1680 continue;
1681 }
1682
1683 auto RegVar = std::make_unique<DbgVariable>(
1684 cast<DILocalVariable>(Var.first), Var.second);
1685 if (VI.inStackSlot())
1686 RegVar->emplace<Loc::MMI>(VI.Expr, VI.getStackSlot());
1687 else
1688 RegVar->emplace<Loc::EntryValue>(VI.getEntryValueRegister(), *VI.Expr);
1689 LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
1690 << "\n");
1691 InfoHolder.addScopeVariable(Scope, RegVar.get());
1692 MFVars.insert({Var, RegVar.get()});
1693 ConcreteEntities.push_back(std::move(RegVar));
1694 }
1695}
1696
1697/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1698/// enclosing lexical scope. The check ensures there are no other instructions
1699/// in the same lexical scope preceding the DBG_VALUE and that its range is
1700/// either open or otherwise rolls off the end of the scope.
1701static bool validThroughout(LexicalScopes &LScopes,
1702 const MachineInstr *DbgValue,
1703 const MachineInstr *RangeEnd,
1704 const InstructionOrdering &Ordering) {
1705 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1706 auto MBB = DbgValue->getParent();
1707 auto DL = DbgValue->getDebugLoc();
1708 auto *LScope = LScopes.findLexicalScope(DL);
1709 // Scope doesn't exist; this is a dead DBG_VALUE.
1710 if (!LScope)
1711 return false;
1712 auto &LSRange = LScope->getRanges();
1713 if (LSRange.size() == 0)
1714 return false;
1715
1716 const MachineInstr *LScopeBegin = LSRange.front().first;
1717 // If the scope starts before the DBG_VALUE then we may have a negative
1718 // result. Otherwise the location is live coming into the scope and we
1719 // can skip the following checks.
1720 if (!Ordering.isBefore(DbgValue, LScopeBegin)) {
1721 // Exit if the lexical scope begins outside of the current block.
1722 if (LScopeBegin->getParent() != MBB)
1723 return false;
1724
1726 for (++Pred; Pred != MBB->rend(); ++Pred) {
1727 if (Pred->getFlag(MachineInstr::FrameSetup))
1728 break;
1729 auto PredDL = Pred->getDebugLoc();
1730 if (!PredDL || Pred->isMetaInstruction())
1731 continue;
1732 // Check whether the instruction preceding the DBG_VALUE is in the same
1733 // (sub)scope as the DBG_VALUE.
1734 if (DL->getScope() == PredDL->getScope())
1735 return false;
1736 auto *PredScope = LScopes.findLexicalScope(PredDL);
1737 if (!PredScope || LScope->dominates(PredScope))
1738 return false;
1739 }
1740 }
1741
1742 // If the range of the DBG_VALUE is open-ended, report success.
1743 if (!RangeEnd)
1744 return true;
1745
1746 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1747 // throughout the function. This is a hack, presumably for DWARF v2 and not
1748 // necessarily correct. It would be much better to use a dbg.declare instead
1749 // if we know the constant is live throughout the scope.
1750 if (MBB->pred_empty() &&
1751 all_of(DbgValue->debug_operands(),
1752 [](const MachineOperand &Op) { return Op.isImm(); }))
1753 return true;
1754
1755 // Test if the location terminates before the end of the scope.
1756 const MachineInstr *LScopeEnd = LSRange.back().second;
1757 if (Ordering.isBefore(RangeEnd, LScopeEnd))
1758 return false;
1759
1760 // There's a single location which starts at the scope start, and ends at or
1761 // after the scope end.
1762 return true;
1763}
1764
1765/// Build the location list for all DBG_VALUEs in the function that
1766/// describe the same variable. The resulting DebugLocEntries will have
1767/// strict monotonically increasing begin addresses and will never
1768/// overlap. If the resulting list has only one entry that is valid
1769/// throughout variable's scope return true.
1770//
1771// See the definition of DbgValueHistoryMap::Entry for an explanation of the
1772// different kinds of history map entries. One thing to be aware of is that if
1773// a debug value is ended by another entry (rather than being valid until the
1774// end of the function), that entry's instruction may or may not be included in
1775// the range, depending on if the entry is a clobbering entry (it has an
1776// instruction that clobbers one or more preceding locations), or if it is an
1777// (overlapping) debug value entry. This distinction can be seen in the example
1778// below. The first debug value is ended by the clobbering entry 2, and the
1779// second and third debug values are ended by the overlapping debug value entry
1780// 4.
1781//
1782// Input:
1783//
1784// History map entries [type, end index, mi]
1785//
1786// 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1787// 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1788// 2 | | [Clobber, $reg0 = [...], -, -]
1789// 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1790// 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1791//
1792// Output [start, end) [Value...]:
1793//
1794// [0-1) [(reg0, fragment 0, 32)]
1795// [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1796// [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1797// [4-) [(@g, fragment 0, 96)]
1798bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1799 const DbgValueHistoryMap::Entries &Entries) {
1800 using OpenRange =
1801 std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1802 SmallVector<OpenRange, 4> OpenRanges;
1803 bool isSafeForSingleLocation = true;
1804 const MachineInstr *StartDebugMI = nullptr;
1805 const MachineInstr *EndMI = nullptr;
1806
1807 for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1808 const MachineInstr *Instr = EI->getInstr();
1809
1810 // Remove all values that are no longer live.
1811 size_t Index = std::distance(EB, EI);
1812 erase_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1813
1814 // If we are dealing with a clobbering entry, this iteration will result in
1815 // a location list entry starting after the clobbering instruction.
1816 const MCSymbol *StartLabel =
1817 EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1818 assert(StartLabel &&
1819 "Forgot label before/after instruction starting a range!");
1820
1821 const MCSymbol *EndLabel;
1822 if (std::next(EI) == Entries.end()) {
1823 const MachineBasicBlock &EndMBB = Asm->MF->back();
1824 EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionID()].EndLabel;
1825 if (EI->isClobber())
1826 EndMI = EI->getInstr();
1827 }
1828 else if (std::next(EI)->isClobber())
1829 EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1830 else
1831 EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1832 assert(EndLabel && "Forgot label after instruction ending a range!");
1833
1834 if (EI->isDbgValue())
1835 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1836
1837 // If this history map entry has a debug value, add that to the list of
1838 // open ranges and check if its location is valid for a single value
1839 // location.
1840 if (EI->isDbgValue()) {
1841 // Do not add undef debug values, as they are redundant information in
1842 // the location list entries. An undef debug results in an empty location
1843 // description. If there are any non-undef fragments then padding pieces
1844 // with empty location descriptions will automatically be inserted, and if
1845 // all fragments are undef then the whole location list entry is
1846 // redundant.
1847 if (!Instr->isUndefDebugValue()) {
1848 auto Value = getDebugLocValue(Instr);
1849 OpenRanges.emplace_back(EI->getEndIndex(), Value);
1850
1851 // TODO: Add support for single value fragment locations.
1852 if (Instr->getDebugExpression()->isFragment())
1853 isSafeForSingleLocation = false;
1854
1855 if (!StartDebugMI)
1856 StartDebugMI = Instr;
1857 } else {
1858 isSafeForSingleLocation = false;
1859 }
1860 }
1861
1862 // Location list entries with empty location descriptions are redundant
1863 // information in DWARF, so do not emit those.
1864 if (OpenRanges.empty())
1865 continue;
1866
1867 // Omit entries with empty ranges as they do not have any effect in DWARF.
1868 if (StartLabel == EndLabel) {
1869 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1870 continue;
1871 }
1872
1874 for (auto &R : OpenRanges)
1875 Values.push_back(R.second);
1876
1877 // With Basic block sections, it is posssible that the StartLabel and the
1878 // Instr are not in the same section. This happens when the StartLabel is
1879 // the function begin label and the dbg value appears in a basic block
1880 // that is not the entry. In this case, the range needs to be split to
1881 // span each individual section in the range from StartLabel to EndLabel.
1882 if (Asm->MF->hasBBSections() && StartLabel == Asm->getFunctionBegin() &&
1883 !Instr->getParent()->sameSection(&Asm->MF->front())) {
1884 for (const auto &[MBBSectionId, MBBSectionRange] :
1885 Asm->MBBSectionRanges) {
1886 if (Instr->getParent()->getSectionID() == MBBSectionId) {
1887 DebugLoc.emplace_back(MBBSectionRange.BeginLabel, EndLabel, Values);
1888 break;
1889 }
1890 DebugLoc.emplace_back(MBBSectionRange.BeginLabel,
1891 MBBSectionRange.EndLabel, Values);
1892 }
1893 } else {
1894 DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1895 }
1896
1897 // Attempt to coalesce the ranges of two otherwise identical
1898 // DebugLocEntries.
1899 auto CurEntry = DebugLoc.rbegin();
1900 LLVM_DEBUG({
1901 dbgs() << CurEntry->getValues().size() << " Values:\n";
1902 for (auto &Value : CurEntry->getValues())
1903 Value.dump();
1904 dbgs() << "-----\n";
1905 });
1906
1907 auto PrevEntry = std::next(CurEntry);
1908 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1909 DebugLoc.pop_back();
1910 }
1911
1912 if (!isSafeForSingleLocation ||
1913 !validThroughout(LScopes, StartDebugMI, EndMI, getInstOrdering()))
1914 return false;
1915
1916 if (DebugLoc.size() == 1)
1917 return true;
1918
1919 if (!Asm->MF->hasBBSections())
1920 return false;
1921
1922 // Check here to see if loclist can be merged into a single range. If not,
1923 // we must keep the split loclists per section. This does exactly what
1924 // MergeRanges does without sections. We don't actually merge the ranges
1925 // as the split ranges must be kept intact if this cannot be collapsed
1926 // into a single range.
1927 const MachineBasicBlock *RangeMBB = nullptr;
1928 if (DebugLoc[0].getBeginSym() == Asm->getFunctionBegin())
1929 RangeMBB = &Asm->MF->front();
1930 else
1931 RangeMBB = Entries.begin()->getInstr()->getParent();
1932 auto RangeIt = Asm->MBBSectionRanges.find(RangeMBB->getSectionID());
1933 assert(RangeIt != Asm->MBBSectionRanges.end() &&
1934 "Range MBB not found in MBBSectionRanges!");
1935 auto *CurEntry = DebugLoc.begin();
1936 auto *NextEntry = std::next(CurEntry);
1937 auto NextRangeIt = std::next(RangeIt);
1938 while (NextEntry != DebugLoc.end()) {
1939 if (NextRangeIt == Asm->MBBSectionRanges.end())
1940 return false;
1941 // CurEntry should end the current section and NextEntry should start
1942 // the next section and the Values must match for these two ranges to be
1943 // merged. Do not match the section label end if it is the entry block
1944 // section. This is because the end label for the Debug Loc and the
1945 // Function end label could be different.
1946 if ((RangeIt->second.EndLabel != Asm->getFunctionEnd() &&
1947 CurEntry->getEndSym() != RangeIt->second.EndLabel) ||
1948 NextEntry->getBeginSym() != NextRangeIt->second.BeginLabel ||
1949 CurEntry->getValues() != NextEntry->getValues())
1950 return false;
1951 RangeIt = NextRangeIt;
1952 NextRangeIt = std::next(RangeIt);
1953 CurEntry = NextEntry;
1954 NextEntry = std::next(CurEntry);
1955 }
1956 return true;
1957}
1958
1959DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1960 LexicalScope &Scope,
1961 const DINode *Node,
1962 const DILocation *Location,
1963 const MCSymbol *Sym) {
1964 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1965 if (isa<const DILocalVariable>(Node)) {
1966 ConcreteEntities.push_back(
1967 std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1968 Location));
1969 InfoHolder.addScopeVariable(&Scope,
1970 cast<DbgVariable>(ConcreteEntities.back().get()));
1971 } else if (isa<const DILabel>(Node)) {
1972 ConcreteEntities.push_back(
1973 std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1974 Location, Sym));
1975 InfoHolder.addScopeLabel(&Scope,
1976 cast<DbgLabel>(ConcreteEntities.back().get()));
1977 }
1978 return ConcreteEntities.back().get();
1979}
1980
1981// Find variables for each lexical scope.
1982void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1983 const DISubprogram *SP,
1984 DenseSet<InlinedEntity> &Processed) {
1985 // Grab the variable info that was squirreled away in the MMI side-table.
1986 collectVariableInfoFromMFTable(TheCU, Processed);
1987
1988 for (const auto &I : DbgValues) {
1989 InlinedEntity IV = I.first;
1990 if (Processed.count(IV))
1991 continue;
1992
1993 // Instruction ranges, specifying where IV is accessible.
1994 const auto &HistoryMapEntries = I.second;
1995
1996 // Try to find any non-empty variable location. Do not create a concrete
1997 // entity if there are no locations.
1998 if (!DbgValues.hasNonEmptyLocation(HistoryMapEntries))
1999 continue;
2000
2001 LexicalScope *Scope = nullptr;
2002 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
2003 if (const DILocation *IA = IV.second)
2004 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
2005 else
2006 Scope = LScopes.findLexicalScope(LocalVar->getScope());
2007 // If variable scope is not found then skip this variable.
2008 if (!Scope)
2009 continue;
2010
2011 Processed.insert(IV);
2012 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
2013 *Scope, LocalVar, IV.second));
2014
2015 const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
2016 assert(MInsn->isDebugValue() && "History must begin with debug value");
2017
2018 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
2019 // If the history map contains a single debug value, there may be an
2020 // additional entry which clobbers the debug value.
2021 size_t HistSize = HistoryMapEntries.size();
2022 bool SingleValueWithClobber =
2023 HistSize == 2 && HistoryMapEntries[1].isClobber();
2024 if (HistSize == 1 || SingleValueWithClobber) {
2025 const auto *End =
2026 SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
2027 if (validThroughout(LScopes, MInsn, End, getInstOrdering())) {
2028 RegVar->emplace<Loc::Single>(MInsn);
2029 continue;
2030 }
2031 }
2032
2033 // Handle multiple DBG_VALUE instructions describing one variable.
2034 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar);
2035
2036 // Build the location list for this variable.
2038 bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
2039
2040 // Check whether buildLocationList managed to merge all locations to one
2041 // that is valid throughout the variable's scope. If so, produce single
2042 // value location.
2043 if (isValidSingleLocation) {
2044 RegVar->emplace<Loc::Single>(Entries[0].getValues()[0]);
2045 continue;
2046 }
2047
2048 // If the variable has a DIBasicType, extract it. Basic types cannot have
2049 // unique identifiers, so don't bother resolving the type with the
2050 // identifier map.
2051 const DIBasicType *BT = dyn_cast<DIBasicType>(
2052 static_cast<const Metadata *>(LocalVar->getType()));
2053
2054 // Finalize the entry by lowering it into a DWARF bytestream.
2055 for (auto &Entry : Entries)
2056 Entry.finalize(*Asm, List, BT, TheCU);
2057 }
2058
2059 // For each InlinedEntity collected from DBG_LABEL instructions, convert to
2060 // DWARF-related DbgLabel.
2061 for (const auto &I : DbgLabels) {
2062 InlinedEntity IL = I.first;
2063 const MachineInstr *MI = I.second;
2064 if (MI == nullptr)
2065 continue;
2066
2067 LexicalScope *Scope = nullptr;
2068 const DILabel *Label = cast<DILabel>(IL.first);
2069 // The scope could have an extra lexical block file.
2070 const DILocalScope *LocalScope =
2071 Label->getScope()->getNonLexicalBlockFileScope();
2072 // Get inlined DILocation if it is inlined label.
2073 if (const DILocation *IA = IL.second)
2074 Scope = LScopes.findInlinedScope(LocalScope, IA);
2075 else
2076 Scope = LScopes.findLexicalScope(LocalScope);
2077 // If label scope is not found then skip this label.
2078 if (!Scope)
2079 continue;
2080
2081 Processed.insert(IL);
2082 /// At this point, the temporary label is created.
2083 /// Save the temporary label to DbgLabel entity to get the
2084 /// actually address when generating Dwarf DIE.
2086 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
2087 }
2088
2089 // Collect info for retained nodes.
2090 for (const DINode *DN : SP->getRetainedNodes()) {
2091 const auto *LS = getRetainedNodeScope(DN);
2092 if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
2093 if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
2094 continue;
2095 LexicalScope *LexS = LScopes.findLexicalScope(LS);
2096 if (LexS)
2097 createConcreteEntity(TheCU, *LexS, DN, nullptr);
2098 } else {
2099 LocalDeclsPerLS[LS].insert(DN);
2100 }
2101 }
2102}
2103
2104// Process beginning of an instruction.
2106 const MachineFunction &MF = *MI->getMF();
2107 const auto *SP = MF.getFunction().getSubprogram();
2108 bool NoDebug =
2109 !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
2110
2111 // Delay slot support check.
2112 auto delaySlotSupported = [](const MachineInstr &MI) {
2113 if (!MI.isBundledWithSucc())
2114 return false;
2115 auto Suc = std::next(MI.getIterator());
2116 (void)Suc;
2117 // Ensure that delay slot instruction is successor of the call instruction.
2118 // Ex. CALL_INSTRUCTION {
2119 // DELAY_SLOT_INSTRUCTION }
2120 assert(Suc->isBundledWithPred() &&
2121 "Call bundle instructions are out of order");
2122 return true;
2123 };
2124
2125 // When describing calls, we need a label for the call instruction.
2126 if (!NoDebug && SP->areAllCallsDescribed() &&
2127 MI->isCandidateForAdditionalCallInfo(MachineInstr::AnyInBundle) &&
2128 (!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
2130 bool IsTail = TII->isTailCall(*MI);
2131 // For tail calls, we need the address of the branch instruction for
2132 // DW_AT_call_pc.
2133 if (IsTail)
2135 // For non-tail calls, we need the return address for the call for
2136 // DW_AT_call_return_pc. Under GDB tuning, this information is needed for
2137 // tail calls as well.
2139 }
2140
2142 if (!CurMI)
2143 return;
2144
2145 if (NoDebug)
2146 return;
2147
2148 auto RecordLineZero = [&]() {
2149 // Preserve the file and column numbers, if we can, to save space in
2150 // the encoded line table.
2151 // Do not update PrevInstLoc, it remembers the last non-0 line.
2152 const MDNode *Scope = nullptr;
2153 unsigned Column = 0;
2154 if (PrevInstLoc) {
2155 Scope = PrevInstLoc.getScope();
2156 Column = PrevInstLoc.getCol();
2157 }
2158 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
2159 };
2160
2161 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
2162 // the last line number actually emitted, to see if it was line 0.
2163 unsigned LastAsmLine =
2164 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
2165
2166 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
2167 // If the instruction is part of the function frame setup code, do not emit
2168 // any line record, as there is no correspondence with any user code.
2169 if (MI->isMetaInstruction())
2170 return;
2171 if (MI->getFlag(MachineInstr::FrameSetup)) {
2172 // Prevent a loc from the previous block leaking into frame setup instrs.
2173 if (LastAsmLine && PrevInstBB && PrevInstBB != MI->getParent())
2174 RecordLineZero();
2175 return;
2176 }
2177
2178 const DebugLoc &DL = MI->getDebugLoc();
2179 unsigned Flags = 0;
2180
2181 if (MI->getFlag(MachineInstr::FrameDestroy) && DL) {
2182 const MachineBasicBlock *MBB = MI->getParent();
2183 if (MBB && (MBB != EpilogBeginBlock)) {
2184 // First time FrameDestroy has been seen in this basic block
2187 }
2188 }
2189
2190 auto RecordSourceLine = [this](auto &DL, auto Flags) {
2191 SmallString<128> LocationString;
2192 if (Asm->OutStreamer->isVerboseAsm()) {
2193 raw_svector_ostream OS(LocationString);
2194 DL.print(OS);
2195 }
2196 recordSourceLine(DL.getLine(), DL.getCol(), DL.getScope(), Flags,
2197 LocationString);
2198 };
2199
2200 // There may be a mixture of scopes using and not using Key Instructions.
2201 // Not-Key-Instructions functions inlined into Key Instructions functions
2202 // should use not-key is_stmt handling. Key Instructions functions inlined
2203 // into Not-Key-Instructions functions should use Key Instructions is_stmt
2204 // handling.
2205 bool ScopeUsesKeyInstructions =
2207 DL->getScope()->getSubprogram()->getKeyInstructionsEnabled();
2208
2209 bool IsKey = false;
2210 if (ScopeUsesKeyInstructions && DL && DL.getLine())
2211 IsKey = KeyInstructions.contains(MI);
2212
2213 if (!DL && MI == PrologEndLoc) {
2214 // In rare situations, we might want to place the end of the prologue
2215 // somewhere that doesn't have a source location already. It should be in
2216 // the entry block.
2217 assert(MI->getParent() == &*MI->getMF()->begin());
2218 recordSourceLine(SP->getScopeLine(), 0, SP,
2220 return;
2221 }
2222
2223 bool PrevInstInSameSection =
2224 (!PrevInstBB ||
2225 PrevInstBB->getSectionID() == MI->getParent()->getSectionID());
2226 bool ForceIsStmt = ForceIsStmtInstrs.contains(MI);
2227 if (PrevInstInSameSection && !ForceIsStmt && DL.isSameSourceLocation(PrevInstLoc)) {
2228 // If we have an ongoing unspecified location, nothing to do here.
2229 if (!DL)
2230 return;
2231
2232 // Skip this if the instruction is Key, else we might accidentally miss an
2233 // is_stmt.
2234 if (!IsKey) {
2235 // We have an explicit location, same as the previous location.
2236 // But we might be coming back to it after a line 0 record.
2237 if ((LastAsmLine == 0 && DL.getLine() != 0) || Flags) {
2238 // Reinstate the source location but not marked as a statement.
2239 RecordSourceLine(DL, Flags);
2240 }
2241 return;
2242 }
2243 }
2244
2245 if (!DL) {
2246 // FIXME: We could assert that `DL.getKind() != DebugLocKind::Temporary`
2247 // here, or otherwise record any temporary DebugLocs seen to ensure that
2248 // transient compiler-generated instructions aren't leaking their DLs to
2249 // other instructions.
2250 // We have an unspecified location, which might want to be line 0.
2251 // If we have already emitted a line-0 record, don't repeat it.
2252 if (LastAsmLine == 0)
2253 return;
2254 // If user said Don't Do That, don't do that.
2256 return;
2257 // See if we have a reason to emit a line-0 record now.
2258 // Reasons to emit a line-0 record include:
2259 // - User asked for it (UnknownLocations).
2260 // - Instruction has a label, so it's referenced from somewhere else,
2261 // possibly debug information; we want it to have a source location.
2262 // - Instruction is at the top of a block; we don't want to inherit the
2263 // location from the physically previous (maybe unrelated) block.
2264 if (UnknownLocations == Enable || PrevLabel ||
2265 (PrevInstBB && PrevInstBB != MI->getParent()))
2266 RecordLineZero();
2267 return;
2268 }
2269
2270 // We have an explicit location, different from the previous location.
2271 // Don't repeat a line-0 record, but otherwise emit the new location.
2272 // (The new location might be an explicit line 0, which we do emit.)
2273 if (DL.getLine() == 0 && LastAsmLine == 0)
2274 return;
2275 if (MI == PrologEndLoc) {
2277 PrologEndLoc = nullptr;
2278 }
2279
2280 if (ScopeUsesKeyInstructions) {
2281 if (IsKey)
2282 Flags |= DWARF2_FLAG_IS_STMT;
2283 } else {
2284 // If the line changed, we call that a new statement; unless we went to
2285 // line 0 and came back, in which case it is not a new statement.
2286 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
2287 if (DL.getLine() && (DL.getLine() != OldLine || ForceIsStmt))
2288 Flags |= DWARF2_FLAG_IS_STMT;
2289 }
2290
2291 // Call target-specific source line recording.
2292 recordTargetSourceLine(DL, Flags);
2293
2294 // If we're not at line 0, remember this location.
2295 if (DL.getLine())
2296 PrevInstLoc = DL;
2297}
2298
2299/// Default implementation of target-specific source line recording.
2300void DwarfDebug::recordTargetSourceLine(const DebugLoc &DL, unsigned Flags) {
2301 SmallString<128> LocationString;
2302 if (Asm->OutStreamer->isVerboseAsm()) {
2303 raw_svector_ostream OS(LocationString);
2304 DL.print(OS);
2305 }
2306 recordSourceLine(DL.getLine(), DL.getCol(), DL.getScope(), Flags,
2307 LocationString);
2308}
2309
2310// Returns the position where we should place prologue_end, potentially nullptr,
2311// which means "no good place to put prologue_end". Returns true in the second
2312// return value if there are no setup instructions in this function at all,
2313// meaning we should not emit a start-of-function linetable entry, because it
2314// would be zero-lengthed.
2315static std::pair<const MachineInstr *, bool>
2317 // First known non-DBG_VALUE and non-frame setup location marks
2318 // the beginning of the function body.
2319 const auto &TII = *MF->getSubtarget().getInstrInfo();
2320 const MachineInstr *NonTrivialInst = nullptr;
2321 const Function &F = MF->getFunction();
2322 DISubprogram *SP = const_cast<DISubprogram *>(F.getSubprogram());
2323
2324 // Some instructions may be inserted into prologue after this function. Must
2325 // keep prologue for these cases.
2326 bool IsEmptyPrologue =
2327 !(F.hasPrologueData() || F.getMetadata(LLVMContext::MD_func_sanitize));
2328
2329 // Helper lambda to examine each instruction and potentially return it
2330 // as the prologue_end point.
2331 auto ExamineInst = [&](const MachineInstr &MI)
2332 -> std::optional<std::pair<const MachineInstr *, bool>> {
2333 // Is this instruction trivial data shuffling or frame-setup?
2334 bool isCopy = (TII.isCopyInstr(MI) ? true : false);
2335 bool isTrivRemat = TII.isTriviallyReMaterializable(MI);
2336 bool isFrameSetup = MI.getFlag(MachineInstr::FrameSetup);
2337
2338 if (!isFrameSetup && MI.getDebugLoc()) {
2339 // Scan forward to try to find a non-zero line number. The
2340 // prologue_end marks the first breakpoint in the function after the
2341 // frame setup, and a compiler-generated line 0 location is not a
2342 // meaningful breakpoint. If none is found, return the first
2343 // location after the frame setup.
2344 if (MI.getDebugLoc().getLine())
2345 return std::make_pair(&MI, IsEmptyPrologue);
2346 }
2347
2348 // Keep track of the first "non-trivial" instruction seen, i.e. anything
2349 // that doesn't involve shuffling data around or is a frame-setup.
2350 if (!isCopy && !isTrivRemat && !isFrameSetup && !NonTrivialInst)
2351 NonTrivialInst = &MI;
2352
2353 IsEmptyPrologue = false;
2354 return std::nullopt;
2355 };
2356
2357 // Examine all the instructions at the start of the function. This doesn't
2358 // necessarily mean just the entry block: unoptimised code can fall-through
2359 // into an initial loop, and it makes sense to put the initial breakpoint on
2360 // the first instruction of such a loop. However, if we pass branches, we're
2361 // better off synthesising an early prologue_end.
2362 auto CurBlock = MF->begin();
2363 auto CurInst = CurBlock->begin();
2364
2365 // Find the initial instruction, we're guaranteed one by the caller, but not
2366 // which block it's in.
2367 while (CurBlock->empty())
2368 CurInst = (++CurBlock)->begin();
2369 assert(CurInst != CurBlock->end());
2370
2371 // Helper function for stepping through the initial sequence of
2372 // unconditionally executed instructions.
2373 auto getNextInst = [&CurBlock, &CurInst, MF]() -> bool {
2374 // We've reached the end of the block. Did we just look at a terminator?
2375 if (CurInst->isTerminator()) {
2376 // Some kind of "real" control flow is occurring. At the very least
2377 // we would have to start exploring the CFG, a good signal that the
2378 // prologue is over.
2379 return false;
2380 }
2381
2382 // If we've already fallen through into a loop, don't fall through
2383 // further, use a backup-location.
2384 if (CurBlock->pred_size() > 1)
2385 return false;
2386
2387 // Fall-through from entry to the next block. This is common at -O0 when
2388 // there's no initialisation in the function. Bail if we're also at the
2389 // end of the function, or the remaining blocks have no instructions.
2390 // Skip empty blocks, in rare cases the entry can be empty, and
2391 // other optimisations may add empty blocks that the control flow falls
2392 // through.
2393 do {
2394 ++CurBlock;
2395 if (CurBlock == MF->end())
2396 return false;
2397 } while (CurBlock->empty());
2398 CurInst = CurBlock->begin();
2399 return true;
2400 };
2401
2402 while (true) {
2403 // Check whether this non-meta instruction a good position for prologue_end.
2404 if (!CurInst->isMetaInstruction()) {
2405 auto FoundInst = ExamineInst(*CurInst);
2406 if (FoundInst)
2407 return *FoundInst;
2408 }
2409
2410 // In very rare scenarios function calls can have line zero, and we
2411 // shouldn't step over such a call while trying to reach prologue_end. In
2412 // these extraordinary conditions, force the call to have the scope line
2413 // and put prologue_end there. This isn't ideal, but signals that the call
2414 // is where execution in the function starts, and is less catastrophic than
2415 // stepping over the call.
2416 if (CurInst->isCall()) {
2417 if (const DILocation *Loc = CurInst->getDebugLoc().get();
2418 Loc && Loc->getLine() == 0) {
2419 // Create and assign the scope-line position.
2420 unsigned ScopeLine = SP->getScopeLine();
2421 DILocation *ScopeLineDILoc =
2422 DILocation::get(SP->getContext(), ScopeLine, 0, SP);
2423 const_cast<MachineInstr *>(&*CurInst)->setDebugLoc(ScopeLineDILoc);
2424
2425 // Consider this position to be where prologue_end is placed.
2426 return std::make_pair(&*CurInst, false);
2427 }
2428 }
2429
2430 // Try to continue searching, but use a backup-location if substantive
2431 // computation is happening.
2432 auto NextInst = std::next(CurInst);
2433 if (NextInst != CurInst->getParent()->end()) {
2434 // Continue examining the current block.
2435 CurInst = NextInst;
2436 continue;
2437 }
2438
2439 if (!getNextInst())
2440 break;
2441 }
2442
2443 // We couldn't find any source-location, suggesting all meaningful information
2444 // got optimised away. Set the prologue_end to be the first non-trivial
2445 // instruction, which will get the scope line number. This is better than
2446 // nothing.
2447 // Only do this in the entry block, as we'll be giving it the scope line for
2448 // the function. Return IsEmptyPrologue==true if we've picked the first
2449 // instruction.
2450 if (NonTrivialInst && NonTrivialInst->getParent() == &*MF->begin()) {
2451 IsEmptyPrologue = NonTrivialInst == &*MF->begin()->begin();
2452 return std::make_pair(NonTrivialInst, IsEmptyPrologue);
2453 }
2454
2455 // If the entry path is empty, just don't have a prologue_end at all.
2456 return std::make_pair(nullptr, IsEmptyPrologue);
2457}
2458
2459/// Register a source line with debug info. Returns the unique label that was
2460/// emitted and which provides correspondence to the source line list.
2461static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
2462 const MDNode *S, unsigned Flags, unsigned CUID,
2463 uint16_t DwarfVersion,
2464 ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs,
2465 StringRef Comment = {}) {
2466 StringRef Fn;
2467 unsigned FileNo = 1;
2468 unsigned Discriminator = 0;
2469 if (auto *Scope = cast_or_null<DIScope>(S)) {
2470 Fn = Scope->getFilename();
2471 if (Line != 0 && DwarfVersion >= 4)
2472 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
2473 Discriminator = LBF->getDiscriminator();
2474
2475 FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
2476 .getOrCreateSourceID(Scope->getFile());
2477 }
2478 Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
2479 Discriminator, Fn, Comment);
2480}
2481
2482const MachineInstr *
2484 // Don't deal with functions that have no instructions.
2485 if (llvm::all_of(MF, [](const MachineBasicBlock &MBB) { return MBB.empty(); }))
2486 return nullptr;
2487
2488 std::pair<const MachineInstr *, bool> PrologEnd = findPrologueEndLoc(&MF);
2489 const MachineInstr *PrologEndLoc = PrologEnd.first;
2490 bool IsEmptyPrologue = PrologEnd.second;
2491
2492 // If the prolog is empty, no need to generate scope line for the proc.
2493 if (IsEmptyPrologue) {
2494 // If there's nowhere to put a prologue_end flag, emit a scope line in case
2495 // there are simply no source locations anywhere in the function.
2496 if (PrologEndLoc) {
2497 // Avoid trying to assign prologue_end to a line-zero location.
2498 // Instructions with no DebugLoc at all are fine, they'll be given the
2499 // scope line nuumber.
2500 const DebugLoc &DL = PrologEndLoc->getDebugLoc();
2501 if (!DL || DL->getLine() != 0)
2502 return PrologEndLoc;
2503
2504 // Later, don't place the prologue_end flag on this line-zero location.
2505 PrologEndLoc = nullptr;
2506 }
2507 }
2508
2509 // Ensure the compile unit is created if the function is called before
2510 // beginFunction().
2512 (void)getOrCreateDwarfCompileUnit(SP->getUnit());
2513 // We'd like to list the prologue as "not statements" but GDB behaves
2514 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
2515 ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
2516 CUID, getDwarfVersion(), getUnits());
2517 return PrologEndLoc;
2518}
2519
2520void DwarfDebug::computeKeyInstructions(const MachineFunction *MF) {
2521 // New function - reset KeyInstructions.
2522 KeyInstructions.clear();
2523
2524 // The current candidate is_stmt instructions for each source atom.
2525 // Map {(InlinedAt, Group): (Rank, Instructions)}.
2526 // NOTE: Anecdotally, for a large C++ blob, 99% of the instruction
2527 // SmallVectors contain 2 or fewer elements; use 2 inline elements.
2529 std::pair<uint8_t, SmallVector<const MachineInstr *, 2>>>
2530 GroupCandidates;
2531
2532 const auto &TII = *MF->getSubtarget().getInstrInfo();
2533
2534 // For each instruction:
2535 // * Skip insts without DebugLoc, AtomGroup or AtomRank, and line zeros.
2536 // * Check if insts in this group have been seen already in GroupCandidates.
2537 // * If this instr rank is equal, add this instruction to GroupCandidates.
2538 // Remove existing instructions from GroupCandidates if they have the
2539 // same parent.
2540 // * If this instr rank is higher (lower precedence), ignore it.
2541 // * If this instr rank is lower (higher precedence), erase existing
2542 // instructions from GroupCandidates and add this one.
2543 //
2544 // Then insert each GroupCandidates instruction into KeyInstructions.
2545
2546 for (auto &MBB : *MF) {
2547 // Rather than apply is_stmt directly to Key Instructions, we "float"
2548 // is_stmt up to the 1st instruction with the same line number in a
2549 // contiguous block. That instruction is called the "buoy". The
2550 // buoy gets reset if we encouner an instruction with an atom
2551 // group.
2552 const MachineInstr *Buoy = nullptr;
2553 // The atom group number associated with Buoy which may be 0 if we haven't
2554 // encountered an atom group yet in this blob of instructions with the same
2555 // line number.
2556 uint64_t BuoyAtom = 0;
2557
2558 for (auto &MI : MBB) {
2559 if (MI.isMetaInstruction())
2560 continue;
2561
2562 const DILocation *Loc = MI.getDebugLoc().get();
2563 if (!Loc || !Loc->getLine())
2564 continue;
2565
2566 // Reset the Buoy to this instruction if it has a different line number.
2567 if (!Buoy || Buoy->getDebugLoc().getLine() != Loc->getLine()) {
2568 Buoy = &MI;
2569 BuoyAtom = 0; // Set later when we know which atom the buoy is used by.
2570 }
2571
2572 // Call instructions are handled specially - we always mark them as key
2573 // regardless of atom info.
2574 bool IsCallLike = MI.isCall() || TII.isTailCall(MI);
2575 if (IsCallLike) {
2576 // Calls are always key. Put the buoy (may not be the call) into
2577 // KeyInstructions directly rather than the candidate map to avoid it
2578 // being erased (and we may not have a group number for the call).
2579 KeyInstructions.insert(Buoy);
2580
2581 // Avoid floating any future is_stmts up to the call.
2582 Buoy = nullptr;
2583 BuoyAtom = 0;
2584
2585 if (!Loc->getAtomGroup() || !Loc->getAtomRank())
2586 continue;
2587 }
2588
2589 auto *InlinedAt = Loc->getInlinedAt();
2590 uint64_t Group = Loc->getAtomGroup();
2591 uint8_t Rank = Loc->getAtomRank();
2592 if (!Group || !Rank)
2593 continue;
2594
2595 // Don't let is_stmts float past instructions from different source atoms.
2596 if (BuoyAtom && BuoyAtom != Group) {
2597 Buoy = &MI;
2598 BuoyAtom = Group;
2599 }
2600
2601 auto &[CandidateRank, CandidateInsts] =
2602 GroupCandidates[{InlinedAt, Group}];
2603
2604 // If CandidateRank is zero then CandidateInsts should be empty: there
2605 // are no other candidates for this group yet. If CandidateRank is nonzero
2606 // then CandidateInsts shouldn't be empty: we've got existing candidate
2607 // instructions.
2608 assert((CandidateRank == 0 && CandidateInsts.empty()) ||
2609 (CandidateRank != 0 && !CandidateInsts.empty()));
2610
2611 assert(Rank && "expected nonzero rank");
2612 // If we've seen other instructions in this group with higher precedence
2613 // (lower nonzero rank), don't add this one as a candidate.
2614 if (CandidateRank && CandidateRank < Rank)
2615 continue;
2616
2617 // If we've seen other instructions in this group of the same rank,
2618 // discard any from this block (keeping the others). Else if we've
2619 // seen other instructions in this group of lower precedence (higher
2620 // rank), discard them all.
2621 if (CandidateRank == Rank)
2622 llvm::remove_if(CandidateInsts, [&MI](const MachineInstr *Candidate) {
2623 return MI.getParent() == Candidate->getParent();
2624 });
2625 else if (CandidateRank > Rank)
2626 CandidateInsts.clear();
2627
2628 if (Buoy) {
2629 // Add this candidate.
2630 CandidateInsts.push_back(Buoy);
2631 CandidateRank = Rank;
2632
2633 assert(!BuoyAtom || BuoyAtom == Loc->getAtomGroup());
2634 BuoyAtom = Loc->getAtomGroup();
2635 } else {
2636 // Don't add calls, because they've been dealt with already. This means
2637 // CandidateInsts might now be empty - handle that.
2638 assert(IsCallLike);
2639 if (CandidateInsts.empty())
2640 CandidateRank = 0;
2641 }
2642 }
2643 }
2644
2645 for (const auto &[_, Insts] : GroupCandidates.values())
2646 for (auto *I : Insts)
2647 KeyInstructions.insert(I);
2648}
2649
2650/// For the function \p MF, finds the set of instructions which may represent a
2651/// change in line number from one or more of the preceding MBBs. Stores the
2652/// resulting set of instructions, which should have is_stmt set, in
2653/// ForceIsStmtInstrs.
2654void DwarfDebug::findForceIsStmtInstrs(const MachineFunction *MF) {
2655 ForceIsStmtInstrs.clear();
2656
2657 // For this function, we try to find MBBs where the last source line in every
2658 // block predecessor matches the first line seen in the block itself; for
2659 // every such MBB, we set is_stmt=false on the first line in the block, and
2660 // for every other block we set is_stmt=true on the first line.
2661 // For example, if we have the block %bb.3, which has 2 predecesors %bb.1 and
2662 // %bb.2:
2663 // bb.1:
2664 // $r3 = MOV64ri 12, debug-location !DILocation(line: 4)
2665 // JMP %bb.3, debug-location !DILocation(line: 5)
2666 // bb.2:
2667 // $r3 = MOV64ri 24, debug-location !DILocation(line: 5)
2668 // JMP %bb.3
2669 // bb.3:
2670 // $r2 = MOV64ri 1
2671 // $r1 = ADD $r2, $r3, debug-location !DILocation(line: 5)
2672 // When we examine %bb.3, we first check to see if it contains any
2673 // instructions with debug locations, and select the first such instruction;
2674 // in this case, the ADD, with line=5. We then examine both of its
2675 // predecessors to see what the last debug-location in them is. For each
2676 // predecessor, if they do not contain any debug-locations, or if the last
2677 // debug-location before jumping to %bb.3 does not have line=5, then the ADD
2678 // in %bb.3 must use IsStmt. In this case, all predecessors have a
2679 // debug-location with line=5 as the last debug-location before jumping to
2680 // %bb.3, so we do not set is_stmt for the ADD instruction - we know that
2681 // whichever MBB we have arrived from, the line has not changed.
2682
2683 const auto *TII = MF->getSubtarget().getInstrInfo();
2684
2685 // We only need to the predecessors of MBBs that could have is_stmt set by
2686 // this logic.
2687 SmallDenseSet<MachineBasicBlock *, 4> PredMBBsToExamine;
2688 SmallDenseMap<MachineBasicBlock *, MachineInstr *> PotentialIsStmtMBBInstrs;
2689 // We use const_cast even though we won't actually modify MF, because some
2690 // methods we need take a non-const MBB.
2691 for (auto &MBB : *const_cast<MachineFunction *>(MF)) {
2692 if (MBB.empty() || MBB.pred_empty())
2693 continue;
2694 for (auto &MI : MBB) {
2695 if (MI.getDebugLoc() && MI.getDebugLoc()->getLine()) {
2696 PredMBBsToExamine.insert_range(MBB.predecessors());
2697 PotentialIsStmtMBBInstrs.insert({&MBB, &MI});
2698 break;
2699 }
2700 }
2701 }
2702
2703 // For each predecessor MBB, we examine the last line seen before each branch
2704 // or logical fallthrough. We use analyzeBranch to handle cases where
2705 // different branches have different outgoing lines (i.e. if there are
2706 // multiple branches that each have their own source location); otherwise we
2707 // just use the last line in the block.
2708 for (auto *MBB : PredMBBsToExamine) {
2709 auto CheckMBBEdge = [&](MachineBasicBlock *Succ, unsigned OutgoingLine) {
2710 auto MBBInstrIt = PotentialIsStmtMBBInstrs.find(Succ);
2711 if (MBBInstrIt == PotentialIsStmtMBBInstrs.end())
2712 return;
2713 MachineInstr *MI = MBBInstrIt->second;
2714 if (MI->getDebugLoc()->getLine() == OutgoingLine)
2715 return;
2716 PotentialIsStmtMBBInstrs.erase(MBBInstrIt);
2717 ForceIsStmtInstrs.insert(MI);
2718 };
2719 // If this block is empty, we conservatively assume that its fallthrough
2720 // successor needs is_stmt; we could check MBB's predecessors to see if it
2721 // has a consistent entry line, but this seems unlikely to be worthwhile.
2722 if (MBB->empty()) {
2723 for (auto *Succ : MBB->successors())
2724 CheckMBBEdge(Succ, 0);
2725 continue;
2726 }
2727 // If MBB has no successors that are in the "potential" set, due to one or
2728 // more of them having confirmed is_stmt, we can skip this check early.
2729 if (none_of(MBB->successors(), [&](auto *SuccMBB) {
2730 return PotentialIsStmtMBBInstrs.contains(SuccMBB);
2731 }))
2732 continue;
2733 // If we can't determine what DLs this branch's successors use, just treat
2734 // all the successors as coming from the last DebugLoc.
2736 auto MIIt = MBB->rbegin();
2737 {
2738 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2740 bool AnalyzeFailed = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
2741 // For a conditional branch followed by unconditional branch where the
2742 // unconditional branch has a DebugLoc, that loc is the outgoing loc to
2743 // the the false destination only; otherwise, both destinations share an
2744 // outgoing loc.
2745 if (!AnalyzeFailed && !Cond.empty() && FBB != nullptr &&
2746 MBB->back().getDebugLoc() && MBB->back().getDebugLoc()->getLine()) {
2747 unsigned FBBLine = MBB->back().getDebugLoc()->getLine();
2748 assert(MIIt->isBranch() && "Bad result from analyzeBranch?");
2749 CheckMBBEdge(FBB, FBBLine);
2750 ++MIIt;
2751 SuccessorBBs.push_back(TBB);
2752 } else {
2753 // For all other cases, all successors share the last outgoing DebugLoc.
2754 SuccessorBBs.assign(MBB->succ_begin(), MBB->succ_end());
2755 }
2756 }
2757
2758 // If we don't find an outgoing loc, this block will start with a line 0.
2759 // It is possible that we have a block that has no DebugLoc, but acts as a
2760 // simple passthrough between two blocks that end and start with the same
2761 // line, e.g.:
2762 // bb.1:
2763 // JMP %bb.2, debug-location !10
2764 // bb.2:
2765 // JMP %bb.3
2766 // bb.3:
2767 // $r1 = ADD $r2, $r3, debug-location !10
2768 // If these blocks were merged into a single block, we would not attach
2769 // is_stmt to the ADD, but with this logic that only checks the immediate
2770 // predecessor, we will; we make this tradeoff because doing a full dataflow
2771 // analysis would be expensive, and these situations are probably not common
2772 // enough for this to be worthwhile.
2773 unsigned LastLine = 0;
2774 while (MIIt != MBB->rend()) {
2775 if (auto DL = MIIt->getDebugLoc(); DL && DL->getLine()) {
2776 LastLine = DL->getLine();
2777 break;
2778 }
2779 ++MIIt;
2780 }
2781 for (auto *Succ : SuccessorBBs)
2782 CheckMBBEdge(Succ, LastLine);
2783 }
2784}
2785
2786// Gather pre-function debug information. Assumes being called immediately
2787// after the function entry point has been emitted.
2789 CurFn = MF;
2790
2791 auto *SP = MF->getFunction().getSubprogram();
2792 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
2793 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
2794 return;
2795
2796 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
2797 FunctionLineTableLabel = CU.emitFuncLineTableOffsets()
2798 ? Asm->OutStreamer->emitLineTableLabel()
2799 : nullptr;
2800
2801 Asm->OutStreamer->getContext().setDwarfCompileUnitID(
2803
2804 // Call target-specific debug info initialization.
2806
2807 // Record beginning of function.
2809 *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
2810
2811 // Run both `findForceIsStmtInstrs` and `computeKeyInstructions` because
2812 // Not-Key-Instructions functions may be inlined into Key Instructions
2813 // functions and vice versa.
2815 computeKeyInstructions(MF);
2816 findForceIsStmtInstrs(MF);
2817}
2818
2819unsigned
2821 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
2822 // belongs to so that we add to the correct per-cu line table in the
2823 // non-asm case.
2824 if (Asm->OutStreamer->hasRawTextSupport())
2825 // Use a single line table if we are generating assembly.
2826 return 0;
2827 else
2828 return CU.getUniqueID();
2829}
2830
2832 const auto &CURanges = CU->getRanges();
2833 auto &LineTable = Asm->OutStreamer->getContext().getMCDwarfLineTable(
2835 // Add the last range label for the given CU.
2836 LineTable.getMCLineSections().addEndEntry(
2837 const_cast<MCSymbol *>(CURanges.back().End));
2838}
2839
2841 // If we don't have a subprogram for this function then there will be a hole
2842 // in the range information. Keep note of this by setting the previously used
2843 // section to nullptr.
2844 // Terminate the pending line table.
2845 if (PrevCU)
2846 terminateLineTable(PrevCU);
2847 PrevCU = nullptr;
2848 CurFn = nullptr;
2849}
2850
2851// Gather and emit post-function debug information.
2853 const Function &F = MF->getFunction();
2854 const DISubprogram *SP = F.getSubprogram();
2855
2856 assert(CurFn == MF &&
2857 "endFunction should be called with the same function as beginFunction");
2858
2859 // Set DwarfDwarfCompileUnitID in MCContext to default value.
2860 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
2861
2862 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
2863 assert(!FnScope || SP == FnScope->getScopeNode());
2864 DwarfCompileUnit &TheCU = getOrCreateDwarfCompileUnit(SP->getUnit());
2865 if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
2866 PrevLabel = nullptr;
2867 CurFn = nullptr;
2868 return;
2869 }
2870
2871 DenseSet<InlinedEntity> Processed;
2872 collectEntityInfo(TheCU, SP, Processed);
2873
2874 // Add the range of this function to the list of ranges for the CU.
2875 // With basic block sections, add ranges for all basic block sections.
2876 for (const auto &R : Asm->MBBSectionRanges)
2877 TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});
2878
2879 // Under -gmlt, skip building the subprogram if there are no inlined
2880 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
2881 // is still needed as we need its source location.
2882 if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
2884 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
2885 for (const auto &R : Asm->MBBSectionRanges)
2886 addArangeLabel(SymbolCU(&TheCU, R.second.BeginLabel));
2887
2888 assert(InfoHolder.getScopeVariables().empty());
2889 PrevLabel = nullptr;
2890 CurFn = nullptr;
2891 return;
2892 }
2893
2894#ifndef NDEBUG
2895 size_t NumAbstractSubprograms = LScopes.getAbstractScopesList().size();
2896#endif
2897 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
2898 const auto *SP = cast<DISubprogram>(AScope->getScopeNode());
2899 for (const DINode *DN : SP->getRetainedNodes()) {
2900 const auto *LS = getRetainedNodeScope(DN);
2901 // Ensure LexicalScope is created for the scope of this node.
2902 auto *LexS = LScopes.getOrCreateAbstractScope(LS);
2903 assert(LexS && "Expected the LexicalScope to be created.");
2904 if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
2905 // Collect info for variables/labels that were optimized out.
2906 if (!Processed.insert(InlinedEntity(DN, nullptr)).second ||
2907 TheCU.getExistingAbstractEntity(DN))
2908 continue;
2909 TheCU.createAbstractEntity(DN, LexS);
2910 } else {
2911 // Remember the node if this is a local declarations.
2912 LocalDeclsPerLS[LS].insert(DN);
2913 }
2914 assert(
2915 LScopes.getAbstractScopesList().size() == NumAbstractSubprograms &&
2916 "getOrCreateAbstractScope() inserted an abstract subprogram scope");
2917 }
2918 constructAbstractSubprogramScopeDIE(TheCU, AScope);
2919 }
2920
2921 ProcessedSPNodes.insert(SP);
2922 DIE &ScopeDIE =
2923 TheCU.constructSubprogramScopeDIE(SP, F, FnScope, FunctionLineTableLabel);
2924 if (auto *SkelCU = TheCU.getSkeleton())
2925 if (!LScopes.getAbstractScopesList().empty() &&
2927 SkelCU->constructSubprogramScopeDIE(SP, F, FnScope,
2928 FunctionLineTableLabel);
2929
2930 FunctionLineTableLabel = nullptr;
2931
2932 // Construct call site entries.
2933 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
2934
2935 // Clear debug info
2936 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
2937 // DbgVariables except those that are also in AbstractVariables (since they
2938 // can be used cross-function)
2939 InfoHolder.getScopeVariables().clear();
2940 InfoHolder.getScopeLabels().clear();
2941 LocalDeclsPerLS.clear();
2942 PrevLabel = nullptr;
2943 CurFn = nullptr;
2944}
2945
2946// Register a source line with debug info. Returns the unique label that was
2947// emitted and which provides correspondence to the source line list.
2948void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
2949 unsigned Flags, StringRef Location) {
2950 ::recordSourceLine(*Asm, Line, Col, S, Flags,
2951 Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
2952 getDwarfVersion(), getUnits(), Location);
2953}
2954
2955//===----------------------------------------------------------------------===//
2956// Emit Methods
2957//===----------------------------------------------------------------------===//
2958
2959// Emit the debug info section.
2960void DwarfDebug::emitDebugInfo() {
2961 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2962 Holder.emitUnits(/* UseOffsets */ false);
2963}
2964
2965// Emit the abbreviation section.
2966void DwarfDebug::emitAbbreviations() {
2967 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2968
2969 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2970}
2971
2972void DwarfDebug::emitStringOffsetsTableHeader() {
2973 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2975 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
2976 Holder.getStringOffsetsStartSym());
2977}
2978
2979template <typename AccelTableT>
2980void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
2981 StringRef TableName) {
2982 Asm->OutStreamer->switchSection(Section);
2983
2984 // Emit the full data.
2985 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
2986}
2987
2988void DwarfDebug::emitAccelDebugNames() {
2989 // Don't emit anything if we have no compilation units to index.
2990 if (getUnits().empty())
2991 return;
2992
2993 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
2994}
2995
2996// Emit visible names into a hashed accelerator table section.
2997void DwarfDebug::emitAccelNames() {
2998 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
2999 "Names");
3000}
3001
3002// Emit objective C classes and categories into a hashed accelerator table
3003// section.
3004void DwarfDebug::emitAccelObjC() {
3005 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
3006 "ObjC");
3007}
3008
3009// Emit namespace dies into a hashed accelerator table.
3010void DwarfDebug::emitAccelNamespaces() {
3011 emitAccel(AccelNamespace,
3012 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
3013 "namespac");
3014}
3015
3016// Emit type dies into a hashed accelerator table.
3017void DwarfDebug::emitAccelTypes() {
3018 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
3019 "types");
3020}
3021
3022// Public name handling.
3023// The format for the various pubnames:
3024//
3025// dwarf pubnames - offset/name pairs where the offset is the offset into the CU
3026// for the DIE that is named.
3027//
3028// gnu pubnames - offset/index value/name tuples where the offset is the offset
3029// into the CU and the index value is computed according to the type of value
3030// for the DIE that is named.
3031//
3032// For type units the offset is the offset of the skeleton DIE. For split dwarf
3033// it's the offset within the debug_info/debug_types dwo section, however, the
3034// reference in the pubname header doesn't change.
3035
3036/// computeIndexValue - Compute the gdb index value for the DIE and CU.
3038 const DIE *Die) {
3039 // Entities that ended up only in a Type Unit reference the CU instead (since
3040 // the pub entry has offsets within the CU there's no real offset that can be
3041 // provided anyway). As it happens all such entities (namespaces and types,
3042 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
3043 // not to be true it would be necessary to persist this information from the
3044 // point at which the entry is added to the index data structure - since by
3045 // the time the index is built from that, the original type/namespace DIE in a
3046 // type unit has already been destroyed so it can't be queried for properties
3047 // like tag, etc.
3048 if (Die->getTag() == dwarf::DW_TAG_compile_unit)
3052
3053 // We could have a specification DIE that has our most of our knowledge,
3054 // look for that now.
3055 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
3056 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
3057 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
3059 } else if (Die->findAttribute(dwarf::DW_AT_external))
3061
3062 switch (Die->getTag()) {
3063 case dwarf::DW_TAG_class_type:
3064 case dwarf::DW_TAG_structure_type:
3065 case dwarf::DW_TAG_union_type:
3066 case dwarf::DW_TAG_enumeration_type:
3068 dwarf::GIEK_TYPE, dwarf::isCPlusPlus(CU->getSourceLanguage())
3071 case dwarf::DW_TAG_typedef:
3072 case dwarf::DW_TAG_base_type:
3073 case dwarf::DW_TAG_subrange_type:
3074 case dwarf::DW_TAG_template_alias:
3076 case dwarf::DW_TAG_namespace:
3077 return dwarf::GIEK_TYPE;
3078 case dwarf::DW_TAG_subprogram:
3080 case dwarf::DW_TAG_variable:
3082 case dwarf::DW_TAG_enumerator:
3085 default:
3086 return dwarf::GIEK_NONE;
3087 }
3088}
3089
3090/// emitDebugPubSections - Emit visible names and types into debug pubnames and
3091/// pubtypes sections.
3092void DwarfDebug::emitDebugPubSections() {
3093 for (const auto &NU : CUMap) {
3094 DwarfCompileUnit *TheU = NU.second;
3095 if (!TheU->hasDwarfPubSections())
3096 continue;
3097
3098 bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
3100
3101 Asm->OutStreamer->switchSection(
3102 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
3103 : Asm->getObjFileLowering().getDwarfPubNamesSection());
3104 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
3105
3106 Asm->OutStreamer->switchSection(
3107 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
3108 : Asm->getObjFileLowering().getDwarfPubTypesSection());
3109 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
3110 }
3111}
3112
3113void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
3115 Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
3116 CU.getDebugSectionOffset());
3117 else
3118 Asm->emitDwarfSymbolReference(CU.getLabelBegin());
3119}
3120
3121void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
3122 DwarfCompileUnit *TheU,
3123 const StringMap<const DIE *> &Globals) {
3124 if (auto *Skeleton = TheU->getSkeleton())
3125 TheU = Skeleton;
3126
3127 // Emit the header.
3128 MCSymbol *EndLabel = Asm->emitDwarfUnitLength(
3129 "pub" + Name, "Length of Public " + Name + " Info");
3130
3131 Asm->OutStreamer->AddComment("DWARF Version");
3132 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
3133
3134 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
3135 emitSectionReference(*TheU);
3136
3137 Asm->OutStreamer->AddComment("Compilation Unit Length");
3138 Asm->emitDwarfLengthOrOffset(TheU->getLength());
3139
3140 // Emit the pubnames for this compilation unit.
3142 for (const auto &GI : Globals)
3143 Vec.emplace_back(GI.first(), GI.second);
3144 llvm::sort(Vec, [](auto &A, auto &B) {
3145 return A.second->getOffset() < B.second->getOffset();
3146 });
3147 for (const auto &[Name, Entity] : Vec) {
3148 Asm->OutStreamer->AddComment("DIE offset");
3149 Asm->emitDwarfLengthOrOffset(Entity->getOffset());
3150
3151 if (GnuStyle) {
3152 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
3153 Asm->OutStreamer->AddComment(
3154 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
3155 ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
3156 Asm->emitInt8(Desc.toBits());
3157 }
3158
3159 Asm->OutStreamer->AddComment("External Name");
3160 Asm->OutStreamer->emitBytes(StringRef(Name.data(), Name.size() + 1));
3161 }
3162
3163 Asm->OutStreamer->AddComment("End Mark");
3164 Asm->emitDwarfLengthOrOffset(0);
3165 Asm->OutStreamer->emitLabel(EndLabel);
3166}
3167
3168/// Emit null-terminated strings into a debug str section.
3169void DwarfDebug::emitDebugStr() {
3170 MCSection *StringOffsetsSection = nullptr;
3172 emitStringOffsetsTableHeader();
3173 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
3174 }
3175 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3176 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
3177 StringOffsetsSection, /* UseRelativeOffsets = */ true);
3178}
3179
3181 const DebugLocStream::Entry &Entry,
3182 const DwarfCompileUnit *CU) {
3183 auto &&Comments = DebugLocs.getComments(Entry);
3184 auto Comment = Comments.begin();
3185 auto End = Comments.end();
3186
3187 // The expressions are inserted into a byte stream rather early (see
3188 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
3189 // need to reference a base_type DIE the offset of that DIE is not yet known.
3190 // To deal with this we instead insert a placeholder early and then extract
3191 // it here and replace it with the real reference.
3192 unsigned PtrSize = Asm->MAI.getCodePointerSize();
3193 DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
3194 DebugLocs.getBytes(Entry).size()),
3195 Asm->getDataLayout().isLittleEndian(), PtrSize);
3196 DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());
3197
3198 using Encoding = DWARFExpression::Operation::Encoding;
3199 uint64_t Offset = 0;
3200 for (const auto &Op : Expr) {
3201 assert(Op.getCode() != dwarf::DW_OP_const_type &&
3202 "3 operand ops not yet supported");
3203 assert(!Op.getSubCode() && "SubOps not yet supported");
3204 Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
3205 Offset++;
3206 for (unsigned I = 0; I < Op.getDescription().Op.size(); ++I) {
3207 if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
3208 unsigned Length =
3209 Streamer.emitDIERef(*CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die);
3210 // Make sure comments stay aligned.
3211 for (unsigned J = 0; J < Length; ++J)
3212 if (Comment != End)
3213 Comment++;
3214 } else {
3215 for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
3216 Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
3217 }
3218 Offset = Op.getOperandEndOffset(I);
3219 }
3220 assert(Offset == Op.getEndOffset());
3221 }
3222}
3223
3225 const DbgValueLoc &Value,
3226 DwarfExpression &DwarfExpr) {
3227 auto *DIExpr = Value.getExpression();
3228 DIExpressionCursor ExprCursor(DIExpr);
3229 DwarfExpr.addFragmentOffset(DIExpr);
3230
3231 // If the DIExpr is an Entry Value, we want to follow the same code path
3232 // regardless of whether the DBG_VALUE is variadic or not.
3233 if (DIExpr && DIExpr->isEntryValue()) {
3234 // Entry values can only be a single register with no additional DIExpr,
3235 // so just add it directly.
3236 assert(Value.getLocEntries().size() == 1);
3237 assert(Value.getLocEntries()[0].isLocation());
3238 MachineLocation Location = Value.getLocEntries()[0].getLoc();
3239 DwarfExpr.setLocation(Location, DIExpr);
3240
3241 DwarfExpr.beginEntryValueExpression(ExprCursor);
3242
3244 if (!DwarfExpr.addMachineRegExpression(TRI, ExprCursor, Location.getReg()))
3245 return;
3246 return DwarfExpr.addExpression(std::move(ExprCursor));
3247 }
3248
3249 // Regular entry.
3250 auto EmitValueLocEntry = [&DwarfExpr, &BT,
3251 &AP](const DbgValueLocEntry &Entry,
3252 DIExpressionCursor &Cursor) -> bool {
3253 if (Entry.isInt()) {
3254 if (BT && (BT->getEncoding() == dwarf::DW_ATE_boolean))
3255 DwarfExpr.addBooleanConstant(Entry.getInt());
3256 else if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
3257 BT->getEncoding() == dwarf::DW_ATE_signed_char))
3258 DwarfExpr.addSignedConstant(Entry.getInt());
3259 else
3260 DwarfExpr.addUnsignedConstant(Entry.getInt());
3261 } else if (Entry.isLocation()) {
3262 MachineLocation Location = Entry.getLoc();
3263 if (Location.isIndirect())
3264 DwarfExpr.setMemoryLocationKind();
3265
3267 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
3268 return false;
3269 } else if (Entry.isTargetIndexLocation()) {
3270 TargetIndexLocation Loc = Entry.getTargetIndexLocation();
3271 // TODO TargetIndexLocation is a target-independent. Currently only the
3272 // WebAssembly-specific encoding is supported.
3274 DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
3275 } else if (Entry.isConstantFP()) {
3276 if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&
3277 !Cursor) {
3278 DwarfExpr.addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);
3279 } else if (Entry.getConstantFP()
3280 ->getValueAPF()
3281 .bitcastToAPInt()
3282 .getBitWidth() <= 64 /*bits*/) {
3283 DwarfExpr.addUnsignedConstant(
3284 Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
3285 } else {
3286 LLVM_DEBUG(
3287 dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
3288 << Entry.getConstantFP()
3289 ->getValueAPF()
3290 .bitcastToAPInt()
3291 .getBitWidth()
3292 << " bits\n");
3293 return false;
3294 }
3295 }
3296 return true;
3297 };
3298
3299 if (!Value.isVariadic()) {
3300 if (!EmitValueLocEntry(Value.getLocEntries()[0], ExprCursor))
3301 return;
3302 DwarfExpr.addExpression(std::move(ExprCursor));
3303 return;
3304 }
3305
3306 // If any of the location entries are registers with the value 0, then the
3307 // location is undefined.
3308 if (any_of(Value.getLocEntries(), [](const DbgValueLocEntry &Entry) {
3309 return Entry.isLocation() && !Entry.getLoc().getReg();
3310 }))
3311 return;
3312
3313 DwarfExpr.addExpression(
3314 std::move(ExprCursor),
3315 [EmitValueLocEntry, &Value](unsigned Idx,
3316 DIExpressionCursor &Cursor) -> bool {
3317 return EmitValueLocEntry(Value.getLocEntries()[Idx], Cursor);
3318 });
3319}
3320
3323 const DIBasicType *BT,
3324 DwarfCompileUnit &TheCU) {
3325 assert(!Values.empty() &&
3326 "location list entries without values are redundant");
3327 assert(Begin != End && "unexpected location list entry with empty range");
3328 DebugLocStream::EntryBuilder Entry(List, Begin, End);
3329 BufferByteStreamer Streamer = Entry.getStreamer();
3330 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
3331 const DbgValueLoc &Value = Values[0];
3332 if (Value.isFragment()) {
3333 // Emit all fragments that belong to the same variable and range.
3334 assert(llvm::all_of(Values, [](DbgValueLoc P) {
3335 return P.isFragment();
3336 }) && "all values are expected to be fragments");
3337 assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
3338
3339 for (const auto &Fragment : Values)
3340 DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
3341
3342 } else {
3343 assert(Values.size() == 1 && "only fragments may have >1 value");
3344 DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
3345 }
3346 DwarfExpr.finalize();
3347 if (DwarfExpr.TagOffset)
3348 List.setTagOffset(*DwarfExpr.TagOffset);
3349}
3350
3352 const DwarfCompileUnit *CU) {
3353 // Emit the size.
3354 Asm->OutStreamer->AddComment("Loc expr size");
3355 if (getDwarfVersion() >= 5)
3356 Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
3357 else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
3358 Asm->emitInt16(DebugLocs.getBytes(Entry).size());
3359 else {
3360 // The entry is too big to fit into 16 bit, drop it as there is nothing we
3361 // can do.
3362 Asm->emitInt16(0);
3363 return;
3364 }
3365 // Emit the entry.
3366 APByteStreamer Streamer(*Asm);
3367 emitDebugLocEntry(Streamer, Entry, CU);
3368}
3369
3370// Emit the header of a DWARF 5 range list table list table. Returns the symbol
3371// that designates the end of the table for the caller to emit when the table is
3372// complete.
3374 const DwarfFile &Holder) {
3375 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
3376
3377 Asm->OutStreamer->AddComment("Offset entry count");
3378 Asm->emitInt32(Holder.getRangeLists().size());
3379 Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
3380
3381 for (const RangeSpanList &List : Holder.getRangeLists())
3382 Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
3383 Asm->getDwarfOffsetByteSize());
3384
3385 return TableEnd;
3386}
3387
3388// Emit the header of a DWARF 5 locations list table. Returns the symbol that
3389// designates the end of the table for the caller to emit when the table is
3390// complete.
3392 const DwarfDebug &DD) {
3393 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
3394
3395 const auto &DebugLocs = DD.getDebugLocs();
3396
3397 Asm->OutStreamer->AddComment("Offset entry count");
3398 Asm->emitInt32(DebugLocs.getLists().size());
3399 Asm->OutStreamer->emitLabel(DebugLocs.getSym());
3400
3401 for (const auto &List : DebugLocs.getLists())
3402 Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),
3403 Asm->getDwarfOffsetByteSize());
3404
3405 return TableEnd;
3406}
3407
3408template <typename Ranges, typename PayloadEmitter>
3409static void
3410emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
3411 const DwarfCompileUnit &CU, unsigned BaseAddressx,
3412 unsigned OffsetPair, unsigned StartxLength, unsigned StartxEndx,
3413 unsigned EndOfList, StringRef (*StringifyEnum)(unsigned),
3414 bool ShouldUseBaseAddress, PayloadEmitter EmitPayload) {
3415 auto Size = Asm->MAI.getCodePointerSize();
3416 bool UseDwarf5 = DD.getDwarfVersion() >= 5;
3417
3418 // Emit our symbol so we can find the beginning of the range.
3419 Asm->OutStreamer->emitLabel(Sym);
3420
3421 // Gather all the ranges that apply to the same section so they can share
3422 // a base address entry.
3423 SmallMapVector<const MCSection *, std::vector<decltype(&*R.begin())>, 16>
3424 SectionRanges;
3425
3426 for (const auto &Range : R)
3427 SectionRanges[&Range.Begin->getSection()].push_back(&Range);
3428
3429 const MCSymbol *CUBase = CU.getBaseAddress();
3430 bool BaseIsSet = false;
3431 for (const auto &P : SectionRanges) {
3432 auto *Base = CUBase;
3433 if (DD.shouldResetBaseAddress(*P.first) ||
3434 (DD.useSplitDwarf() && UseDwarf5 && P.first->isLinkerRelaxable())) {
3435 BaseIsSet = false;
3436 Base = nullptr;
3437 } else if (!Base && ShouldUseBaseAddress) {
3438 const MCSymbol *Begin = P.second.front()->Begin;
3439 const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
3440 if (!UseDwarf5) {
3441 Base = NewBase;
3442 BaseIsSet = true;
3443 Asm->OutStreamer->emitIntValue(-1, Size);
3444 Asm->OutStreamer->AddComment(" base address");
3445 Asm->OutStreamer->emitSymbolValue(Base, Size);
3446 } else if (NewBase != Begin || P.second.size() > 1) {
3447 // Only use a base address if
3448 // * the existing pool address doesn't match (NewBase != Begin)
3449 // * or, there's more than one entry to share the base address
3450 Base = NewBase;
3451 BaseIsSet = true;
3452 Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
3453 Asm->emitInt8(BaseAddressx);
3454 Asm->OutStreamer->AddComment(" base address index");
3455 Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
3456 }
3457 } else if (BaseIsSet && !UseDwarf5) {
3458 BaseIsSet = false;
3459 assert(!Base);
3460 Asm->OutStreamer->emitIntValue(-1, Size);
3461 Asm->OutStreamer->emitIntValue(0, Size);
3462 }
3463
3464 for (const auto *RS : P.second) {
3465 const MCSymbol *Begin = RS->Begin;
3466 const MCSymbol *End = RS->End;
3467 assert(Begin && "Range without a begin symbol?");
3468 assert(End && "Range without an end symbol?");
3469 if (Base) {
3470 if (UseDwarf5) {
3471 // Emit offset_pair when we have a base.
3472 Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
3473 Asm->emitInt8(OffsetPair);
3474 Asm->OutStreamer->AddComment(" starting offset");
3475 Asm->emitLabelDifferenceAsULEB128(Begin, Base);
3476 Asm->OutStreamer->AddComment(" ending offset");
3477 Asm->emitLabelDifferenceAsULEB128(End, Base);
3478 } else {
3479 Asm->emitLabelDifference(Begin, Base, Size);
3480 Asm->emitLabelDifference(End, Base, Size);
3481 }
3482 } else if (UseDwarf5) {
3483 // NOTE: We can't use absoluteSymbolDiff here instead of
3484 // isRangeRelaxable. While isRangeRelaxable only checks that the offset
3485 // between labels won't change at link time (which is exactly what we
3486 // need), absoluteSymbolDiff also requires that the offset remain
3487 // unchanged at assembly time, imposing a much stricter condition.
3488 // Consequently, this would lead to less optimal debug info emission.
3489 if (DD.useSplitDwarf() && llvm::isRangeRelaxable(Begin, End)) {
3490 Asm->OutStreamer->AddComment(StringifyEnum(StartxEndx));
3491 Asm->emitInt8(StartxEndx);
3492 Asm->OutStreamer->AddComment(" start index");
3493 Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
3494 Asm->OutStreamer->AddComment(" end index");
3495 Asm->emitULEB128(DD.getAddressPool().getIndex(End));
3496 } else {
3497 Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
3498 Asm->emitInt8(StartxLength);
3499 Asm->OutStreamer->AddComment(" start index");
3500 Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
3501 Asm->OutStreamer->AddComment(" length");
3502 Asm->emitLabelDifferenceAsULEB128(End, Begin);
3503 }
3504 } else {
3505 Asm->OutStreamer->emitSymbolValue(Begin, Size);
3506 Asm->OutStreamer->emitSymbolValue(End, Size);
3507 }
3508 EmitPayload(*RS);
3509 }
3510 }
3511
3512 if (UseDwarf5) {
3513 Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
3514 Asm->emitInt8(EndOfList);
3515 } else {
3516 // Terminate the list with two 0 values.
3517 Asm->OutStreamer->emitIntValue(0, Size);
3518 Asm->OutStreamer->emitIntValue(0, Size);
3519 }
3520}
3521
3522// Handles emission of both debug_loclist / debug_loclist.dwo
3523static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
3525 DD, Asm, List.Label, DD.getDebugLocs().getEntries(List), *List.CU,
3526 dwarf::DW_LLE_base_addressx, dwarf::DW_LLE_offset_pair,
3527 dwarf::DW_LLE_startx_length, dwarf::DW_LLE_startx_endx,
3528 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
3529 /* ShouldUseBaseAddress */ true, [&](const DebugLocStream::Entry &E) {
3530 DD.emitDebugLocEntryLocation(E, List.CU);
3531 });
3532}
3533
3534void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
3535 if (DebugLocs.getLists().empty())
3536 return;
3537
3538 Asm->OutStreamer->switchSection(Sec);
3539
3540 MCSymbol *TableEnd = nullptr;
3541 if (getDwarfVersion() >= 5)
3542 TableEnd = emitLoclistsTableHeader(Asm, *this);
3543
3544 for (const auto &List : DebugLocs.getLists())
3545 emitLocList(*this, Asm, List);
3546
3547 if (TableEnd)
3548 Asm->OutStreamer->emitLabel(TableEnd);
3549}
3550
3551// Emit locations into the .debug_loc/.debug_loclists section.
3552void DwarfDebug::emitDebugLoc() {
3553 emitDebugLocImpl(
3554 getDwarfVersion() >= 5
3555 ? Asm->getObjFileLowering().getDwarfLoclistsSection()
3556 : Asm->getObjFileLowering().getDwarfLocSection());
3557}
3558
3559// Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
3560void DwarfDebug::emitDebugLocDWO() {
3561 if (getDwarfVersion() >= 5) {
3562 emitDebugLocImpl(
3563 Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
3564
3565 return;
3566 }
3567
3568 for (const auto &List : DebugLocs.getLists()) {
3569 Asm->OutStreamer->switchSection(
3570 Asm->getObjFileLowering().getDwarfLocDWOSection());
3571 Asm->OutStreamer->emitLabel(List.Label);
3572
3573 for (const auto &Entry : DebugLocs.getEntries(List)) {
3574 // GDB only supports startx_length in pre-standard split-DWARF.
3575 // (in v5 standard loclists, it currently* /only/ supports base_address +
3576 // offset_pair, so the implementations can't really share much since they
3577 // need to use different representations)
3578 // * as of October 2018, at least
3579 //
3580 // In v5 (see emitLocList), this uses SectionLabels to reuse existing
3581 // addresses in the address pool to minimize object size/relocations.
3582 Asm->emitInt8(dwarf::DW_LLE_startx_length);
3583 unsigned idx = AddrPool.getIndex(Entry.Begin);
3584 Asm->emitULEB128(idx);
3585 // Also the pre-standard encoding is slightly different, emitting this as
3586 // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
3587 Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
3589 }
3590 Asm->emitInt8(dwarf::DW_LLE_end_of_list);
3591 }
3592}
3593
3596};
3597
3598// Emit a debug aranges section, containing a CU lookup for any
3599// address we can tie back to a CU.
3600void DwarfDebug::emitDebugARanges() {
3601 if (ArangeLabels.empty())
3602 return;
3603
3604 // Provides a unique id per text section.
3606
3607 // Filter labels by section.
3608 for (const SymbolCU &SCU : ArangeLabels) {
3609 if (SCU.Sym->isInSection()) {
3610 // Make a note of this symbol and it's section.
3611 MCSection *Section = &SCU.Sym->getSection();
3612 SectionMap[Section].push_back(SCU);
3613 } else {
3614 // Some symbols (e.g. common/bss on mach-o) can have no section but still
3615 // appear in the output. This sucks as we rely on sections to build
3616 // arange spans. We can do it without, but it's icky.
3617 SectionMap[nullptr].push_back(SCU);
3618 }
3619 }
3620
3621 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
3622
3623 for (auto &I : SectionMap) {
3624 MCSection *Section = I.first;
3626 assert(!List.empty());
3627
3628 // If we have no section (e.g. common), just write out
3629 // individual spans for each symbol.
3630 if (!Section) {
3631 for (const SymbolCU &Cur : List) {
3632 ArangeSpan Span;
3633 Span.Start = Cur.Sym;
3634 Span.End = nullptr;
3635 assert(Cur.CU);
3636 Spans[Cur.CU].push_back(Span);
3637 }
3638 continue;
3639 }
3640
3641 // Insert a final terminator.
3642 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
3643
3644 // Build spans between each label.
3645 const MCSymbol *StartSym = List[0].Sym;
3646 for (size_t n = 1, e = List.size(); n < e; n++) {
3647 const SymbolCU &Prev = List[n - 1];
3648 const SymbolCU &Cur = List[n];
3649
3650 // Try and build the longest span we can within the same CU.
3651 if (Cur.CU != Prev.CU) {
3652 ArangeSpan Span;
3653 Span.Start = StartSym;
3654 Span.End = Cur.Sym;
3655 assert(Prev.CU);
3656 Spans[Prev.CU].push_back(Span);
3657 StartSym = Cur.Sym;
3658 }
3659 }
3660 }
3661
3662 // Start the dwarf aranges section.
3663 Asm->OutStreamer->switchSection(
3664 Asm->getObjFileLowering().getDwarfARangesSection());
3665
3666 unsigned PtrSize = Asm->MAI.getCodePointerSize();
3667
3668 // Build a list of CUs used.
3669 std::vector<DwarfCompileUnit *> CUs;
3670 for (const auto &it : Spans) {
3671 DwarfCompileUnit *CU = it.first;
3672 CUs.push_back(CU);
3673 }
3674
3675 // Sort the CU list (again, to ensure consistent output order).
3676 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
3677 return A->getUniqueID() < B->getUniqueID();
3678 });
3679
3680 // Emit an arange table for each CU we used.
3681 for (DwarfCompileUnit *CU : CUs) {
3682 std::vector<ArangeSpan> &List = Spans[CU];
3683
3684 // Describe the skeleton CU's offset and length, not the dwo file's.
3685 if (auto *Skel = CU->getSkeleton())
3686 CU = Skel;
3687
3688 // Emit size of content not including length itself.
3689 unsigned ContentSize =
3690 sizeof(int16_t) + // DWARF ARange version number
3691 Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info
3692 // section
3693 sizeof(int8_t) + // Pointer Size (in bytes)
3694 sizeof(int8_t); // Segment Size (in bytes)
3695
3696 unsigned TupleSize = PtrSize * 2;
3697
3698 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
3699 unsigned Padding = offsetToAlignment(
3700 Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize));
3701
3702 ContentSize += Padding;
3703 ContentSize += (List.size() + 1) * TupleSize;
3704
3705 // For each compile unit, write the list of spans it covers.
3706 Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set");
3707 Asm->OutStreamer->AddComment("DWARF Arange version number");
3708 Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
3709 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
3710 emitSectionReference(*CU);
3711 Asm->OutStreamer->AddComment("Address Size (in bytes)");
3712 Asm->emitInt8(PtrSize);
3713 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
3714 Asm->emitInt8(0);
3715
3716 Asm->OutStreamer->emitFill(Padding, 0xff);
3717
3718 for (const ArangeSpan &Span : List) {
3719 Asm->emitLabelReference(Span.Start, PtrSize);
3720
3721 // Calculate the size as being from the span start to its end.
3722 //
3723 // If the size is zero, then round it up to one byte. The DWARF
3724 // specification requires that entries in this table have nonzero
3725 // lengths.
3726 auto SizeRef = SymSize.find(Span.Start);
3727 if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
3728 Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
3729 } else {
3730 // For symbols without an end marker (e.g. common), we
3731 // write a single arange entry containing just that one symbol.
3732 uint64_t Size;
3733 if (SizeRef == SymSize.end() || SizeRef->second == 0)
3734 Size = 1;
3735 else
3736 Size = SizeRef->second;
3737
3738 Asm->OutStreamer->emitIntValue(Size, PtrSize);
3739 }
3740 }
3741
3742 Asm->OutStreamer->AddComment("ARange terminator");
3743 Asm->OutStreamer->emitIntValue(0, PtrSize);
3744 Asm->OutStreamer->emitIntValue(0, PtrSize);
3745 }
3746}
3747
3748/// Emit a single range list. We handle both DWARF v5 and earlier.
3750 const RangeSpanList &List) {
3751 emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
3752 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
3753 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_startx_endx,
3754 dwarf::DW_RLE_end_of_list, llvm::dwarf::RangeListEncodingString,
3755 List.CU->getCUNode()->getRangesBaseAddress() ||
3756 DD.getDwarfVersion() >= 5,
3757 [](auto) {});
3758}
3759
3760void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
3761 if (Holder.getRangeLists().empty())
3762 return;
3763
3765 assert(!CUMap.empty());
3766 assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
3767 return !Pair.second->getCUNode()->isDebugDirectivesOnly();
3768 }));
3769
3770 Asm->OutStreamer->switchSection(Section);
3771
3772 MCSymbol *TableEnd = nullptr;
3773 if (getDwarfVersion() >= 5)
3774 TableEnd = emitRnglistsTableHeader(Asm, Holder);
3775
3776 for (const RangeSpanList &List : Holder.getRangeLists())
3777 emitRangeList(*this, Asm, List);
3778
3779 if (TableEnd)
3780 Asm->OutStreamer->emitLabel(TableEnd);
3781}
3782
3783/// Emit address ranges into the .debug_ranges section or into the DWARF v5
3784/// .debug_rnglists section.
3785void DwarfDebug::emitDebugRanges() {
3786 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3787
3788 emitDebugRangesImpl(Holder,
3789 getDwarfVersion() >= 5
3790 ? Asm->getObjFileLowering().getDwarfRnglistsSection()
3791 : Asm->getObjFileLowering().getDwarfRangesSection());
3792}
3793
3794void DwarfDebug::emitDebugRangesDWO() {
3795 emitDebugRangesImpl(InfoHolder,
3796 Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
3797}
3798
3799/// Emit the header of a DWARF 5 macro section, or the GNU extension for
3800/// DWARF 4.
3801static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
3802 const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
3803 enum HeaderFlagMask {
3804#define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
3805#include "llvm/BinaryFormat/Dwarf.def"
3806 };
3807 Asm->OutStreamer->AddComment("Macro information version");
3808 Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
3809 // We emit the line offset flag unconditionally here, since line offset should
3810 // be mostly present.
3811 if (Asm->isDwarf64()) {
3812 Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present");
3813 Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
3814 } else {
3815 Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
3816 Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
3817 }
3818 Asm->OutStreamer->AddComment("debug_line_offset");
3819 if (DD.useSplitDwarf())
3820 Asm->emitDwarfLengthOrOffset(0);
3821 else
3822 Asm->emitDwarfSymbolReference(CU.getLineTableStartSym());
3823}
3824
3825void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
3826 for (auto *MN : Nodes) {
3827 if (auto *M = dyn_cast<DIMacro>(MN))
3828 emitMacro(*M);
3829 else if (auto *F = dyn_cast<DIMacroFile>(MN))
3830 emitMacroFile(*F, U);
3831 else
3832 llvm_unreachable("Unexpected DI type!");
3833 }
3834}
3835
3836void DwarfDebug::emitMacro(DIMacro &M) {
3837 StringRef Name = M.getName();
3838 StringRef Value = M.getValue();
3839
3840 // There should be one space between the macro name and the macro value in
3841 // define entries. In undef entries, only the macro name is emitted.
3842 std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
3843
3844 if (UseDebugMacroSection) {
3845 if (getDwarfVersion() >= 5) {
3846 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3847 ? dwarf::DW_MACRO_define_strx
3848 : dwarf::DW_MACRO_undef_strx;
3849 Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
3850 Asm->emitULEB128(Type);
3851 Asm->OutStreamer->AddComment("Line Number");
3852 Asm->emitULEB128(M.getLine());
3853 Asm->OutStreamer->AddComment("Macro String");
3854 Asm->emitULEB128(
3855 InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());
3856 } else {
3857 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3858 ? dwarf::DW_MACRO_GNU_define_indirect
3859 : dwarf::DW_MACRO_GNU_undef_indirect;
3860 Asm->OutStreamer->AddComment(dwarf::GnuMacroString(Type));
3861 Asm->emitULEB128(Type);
3862 Asm->OutStreamer->AddComment("Line Number");
3863 Asm->emitULEB128(M.getLine());
3864 Asm->OutStreamer->AddComment("Macro String");
3865 Asm->emitDwarfSymbolReference(
3866 InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol());
3867 }
3868 } else {
3869 Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
3870 Asm->emitULEB128(M.getMacinfoType());
3871 Asm->OutStreamer->AddComment("Line Number");
3872 Asm->emitULEB128(M.getLine());
3873 Asm->OutStreamer->AddComment("Macro String");
3874 Asm->OutStreamer->emitBytes(Str);
3875 Asm->emitInt8('\0');
3876 }
3877}
3878
3879void DwarfDebug::emitMacroFileImpl(
3880 DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
3881 StringRef (*MacroFormToString)(unsigned Form)) {
3882
3883 Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
3884 Asm->emitULEB128(StartFile);
3885 Asm->OutStreamer->AddComment("Line Number");
3886 Asm->emitULEB128(MF.getLine());
3887 Asm->OutStreamer->AddComment("File Number");
3888 DIFile &F = *MF.getFile();
3889 if (useSplitDwarf())
3890 Asm->emitULEB128(getDwoLineTable(U)->getFile(
3891 F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),
3892 Asm->OutContext.getDwarfVersion(), F.getSource()));
3893 else
3894 Asm->emitULEB128(U.getOrCreateSourceID(&F));
3895 handleMacroNodes(MF.getElements(), U);
3896 Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
3897 Asm->emitULEB128(EndFile);
3898}
3899
3900void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
3901 // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
3902 // so for readibility/uniformity, We are explicitly emitting those.
3903 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
3904 if (UseDebugMacroSection)
3905 emitMacroFileImpl(
3906 F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
3908 else
3909 emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
3911}
3912
3913void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
3914 for (const auto &P : CUMap) {
3915 auto &TheCU = *P.second;
3916 auto *SkCU = TheCU.getSkeleton();
3917 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
3918 auto *CUNode = cast<DICompileUnit>(P.first);
3919 DIMacroNodeArray Macros = CUNode->getMacros();
3920 if (Macros.empty())
3921 continue;
3922 Asm->OutStreamer->switchSection(Section);
3923 Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
3924 if (UseDebugMacroSection)
3925 emitMacroHeader(Asm, *this, U, getDwarfVersion());
3926 handleMacroNodes(Macros, U);
3927 Asm->OutStreamer->AddComment("End Of Macro List Mark");
3928 Asm->emitInt8(0);
3929 }
3930}
3931
3932/// Emit macros into a debug macinfo/macro section.
3933void DwarfDebug::emitDebugMacinfo() {
3934 auto &ObjLower = Asm->getObjFileLowering();
3935 emitDebugMacinfoImpl(UseDebugMacroSection
3936 ? ObjLower.getDwarfMacroSection()
3937 : ObjLower.getDwarfMacinfoSection());
3938}
3939
3940void DwarfDebug::emitDebugMacinfoDWO() {
3941 auto &ObjLower = Asm->getObjFileLowering();
3942 emitDebugMacinfoImpl(UseDebugMacroSection
3943 ? ObjLower.getDwarfMacroDWOSection()
3944 : ObjLower.getDwarfMacinfoDWOSection());
3945}
3946
3947// DWARF5 Experimental Separate Dwarf emitters.
3948
3949void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
3950 std::unique_ptr<DwarfCompileUnit> NewU) {
3951
3952 if (!CompilationDir.empty())
3953 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
3954 addGnuPubAttributes(*NewU, Die);
3955
3956 SkeletonHolder.addUnit(std::move(NewU));
3957}
3958
3959DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
3960
3961 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
3962 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
3964 DwarfCompileUnit &NewCU = *OwnedUnit;
3965 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
3966
3967 NewCU.initStmtList();
3968
3970 NewCU.addStringOffsetsStart();
3971
3972 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
3973
3974 return NewCU;
3975}
3976
3977// Emit the .debug_info.dwo section for separated dwarf. This contains the
3978// compile units that would normally be in debug_info.
3979void DwarfDebug::emitDebugInfoDWO() {
3980 assert(useSplitDwarf() && "No split dwarf debug info?");
3981 // Don't emit relocations into the dwo file.
3982 InfoHolder.emitUnits(/* UseOffsets */ true);
3983}
3984
3985// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3986// abbreviations for the .debug_info.dwo section.
3987void DwarfDebug::emitDebugAbbrevDWO() {
3988 assert(useSplitDwarf() && "No split dwarf?");
3989 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3990}
3991
3992void DwarfDebug::emitDebugLineDWO() {
3993 assert(useSplitDwarf() && "No split dwarf?");
3994 SplitTypeUnitFileTable.Emit(
3995 *Asm->OutStreamer, MCDwarfLineTableParams(),
3996 Asm->getObjFileLowering().getDwarfLineDWOSection());
3997}
3998
3999void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
4000 assert(useSplitDwarf() && "No split dwarf?");
4001 InfoHolder.getStringPool().emitStringOffsetsTableHeader(
4002 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
4003 InfoHolder.getStringOffsetsStartSym());
4004}
4005
4006// Emit the .debug_str.dwo section for separated dwarf. This contains the
4007// string section and is identical in format to traditional .debug_str
4008// sections.
4009void DwarfDebug::emitDebugStrDWO() {
4011 emitStringOffsetsTableHeaderDWO();
4012 assert(useSplitDwarf() && "No split dwarf?");
4013 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
4014 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
4015 OffSec, /* UseRelativeOffsets = */ false);
4016}
4017
4018// Emit address pool.
4019void DwarfDebug::emitDebugAddr() {
4020 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
4021}
4022
4023MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
4024 if (!useSplitDwarf())
4025 return nullptr;
4026 const DICompileUnit *DIUnit = CU.getCUNode();
4027 SplitTypeUnitFileTable.maybeSetRootFile(
4028 DIUnit->getDirectory(), DIUnit->getFilename(),
4029 getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
4030 return &SplitTypeUnitFileTable;
4031}
4032
4034 MD5 Hash;
4035 Hash.update(Identifier);
4036 // ... take the least significant 8 bytes and return those. Our MD5
4037 // implementation always returns its results in little endian, so we actually
4038 // need the "high" word.
4039 MD5::MD5Result Result;
4040 Hash.final(Result);
4041 return Result.high();
4042}
4043
4045 StringRef Identifier, DIE &RefDie,
4046 const DICompositeType *CTy) {
4047 // Fast path if we're building some type units and one has already used the
4048 // address pool we know we're going to throw away all this work anyway, so
4049 // don't bother building dependent types.
4050 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
4051 return;
4052
4053 auto Ins = TypeSignatures.try_emplace(CTy);
4054 if (!Ins.second) {
4055 CU.addDIETypeSignature(RefDie, Ins.first->second);
4056 return;
4057 }
4058
4060 bool TopLevelType = TypeUnitsUnderConstruction.empty();
4061 AddrPool.resetUsedFlag();
4062
4063 auto OwnedUnit = std::make_unique<DwarfTypeUnit>(
4064 CU, Asm, this, &InfoHolder, NumTypeUnitsCreated++, getDwoLineTable(CU));
4065 DwarfTypeUnit &NewTU = *OwnedUnit;
4066 DIE &UnitDie = NewTU.getUnitDie();
4067 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
4068
4069 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
4070 CU.getSourceLanguage());
4071
4072 uint64_t Signature = makeTypeSignature(Identifier);
4073 NewTU.setTypeSignature(Signature);
4074 Ins.first->second = Signature;
4075
4076 if (useSplitDwarf()) {
4077 // Although multiple type units can have the same signature, they are not
4078 // guranteed to be bit identical. When LLDB uses .debug_names it needs to
4079 // know from which CU a type unit came from. These two attrbutes help it to
4080 // figure that out.
4081 if (getDwarfVersion() >= 5) {
4082 if (!CompilationDir.empty())
4083 NewTU.addString(UnitDie, dwarf::DW_AT_comp_dir, CompilationDir);
4084 NewTU.addString(UnitDie, dwarf::DW_AT_dwo_name,
4085 Asm->TM.Options.MCOptions.SplitDwarfFile);
4086 }
4087 MCSection *Section =
4088 getDwarfVersion() <= 4
4089 ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
4090 : Asm->getObjFileLowering().getDwarfInfoDWOSection();
4091 NewTU.setSection(Section);
4092 } else {
4093 MCSection *Section =
4094 getDwarfVersion() <= 4
4095 ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
4096 : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
4097 NewTU.setSection(Section);
4098 // Non-split type units reuse the compile unit's line table.
4099 CU.applyStmtList(UnitDie);
4100 }
4101
4102 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
4103 // units.
4105 NewTU.addStringOffsetsStart();
4106
4107 NewTU.setType(NewTU.createTypeDIE(CTy));
4108
4109 if (TopLevelType) {
4110 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
4111 TypeUnitsUnderConstruction.clear();
4112
4113 // Types referencing entries in the address table cannot be placed in type
4114 // units.
4115 if (AddrPool.hasBeenUsed()) {
4116 AccelTypeUnitsDebugNames.clear();
4117 // Remove all the types built while building this type.
4118 // This is pessimistic as some of these types might not be dependent on
4119 // the type that used an address.
4120 for (const auto &TU : TypeUnitsToAdd)
4121 TypeSignatures.erase(TU.second);
4122
4123 // Construct this type in the CU directly.
4124 // This is inefficient because all the dependent types will be rebuilt
4125 // from scratch, including building them in type units, discovering that
4126 // they depend on addresses, throwing them out and rebuilding them.
4128 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
4129 CU.updateAcceleratorTables(CTy->getScope(), CTy, RefDie);
4130 return;
4131 }
4132
4133 // If the type wasn't dependent on fission addresses, finish adding the type
4134 // and all its dependent types.
4135 for (auto &TU : TypeUnitsToAdd) {
4136 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
4137 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
4138 if (getDwarfVersion() >= 5 &&
4140 if (useSplitDwarf())
4141 AccelDebugNames.addTypeUnitSignature(*TU.first);
4142 else
4143 AccelDebugNames.addTypeUnitSymbol(*TU.first);
4144 }
4145 }
4146 AccelTypeUnitsDebugNames.convertDieToOffset();
4147 AccelDebugNames.addTypeEntries(AccelTypeUnitsDebugNames);
4148 AccelTypeUnitsDebugNames.clear();
4150 }
4151 CU.addDIETypeSignature(RefDie, Signature);
4152}
4153
4154// Add the Name along with its companion DIE to the appropriate accelerator
4155// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
4156// AccelTableKind::Apple, we use the table we got as an argument). If
4157// accelerator tables are disabled, this function does nothing.
4158template <typename DataT>
4159void DwarfDebug::addAccelNameImpl(
4160 const DwarfUnit &Unit,
4161 const DICompileUnit::DebugNameTableKind NameTableKind,
4162 AccelTable<DataT> &AppleAccel, StringRef Name, const DIE &Die) {
4164 Unit.getUnitDie().getTag() == dwarf::DW_TAG_skeleton_unit || Name.empty())
4165 return;
4166
4170 return;
4171
4172 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
4174
4175 switch (getAccelTableKind()) {
4177 AppleAccel.addName(Ref, Die);
4178 break;
4179 case AccelTableKind::Dwarf: {
4181 assert(((&Current == &AccelTypeUnitsDebugNames) ||
4182 ((&Current == &AccelDebugNames) &&
4183 (Unit.getUnitDie().getTag() != dwarf::DW_TAG_type_unit))) &&
4184 "Kind is CU but TU is being processed.");
4185 assert(((&Current == &AccelDebugNames) ||
4186 ((&Current == &AccelTypeUnitsDebugNames) &&
4187 (Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit))) &&
4188 "Kind is TU but CU is being processed.");
4189 // The type unit can be discarded, so need to add references to final
4190 // acceleration table once we know it's complete and we emit it.
4191 Current.addName(Ref, Die, Unit.getUniqueID(),
4192 Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit);
4193 break;
4194 }
4196 llvm_unreachable("Default should have already been resolved.");
4198 llvm_unreachable("None handled above");
4199 }
4200}
4201
4203 const DwarfUnit &Unit,
4204 const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
4205 const DIE &Die) {
4206 addAccelNameImpl(Unit, NameTableKind, AccelNames, Name, Die);
4207}
4208
4210 const DwarfUnit &Unit,
4211 const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
4212 const DIE &Die) {
4213 // ObjC names go only into the Apple accelerator tables.
4215 addAccelNameImpl(Unit, NameTableKind, AccelObjC, Name, Die);
4216}
4217
4219 const DwarfUnit &Unit,
4220 const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
4221 const DIE &Die) {
4222 addAccelNameImpl(Unit, NameTableKind, AccelNamespace, Name, Die);
4223}
4224
4226 const DwarfUnit &Unit,
4227 const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
4228 const DIE &Die, char Flags) {
4229 addAccelNameImpl(Unit, NameTableKind, AccelTypes, Name, Die);
4230}
4231
4233 return Asm->OutStreamer->getContext().getDwarfVersion();
4234}
4235
4237 if (Asm->getDwarfVersion() >= 4)
4238 return dwarf::Form::DW_FORM_sec_offset;
4239 assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&
4240 "DWARF64 is not defined prior DWARFv3");
4241 return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
4242 : dwarf::Form::DW_FORM_data4;
4243}
4244
4246 return SectionLabels.lookup(S);
4247}
4248
4250 if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
4251 if (useSplitDwarf() || getDwarfVersion() >= 5)
4252 AddrPool.getIndex(S);
4253}
4254
4255std::optional<MD5::MD5Result>
4257 assert(File);
4258 if (getDwarfVersion() < 5)
4259 return std::nullopt;
4260 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
4261 if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
4262 return std::nullopt;
4263
4264 // Convert the string checksum to an MD5Result for the streamer.
4265 // The verifier validates the checksum so we assume it's okay.
4266 // An MD5 checksum is 16 bytes.
4267 std::string ChecksumString = fromHex(Checksum->Value);
4268 MD5::MD5Result CKMem;
4269 llvm::copy(ChecksumString, CKMem.data());
4270 return CKMem;
4271}
4272
4274 if (MinimizeAddr == MinimizeAddrInV5::Ranges)
4275 return true;
4276 if (MinimizeAddr != MinimizeAddrInV5::Default)
4277 return false;
4278 if (useSplitDwarf())
4279 return true;
4280 return false;
4281}
4282
4284 if (MBB.getAlignment() == Align(1))
4285 return;
4286
4287 auto *SP = MBB.getParent()->getFunction().getSubprogram();
4288 bool NoDebug =
4289 !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
4290
4291 if (NoDebug)
4292 return;
4293
4294 auto PrevLoc = Asm->OutStreamer->getContext().getCurrentDwarfLoc();
4295 if (PrevLoc.getLine()) {
4296 Asm->OutStreamer->emitDwarfLocDirective(
4297 PrevLoc.getFileNum(), 0, PrevLoc.getColumn(), 0, 0, 0, StringRef());
4298 MCDwarfLineEntry::make(Asm->OutStreamer.get(),
4299 Asm->OutStreamer->getCurrentSectionOnly());
4300 }
4301}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
BitTracker BT
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define clEnumVal(ENUMVAL, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
@ EndOfList
static bool isObjCClass(StringRef Name)
static cl::opt< bool > NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden, cl::desc("Disable emission .debug_ranges section."), cl::init(false))
static void finishCallSiteParams(ValT Val, const DIExpression *Expr, ArrayRef< FwdRegParamInfo > DescribedParams, ParamSet &Params)
Emit call site parameter entries that are described by the given value and debug expression.
static cl::opt< bool > UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden, cl::desc("Emit the GNU .debug_macro format with DWARF <5"), cl::init(false))
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))
static bool validThroughout(LexicalScopes &LScopes, const MachineInstr *DbgValue, const MachineInstr *RangeEnd, const InstructionOrdering &Ordering)
Determine whether a singular DBG_VALUE is valid for the entirety of its enclosing lexical scope.
static cl::opt< bool > GenerateARangeSection("generate-arange-section", cl::Hidden, cl::desc("Generate dwarf aranges"), cl::init(false))
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))
static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg, const DIExpression *Expr, ArrayRef< FwdRegParamInfo > ParamsToAdd)
Add Reg to the worklist, if it's not already present, and mark that the given parameter registers' va...
static cl::opt< bool > GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, cl::desc("Generate DWARF4 type units."), cl::init(false))
SmallSet< MCRegUnit, 16 > ClobberedRegUnitSet
Container for the set of register units known to be clobbered on the path to a call site.
static cl::opt< bool > KeyInstructionsAreStmts("dwarf-use-key-instructions", cl::Hidden, cl::init(true), cl::desc("Set to false to ignore Key Instructions metadata"))
Set to false to ignore Key Instructions metadata.
static bool interpretNextInstr(const MachineInstr *CurMI, FwdRegWorklist &ForwardedRegWorklist, ParamSet &Params, ClobberedRegUnitSet &ClobberedRegUnits)
static SmallVectorImpl< DwarfCompileUnit::GlobalExpr > & sortGlobalExprs(SmallVectorImpl< DwarfCompileUnit::GlobalExpr > &GVEs)
Sort and unique GVEs by comparing their fragment offset.
LinkageNameOption
@ DefaultLinkageNames
@ AbstractLinkageNames
@ AllLinkageNames
static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, const DIE *Die)
computeIndexValue - Compute the gdb index value for the DIE and CU.
static uint64_t getFragmentOffsetInBits(const DIExpression &Expr)
static cl::opt< DefaultOnOff > DwarfOpConvert("dwarf-op-convert", cl::Hidden, cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"), cl::values(clEnumVal(Default, "Default for platform"), clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), cl::init(Default))
static std::pair< const MachineInstr *, bool > findPrologueEndLoc(const MachineFunction *MF)
static void collectCallSiteParameters(const MachineInstr *CallMI, ParamSet &Params)
Try to interpret values loaded into registers that forward parameters for CallMI.
static MCSymbol * emitRnglistsTableHeader(AsmPrinter *Asm, const DwarfFile &Holder)
static cl::opt< bool > SplitDwarfCrossCuReferences("split-dwarf-cross-cu-references", cl::Hidden, cl::desc("Enable cross-cu references in DWO files"), cl::init(false))
MapVector< uint64_t, SmallVector< FwdRegParamInfo, 2 > > FwdRegWorklist
Register worklist for finding call site values.
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))
static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List)
static constexpr unsigned ULEB128PadSize
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))
DefaultOnOff
@ Default
@ Enable
@ Disable
static AccelTableKind computeAccelTableKind(unsigned DwarfVersion, bool GenerateTypeUnits, DebuggerKind Tuning, const Triple &TT)
static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R, const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair, unsigned StartxLength, unsigned StartxEndx, unsigned EndOfList, StringRef(*StringifyEnum)(unsigned), bool ShouldUseBaseAddress, PayloadEmitter EmitPayload)
static void forBothCUs(DwarfCompileUnit &CU, Func F)
static MCSymbol * emitLoclistsTableHeader(AsmPrinter *Asm, const DwarfDebug &DD)
static const DILocalScope * getRetainedNodeScope(const MDNode *N)
static const DIExpression * combineDIExpressions(const DIExpression *Original, const DIExpression *Addition)
Append the expression Addition to Original and return the result.
static void interpretValues(const MachineInstr *CurMI, FwdRegWorklist &ForwardedRegWorklist, ParamSet &Params, ClobberedRegUnitSet &ClobberedRegUnits)
Interpret values loaded into registers by CurMI.
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))
static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col, const MDNode *S, unsigned Flags, unsigned CUID, uint16_t DwarfVersion, ArrayRef< std::unique_ptr< DwarfCompileUnit > > DCUs, StringRef Comment={})
Register a source line with debug info.
static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD, const DwarfCompileUnit &CU, uint16_t DwarfVersion)
Emit the header of a DWARF 5 macro section, or the GNU extension for DWARF 4.
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))
static cl::opt< DwarfDebug::MinimizeAddrInV5 > MinimizeAddrInV5Option("minimize-addr-in-v5", cl::Hidden, cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more " "address pool entry sharing to reduce relocations/object size"), cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default", "Default address minimization strategy"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges", "Use rnglists for contiguous ranges if that allows " "using a pre-existing base address"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions, "Expressions", "Use exprloc addrx+offset expressions for any " "address with a prior base address"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Form, "Form", "Use addrx+offset extension form for any address " "with a prior base address"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled", "Stuff")), cl::init(DwarfDebug::MinimizeAddrInV5::Default))
static StringRef getObjCMethodName(StringRef In)
static DbgValueLoc getDebugLocValue(const MachineInstr *MI)
Get .debug_loc entry for the instruction range starting at MI.
static void getObjCClassCategory(StringRef In, StringRef &Class, StringRef &Category)
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define DWARF2_FLAG_IS_STMT
Definition MCDwarf.h:119
#define DWARF2_FLAG_PROLOGUE_END
Definition MCDwarf.h:121
#define DWARF2_FLAG_EPILOGUE_BEGIN
Definition MCDwarf.h:122
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
if(PassOpts->AAPipeline)
static const MCPhysReg CalleeSavedReg
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
static bool isCopy(MachineInstr *MI)
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class recording the (high level) value of a variable.
This class holds an abstract representation of an Accelerator Table, consisting of a sequence of buck...
Definition AccelTable.h:203
void addName(DwarfStringPoolEntryRef Name, Types &&... Args)
Definition AccelTable.h:216
unsigned getIndex(const MCSymbol *Sym, bool TLS=false)
Returns the index into the address pool with the given label/symbol.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
std::vector< T > vec() const
Definition ArrayRef.h:270
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
DwarfDebug * getDwarfDebug()
Definition AsmPrinter.h:290
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:94
MachineFunction * MF
The current machine function.
Definition AsmPrinter.h:109
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition AsmPrinter.h:106
uint16_t getDwarfVersion() const
virtual void emitInt8(uint8_t Byte, const Twine &Comment="")=0
virtual unsigned emitDIERef(const DIE &D)=0
Basic type, like 'int' or 'float'.
bool getDebugInfoForProfiling() const
bool isDebugDirectivesOnly() const
StringRef getFlags() const
StringRef getSDK() const
static LLVM_ABI std::optional< DebugNameTableKind > getNameTableKind(StringRef Str)
unsigned getRuntimeVersion() const
bool getSplitDebugInlining() const
StringRef getSysRoot() const
StringRef getProducer() const
DISourceLanguageName getSourceLanguage() const
uint64_t getDWOId() const
StringRef getSplitDebugFilename() const
static LLVM_ABI std::optional< DebugEmissionKind > getEmissionKind(StringRef Str)
void setSection(MCSection *Section)
Set the section that this DIEUnit will be emitted into.
Definition DIE.h:994
DIE & getUnitDie()
Definition DIE.h:1009
A structured debug information entry.
Definition DIE.h:828
LLVM_ABI DIEValue findAttribute(dwarf::Attribute Attribute) const
Find a value in the DIE with the attribute given.
Definition DIE.cpp:210
LLVM_ABI 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:191
dwarf::Tag getTag() const
Definition DIE.h:864
Holds a DIExpression and keeps track of how many operands have been consumed so far.
DWARF expression.
static LLVM_ABI DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
unsigned getNumElements() const
LLVM_ABI bool isImplicit() const
Return whether this is an implicit location description.
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
static LLVM_ABI std::optional< const DIExpression * > convertToNonVariadicExpression(const DIExpression *Expr)
If Expr is a valid single-location expression, i.e.
ArrayRef< uint64_t > getElements() const
LLVM_ABI bool isValid() const
A scope for locals.
LLVM_ABI DILocalScope * getNonLexicalBlockFileScope() const
Get the first non DILexicalBlockFile scope of this scope.
uint64_t getAtomGroup() const
uint8_t getAtomRank() const
DIFile * getFile() const
unsigned getLine() const
DIMacroNodeArray getElements() const
Tagged DWARF-like metadata node.
StringRef getFilename() const
DIFile * getFile() const
StringRef getDirectory() const
std::optional< StringRef > getSource() const
Subprogram description. Uses SubclassData1.
static DILocalScope * getRetainedNodeScope(MDNode *N)
Base class for types.
DIScope * getScope() const
DIType * getType() const
A DWARFDataExtractor (typically for an in-memory copy of an object-file section) plus a relocation ma...
Encoding
Size and signedness of expression operations' operands.
Used for tracking debug info about call site parameters.
Definition DwarfDebug.h:317
This class is defined as the common parent of DbgVariable and DbgLabel such that it could levarage po...
Definition DwarfDebug.h:66
A single location or constant within a variable location description, with either a single entry (wit...
The location of a single variable, composed of an expression and 0 or more DbgValueLocEntries.
const DILocalVariable * getVariable() const
Definition DwarfDebug.h:247
const DIType * getType() const
const MachineInstr * CurMI
If nonnull, stores the current machine instruction we're processing.
AsmPrinter * Asm
Target of debug info emission.
MCSymbol * getLabelBeforeInsn(const MachineInstr *MI)
Return Label preceding the instruction.
MachineModuleInfo * MMI
Collected machine module information.
DebugLoc PrevInstLoc
Previous instruction's location information.
MCSymbol * getLabelAfterInsn(const MachineInstr *MI)
Return Label immediately following the instruction.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
const MachineBasicBlock * PrevInstBB
void requestLabelAfterInsn(const MachineInstr *MI)
Ensure that a label will be emitted after MI.
DbgValueHistoryMap DbgValues
History of DBG_VALUE and clobber instructions for each user variable.
DbgLabelInstrMap DbgLabels
Mapping of inlined labels and DBG_LABEL machine instruction.
void beginModule(Module *M) override
const InstructionOrdering & getInstOrdering() const
void requestLabelBeforeInsn(const MachineInstr *MI)
Ensure that a label will be emitted before MI.
const MachineBasicBlock * EpilogBeginBlock
This block includes epilogue instructions.
const MachineInstr * PrologEndLoc
This location indicates end of function prologue and beginning of function body.
DwarfExpression implementation for .debug_loc entries.
void finalize(const AsmPrinter &AP, DebugLocStream::ListBuilder &List, const DIBasicType *BT, DwarfCompileUnit &TheCU)
Lower this entry into a DWARF expression.
Builder for DebugLocStream entries.
Builder for DebugLocStream lists.
ArrayRef< Entry > getEntries(const List &L) const
A debug info location.
Definition DebugLoc.h:124
LLVM_ABI unsigned getLine() const
Definition DebugLoc.cpp:40
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:205
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
bool erase(const KeyT &Val)
Definition DenseMap.h:332
iterator end()
Definition DenseMap.h:85
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:239
Implements a dense probed hash-table based set.
Definition DenseSet.h:289
void addRange(RangeSpan Range)
addRange - Add an address range to the list of ranges for this unit.
DIE & constructSubprogramScopeDIE(const DISubprogram *Sub, const Function &F, LexicalScope *Scope, MCSymbol *LineTableSym)
Construct a DIE for this subprogram scope.
void createAbstractEntity(const DINode *Node, LexicalScope *Scope)
DwarfCompileUnit * getSkeleton() const
void setSkeleton(DwarfCompileUnit &Skel)
Set the skeleton unit associated with this unit.
const StringMap< const DIE * > & getGlobalNames() const
DbgEntity * getExistingAbstractEntity(const DINode *Node)
const StringMap< const DIE * > & getGlobalTypes() const
Collects and handles dwarf debug information.
Definition DwarfDebug.h:352
bool useSegmentedStringOffsetsTable() const
Returns whether to generate a string offsets table with (possibly shared) contributions from each CU ...
Definition DwarfDebug.h:884
virtual bool shouldResetBaseAddress(const MCSection &Section) const
Whether the target requires resetting the base address in range/loc lists.
Definition DwarfDebug.h:751
std::optional< MD5::MD5Result > getMD5AsBytes(const DIFile *File) const
If the File has an MD5 checksum, return it as an MD5Result allocated in the MCContext.
virtual bool shouldAttachCompileUnitRanges() const
Whether to attach ranges/low_pc to the compile unit DIE in endModule.
Definition DwarfDebug.h:732
bool emitDebugEntryValues() const
Definition DwarfDebug.h:888
uint16_t getDwarfVersion() const
Returns the Dwarf Version.
void emitDebugLocEntry(ByteStreamer &Streamer, const DebugLocStream::Entry &Entry, const DwarfCompileUnit *CU)
Emit an entry for the debug loc section.
void addAccelNamespace(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
void setCurrentDWARF5AccelTable(const DWARF5AccelTableKind Kind)
Sets the current DWARF5AccelTable to use.
bool alwaysUseRanges(const DwarfCompileUnit &) const
Returns whether range encodings should be used for single entry range lists.
void beginModule(Module *M) override
Emit all Dwarf sections that should come prior to the content.
void addSubprogramNames(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, const DISubprogram *SP, DIE &Die)
bool useAllLinkageNames() const
Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
Definition DwarfDebug.h:822
void insertSectionLabel(const MCSymbol *S)
void addAccelObjC(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
dwarf::Form getDwarfSectionOffsetForm() const
Returns a suitable DWARF form to represent a section offset, i.e.
bool useAppleExtensionAttributes() const
Definition DwarfDebug.h:870
void skippedNonDebugFunction() override
void addArangeLabel(SymbolCU SCU)
Add a label so that arange data can be generated for it.
Definition DwarfDebug.h:809
virtual void finishTargetUnitAttributes(const DICompileUnit &DIUnit, DwarfCompileUnit &NewCU)
Target-specific compile unit attribute finalization.
Definition DwarfDebug.h:738
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
AddressPool & getAddressPool()
Definition DwarfDebug.h:931
DWARF5AccelTable & getCurrentDWARF5AccelTable()
Returns either CU or TU DWARF5AccelTable.
bool useSectionsAsReferences() const
Returns whether to use sections as labels rather than temp symbols.
Definition DwarfDebug.h:855
const DebugLocStream & getDebugLocs() const
Returns the entries for the .debug_loc section.
Definition DwarfDebug.h:915
bool shareAcrossDWOCUs() const
void terminateLineTable(const DwarfCompileUnit *CU)
Terminate the line table by adding the last range label.
~DwarfDebug() override
void endFunctionImpl(const MachineFunction *MF) override
Gather and emit post-function debug information.
DwarfCompileUnit & getOrCreateAbstractSubprogramCU(const DISubprogram *SP, DwarfCompileUnit &SrcCU)
Find the matching DwarfCompileUnit for the given SP referenced from SrcCU.
void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry, const DwarfCompileUnit *CU)
Emit the location for a debug loc entry, including the size header.
const SmallVectorImpl< std::unique_ptr< DwarfCompileUnit > > & getUnits()
Definition DwarfDebug.h:741
const MCSymbol * getSectionLabel(const MCSection *S)
static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, const DbgValueLoc &Value, DwarfExpression &DwarfExpr)
bool useSplitDwarf() const
Returns whether or not to change the current debug info for the split dwarf proposal support.
Definition DwarfDebug.h:876
virtual void initializeTargetDebugInfo(const MachineFunction &MF)
Target-specific debug info initialization at function start.
Definition DwarfDebug.h:723
unsigned getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU)
Get Dwarf compile unit ID for line table.
const MachineInstr * emitInitialLocDirective(const MachineFunction &MF, unsigned CUID)
Emits inital debug location directive.
bool useRangesSection() const
Returns whether ranges section should be emitted.
Definition DwarfDebug.h:836
void addAccelName(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
virtual void recordTargetSourceLine(const DebugLoc &DL, unsigned Flags)
Target-specific source line recording.
bool isLexicalScopeDIENull(LexicalScope *Scope)
A helper function to check whether the DIE for a given Scope is going to be null.
void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier, DIE &Die, const DICompositeType *CTy)
Add a DIE to the set of types that we're going to pull into type units.
DwarfFile InfoHolder
Holder for the file specific debug information.
Definition DwarfDebug.h:710
void endModule() override
Emit all Dwarf sections that should come after the content.
void addAccelType(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die, char Flags)
void beginCodeAlignment(const MachineBasicBlock &MBB) override
Process beginning of code alignment.
DwarfDebug(AsmPrinter *A)
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
AccelTableKind getAccelTableKind() const
Returns what kind (if any) of accelerator tables to emit.
Definition DwarfDebug.h:865
static uint64_t makeTypeSignature(StringRef Identifier)
Perform an MD5 checksum of Identifier and return the lower 64 bits.
Base class containing the logic for constructing DWARF expressions independently of whether they are ...
void setLocation(const MachineLocation &Loc, const DIExpression *DIExpr)
Set the location (Loc) and DIExpression (DIExpr) to describe.
virtual void disableTemporaryBuffer()=0
Disable emission to the temporary buffer.
virtual unsigned getTemporaryBufferSize()=0
Return the emitted size, in number of bytes, for the data stored in the temporary buffer.
void finalize()
This needs to be called last to commit any pending changes.
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...
void setMemoryLocationKind()
Lock this down to become a memory location description.
std::optional< uint8_t > TagOffset
void addBooleanConstant(int64_t Value)
Emit a boolean constant.
void addConstantFP(const APFloat &Value, const AsmPrinter &AP)
Emit an floating point constant.
bool addMachineRegExpression(const TargetRegisterInfo &TRI, DIExpressionCursor &Expr, llvm::Register MachineReg, unsigned FragmentOffsetInBits=0)
Emit a machine register location.
void addUnsignedConstant(uint64_t Value)
Emit an unsigned constant.
void addExpression(DIExpressionCursor &&Expr)
Emit all remaining operations in the DIExpressionCursor.
void addSignedConstant(int64_t Value)
Emit a signed constant.
virtual void commitTemporaryBuffer()=0
Commit the data stored in the temporary buffer to the main output.
void addWasmLocation(unsigned Index, uint64_t Offset)
Emit location information expressed via WebAssembly location + offset The Index is an identifier for ...
virtual void enableTemporaryBuffer()=0
Start emitting data to the temporary buffer.
void beginEntryValueExpression(DIExpressionCursor &ExprCursor)
Begin emission of an entry value dwarf operation.
void setRnglistsTableBaseSym(MCSymbol *Sym)
Definition DwarfFile.h:160
void emitUnits(bool UseOffsets)
Emit all of the units to the section listed with the given abbreviation section.
Definition DwarfFile.cpp:29
const SmallVectorImpl< RangeSpanList > & getRangeLists() const
getRangeLists - Get the vector of range lists.
Definition DwarfFile.h:119
MCSymbol * getStringOffsetsStartSym() const
Definition DwarfFile.h:156
MCSymbol * getRnglistsTableBaseSym() const
Definition DwarfFile.h:159
DwarfStringPool & getStringPool()
Returns the string pool.
Definition DwarfFile.h:154
void emitAbbrevs(MCSection *)
Emit a set of abbreviations to the specific section.
Definition DwarfFile.cpp:97
void emitStrings(MCSection *StrSection, MCSection *OffsetSection=nullptr, bool UseRelativeOffsets=false)
Emit all of the strings to the section given.
DwarfStringPoolEntryRef: Dwarf string pool entry reference.
LLVM_ABI_FOR_TEST EntryRef getEntry(AsmPrinter &Asm, StringRef Str)
Get a reference to an entry in the string pool.
LLVM_ABI_FOR_TEST void emitStringOffsetsTableHeader(AsmPrinter &Asm, MCSection *OffsetSection, MCSymbol *StartSym)
void setTypeSignature(uint64_t Signature)
Definition DwarfUnit.h:434
void setType(const DIE *Ty)
Definition DwarfUnit.h:437
This dwarf writer support class manages information associated with a source file.
Definition DwarfUnit.h:36
void addStringOffsetsStart()
Add the DW_AT_str_offsets_base attribute to the unit DIE.
void addUInt(DIEValueList &Die, dwarf::Attribute Attribute, std::optional< dwarf::Form > Form, uint64_t Integer)
Add an unsigned integer attribute data and value.
void addString(DIE &Die, dwarf::Attribute Attribute, StringRef Str)
Add a string attribute data and value.
DIE * createTypeDIE(const DIScope *Context, DIE &ContextDIE, const DIType *Ty)
Creates type DIE with specific context.
const DICompileUnit * getCUNode() const
Definition DwarfUnit.h:112
void addFlag(DIE &Die, dwarf::Attribute Attribute)
Add a flag that is true to the DIE.
unsigned getUniqueID() const
Gets Unique ID for this unit.
Definition DwarfUnit.h:102
DISubprogram * getSubprogram() const
Get the attached subprogram.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:358
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool isTailCall(const MachineInstr &MI) const override
Record instruction ordering so we can query their relative positions within a function.
This class is used to track scope information.
SmallVectorImpl< InsnRange > & getRanges()
const DILocalScope * getScopeNode() const
This class provides interface to collect and use lexical scoping information from machine instruction...
LLVM_ABI LexicalScope * findLexicalScope(const DILocation *DL)
Find lexical scope, either regular or inlined, for the given DebugLoc.
LexicalScope * findAbstractScope(const DILocalScope *N)
Find an abstract scope or return null.
Single(DbgValueLoc ValueLoc)
static LLVM_ABI void make(MCStreamer *MCOS, MCSection *Section)
Definition MCDwarf.cpp:91
MCSection * getDwarfLoclistsSection() const
MCSection * getDwarfRangesSection() const
MCSection * getDwarfMacroSection() const
MCSection * getDwarfMacinfoDWOSection() const
MCSection * getDwarfMacinfoSection() const
MCSection * getDwarfMacroDWOSection() const
static constexpr unsigned NoRegister
Definition MCRegister.h:60
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:573
MCSymbol * getBeginSymbol()
Definition MCSection.h:646
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
uint32_t getIndex() const
Get the (implementation defined) index.
Definition MCSymbol.h:280
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition MCSymbol.h:251
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:188
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:233
Metadata node.
Definition Metadata.h:1075
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< const MachineInstr, true > const_reverse_iterator
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const CallSiteInfoMap & getCallSitesInfo() const
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
bool isCall(QueryType Type=AnyInBundle) const
bool isBundle() const
unsigned getNumOperands() const
Retuns the total number of operands.
bool hasDelaySlot(QueryType Type=AnyInBundle) const
Returns true if the specified instruction has a delay slot which must be filled by the code generator...
mop_range uses()
Returns all operands which may be register uses.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
bool isDebugValue() const
unsigned getReg() const
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
Register getReg() const
getReg - Returns the register number.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator begin()
Definition MapVector.h:67
iterator end()
Definition MapVector.h:69
bool empty() const
Definition MapVector.h:79
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition MapVector.h:210
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
void insert_range(Range &&R)
Definition SmallSet.h:196
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
TargetInstrInfo - Interface to description of machine instruction set.
const Triple & getTargetTriple() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
bool isWasm() const
Tests whether the target is wasm (32- and 64-bit).
Definition Triple.h:1125
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
void insert_range(Range &&R)
Definition DenseSet.h:238
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:190
reverse_self_iterator getReverseIterator()
Definition ilist_node.h:126
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an SmallVector or SmallString.
bool tuneForSCE() const
Definition DwarfDebug.h:981
bool tuneForDBX() const
Definition DwarfDebug.h:982
bool tuneForGDB() const
Definition DwarfDebug.h:979
bool tuneForLLDB() const
Definition DwarfDebug.h:980
LLVM_ABI StringRef RangeListEncodingString(unsigned Encoding)
Definition Dwarf.cpp:764
LLVM_ABI StringRef GDBIndexEntryLinkageString(GDBIndexEntryLinkage Linkage)
Definition Dwarf.cpp:879
LLVM_ABI StringRef MacroString(unsigned Encoding)
Definition Dwarf.cpp:736
LLVM_ABI StringRef LocListEncodingString(unsigned Encoding)
Definition Dwarf.cpp:775
LLVM_ABI StringRef GnuMacroString(unsigned Encoding)
Definition Dwarf.cpp:747
LLVM_ABI StringRef MacinfoString(unsigned Encoding)
Definition Dwarf.cpp:707
LLVM_ABI StringRef OperationEncodingString(unsigned Encoding)
Definition Dwarf.cpp:138
LLVM_ABI StringRef GDBIndexEntryKindString(GDBIndexEntryKind Kind)
Definition Dwarf.cpp:856
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
Attribute
Attributes.
Definition Dwarf.h:125
@ DWARF64
Definition Dwarf.h:93
@ DWARF32
Definition Dwarf.h:93
@ DW_MACINFO_start_file
Definition Dwarf.h:825
@ DW_MACINFO_end_file
Definition Dwarf.h:826
@ DW_MACINFO_define
Definition Dwarf.h:823
@ GIEK_NONE
Definition Dwarf.h:978
@ GIEK_TYPE
Definition Dwarf.h:979
@ GIEK_FUNCTION
Definition Dwarf.h:981
@ GIEK_VARIABLE
Definition Dwarf.h:980
bool isCPlusPlus(SourceLanguage S)
Definition Dwarf.h:518
@ DW_ARANGES_VERSION
Section version number for .debug_aranges.
Definition Dwarf.h:66
@ DW_PUBNAMES_VERSION
Section version number for .debug_pubnames.
Definition Dwarf.h:65
@ DWARF_VERSION
Other constants.
Definition Dwarf.h:63
GDBIndexEntryLinkage
Definition Dwarf.h:988
@ GIEL_EXTERNAL
Definition Dwarf.h:988
@ GIEL_STATIC
Definition Dwarf.h:988
LLVM_ABI MCSymbol * emitListsTableHeaderStart(MCStreamer &S)
Definition MCDwarf.cpp:44
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
bool empty() const
Definition BasicBlock.h:101
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
@ Length
Definition DWP.cpp:558
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
MachineBasicBlock::instr_iterator getBundleStart(MachineBasicBlock::instr_iterator I)
Returns an iterator to the first instruction in the bundle containing I.
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:1738
std::string fromHex(StringRef Input)
Convert hexadecimal string Input to its binary representation. The return string is half the size of ...
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2553
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isRangeRelaxable(const MCSymbol *Begin, const MCSymbol *End)
Definition MCSymbol.cpp:94
auto cast_or_null(const Y &Val)
Definition Casting.h:714
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2133
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
Op::Description Desc
SmallVector< DbgCallSiteParam, 4 > ParamSet
Collection used for storing debug call site parameters.
Definition DwarfDebug.h:333
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2199
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:1745
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
AccelTableKind
The kind of accelerator tables we should emit.
Definition DwarfDebug.h:344
@ Default
Platform default.
Definition DwarfDebug.h:345
@ Apple
.apple_names, .apple_namespaces, .apple_types, .apple_objc.
Definition DwarfDebug.h:347
@ Dwarf
DWARF v5 .debug_names.
Definition DwarfDebug.h:348
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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:1752
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
MachineBasicBlock::instr_iterator getBundleEnd(MachineBasicBlock::instr_iterator I)
Returns an iterator pointing beyond the bundle containing I.
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1969
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
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:186
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
auto remove_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1783
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
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:449
DWARFExpression::Operation Op
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1884
LLVM_ABI void emitDWARF5AccelTable(AsmPrinter *Asm, DWARF5AccelTable &Contents, const DwarfDebug &DD, ArrayRef< std::unique_ptr< DwarfCompileUnit > > CUs)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2191
DebuggerKind
Identify a debugger for "tuning" the debug info.
@ SCE
Tune debug info for SCE targets (e.g. PS4).
@ DBX
Tune debug info for dbx.
@ Default
No specific tuning requested.
@ GDB
Tune debug info for gdb.
@ LLDB
Tune debug info for lldb.
@ Enable
Enable colors.
Definition WithColor.h:47
@ Disable
Disable colors.
Definition WithColor.h:49
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:874
#define N
const MCSymbol * Start
const MCSymbol * End
Represents a parameter whose call site value can be described by applying a debug expression to a reg...
uint64_t ParamReg
The described parameter register.
const DIExpression * Expr
Debug expression that has been built up when walking through the instruction chain that produces the ...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A pair of GlobalVariable and DIExpression.
Represents an entry-value location, or a fragment of one.
Definition DwarfDebug.h:121
Proxy for one MMI entry.
Definition DwarfDebug.h:112
void addFrameIndexExpr(const DIExpression *Expr, int FI)
std::set< FrameIndexExpr > FrameIndexExprs
Definition DwarfDebug.h:161
const std::set< FrameIndexExpr > & getFrameIndexExprs() const
Get the FI entries, sorted by fragment offset.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:334
Helper used to pair up a symbol and its DWARF compile unit.
Definition DwarfDebug.h:336
const MCSymbol * Sym
Definition DwarfDebug.h:339
DwarfCompileUnit * CU
Definition DwarfDebug.h:340
This struct describes target specific location.
Describes an entry of the various gnu_pub* debug sections.
Definition Dwarf.h:1197