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