1//===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===// 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 7//===----------------------------------------------------------------------===// 9// This file contains support for writing dwarf debug info into asm files. 11//===----------------------------------------------------------------------===// 65#define DEBUG_TYPE "dwarfdebug" 67STATISTIC(NumCSParams,
"Number of dbg call site params created");
70"use-dwarf-ranges-base-address-specifier",
cl::Hidden,
80cl::desc(
"Generate DWARF4 type units."),
91cl::desc(
"Make an absence of debug location information explicit."),
99"Default for platform"),
100clEnumValN(AccelTableKind::None,
"Disable",
"Disabled."),
101clEnumValN(AccelTableKind::Apple,
"Apple",
"Apple"),
102clEnumValN(AccelTableKind::Dwarf,
"Dwarf",
"DWARF")),
107cl::desc(
"Use inlined strings rather than string section."),
115cl::desc(
"Disable emission .debug_ranges section."),
120cl::desc(
"Use sections+offset as references rather than labels."),
127cl::desc(
"Emit the GNU .debug_macro format with DWARF <5"),
132cl::desc(
"Enable use of the DWARFv5 DW_OP_convert operator"),
145cl::desc(
"Which DWARF linkage-name attributes to emit."),
147"Default for platform"),
150"Abstract subprograms")),
155cl::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"),
159clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges,
"Ranges",
160"Use rnglists for contiguous ranges if that allows " 161"using a pre-existing base address"),
162clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions,
164"Use exprloc addrx+offset expressions for any " 165"address with a prior base address"),
166clEnumValN(DwarfDebug::MinimizeAddrInV5::Form,
"Form",
167"Use addrx+offset extension form for any address " 168"with a prior base address"),
169clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled,
"Disabled",
171cl::init(DwarfDebug::MinimizeAddrInV5::Default));
175void DebugLocDwarfExpression::emitOp(
uint8_tOp,
constchar *Comment) {
181void DebugLocDwarfExpression::emitSigned(int64_t
Value) {
193void DebugLocDwarfExpression::emitBaseTypeRef(
uint64_tIdx) {
200// This information is not available while emitting .debug_loc entries. 204void DebugLocDwarfExpression::enableTemporaryBuffer() {
205assert(!IsBuffering &&
"Already buffering?");
211void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering =
false; }
213unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
214return TmpBuf ? TmpBuf->Bytes.size() : 0;
217void DebugLocDwarfExpression::commitTemporaryBuffer() {
220for (
auto Byte :
enumerate(TmpBuf->Bytes)) {
221constchar *
Comment = (
Byte.index() < TmpBuf->Comments.size())
222 ? TmpBuf->Comments[
Byte.index()].c_str()
226 TmpBuf->Bytes.clear();
227 TmpBuf->Comments.clear();
234/// Get .debug_loc entry for the instruction range starting at MI. 238constbool IsVariadic = !SingleLocExprOpt;
239// If we have a variadic debug value instruction that is equivalent to a 240// non-variadic instruction, then convert it to non-variadic form here. 241if (!IsVariadic && !
MI->isNonListDebugValue()) {
242assert(
MI->getNumDebugOperands() == 1 &&
243"Mismatched DIExpression and debug operands for debug instruction.");
244 Expr = *SingleLocExprOpt;
251MI->isNonListDebugValue() &&
MI->isDebugOffsetImm());
253 }
elseif (
Op.isTargetIndex()) {
265returnDbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);
269 std::optional<DIExpression::FragmentInfo> Fragment = Expr.
getFragmentInfo();
270return Fragment ? Fragment->OffsetInBits : 0;
284 Expr(ValueLoc.getExpression()) {
293return FrameIndexExprs;
297 FrameIndexExprs.insert({FI, Expr});
298assert((FrameIndexExprs.size() == 1 ||
301 return FIE.Expr && FIE.Expr->isFragment();
303"conflicting locations for variable");
307bool GenerateTypeUnits,
310// Honor an explicit request. 314// Generating DWARF5 acceleration table. 315// Currently Split dwarf and non ELF format is not supported. 316if (GenerateTypeUnits && (DwarfVersion < 5 || !TT.isOSBinFormatELF()))
319// Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5 320// always implies debug_names. For lower standard versions we use apple 321// accelerator tables on apple platforms and debug_names elsewhere. 322if (DwarfVersion >= 5)
332 InfoHolder(
A,
"info_string", DIEValueAllocator),
333 SkeletonHolder(
A,
"skel_string", DIEValueAllocator),
334 IsDarwin(
A->TM.getTargetTriple().isOSDarwin()) {
337// Make sure we know our "debugger tuning". The target option takes 338// precedence; fall back to triple-based defaults. 351 UseInlineStrings = TT.isNVPTX() ||
tuneForDBX();
355// Always emit .debug_aranges for SCE tuning. 360// Handle split DWARF. 363// SCE defaults to linkage names only for abstract subprograms. 370unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
372// Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2. 376bool Dwarf64 = DwarfVersion >= 3 &&
// DWARF64 was introduced in DWARFv3. 377 TT.isArch64Bit();
// DWARF64 requires 64-bit relocations. 380// 1: For ELF when requested. 381// 2: For XCOFF64: the AIX assembler will fill in debug section lengths 382// according to the DWARF64 format for 64-bit assembly, so we must use 383// DWARF64 in the compiler too for 64-bit mode. 386 TT.isOSBinFormatELF()) ||
387 TT.isOSBinFormatXCOFF();
389if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())
394// Use sections as references. Force for NVPTX. 396 UseSectionsAsReferences = TT.isNVPTX();
400// Don't generate type units for unsupported object file formats. 401 GenerateTypeUnits = (
A->TM.getTargetTriple().isOSBinFormatELF() ||
402A->TM.getTargetTriple().isOSBinFormatWasm()) &&
406 DwarfVersion, GenerateTypeUnits, DebuggerTuning,
A->TM.getTargetTriple());
408// Work around a GDB bug. GDB doesn't support the standard opcode; 409// SCE doesn't support GNU's; LLDB prefers the standard opcode, which 410// is defined as of DWARF 3. 411// See GDB bug 11616 - DW_OP_form_tls_address is unimplemented 412// https://sourceware.org/bugzilla/show_bug.cgi?id=11616 413 UseGNUTLSOpcode =
tuneForGDB() || DwarfVersion < 3;
415 UseDWARF2Bitfields = DwarfVersion < 4;
417// The DWARF v5 string offsets table has - possibly shared - contributions 418// from each compile and type unit each preceded by a header. The string 419// offsets table used by the pre-DWARF v5 split-DWARF implementation uses 420// a monolithic string offsets table without any header. 421 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
423// Emit call-site-param debug info for GDB and LLDB, if the target supports 424// the debug entry values feature. It can also be enabled explicitly. 427// It is unclear if the GCC .debug_macro extension is well-specified 428// for split DWARF. For now, do not allow LLVM to emit it. 429 UseDebugMacroSection =
436// Split DWARF would benefit object size significantly by trading reductions 437// in address pool usage for slightly increased range list encodings. 438if (DwarfVersion >= 5)
446// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h. 450returnName.starts_with(
"+") ||
Name.starts_with(
"-");
457returnName.contains(
") ");
463 Class = In.slice(In.find(
'[') + 1, In.find(
' '));
468 Class = In.slice(In.find(
'[') + 1, In.find(
'('));
469 Category = In.slice(In.find(
'[') + 1, In.find(
' '));
473return In.slice(In.find(
' ') + 1, In.find(
']'));
476// Add the various names to the Dwarf accelerator table names. 486if (!SP->isDefinition())
492// If the linkage name is different than the name, go ahead and output that as 493// well into the name table. Only do that if we are going to actually emit 495if (SP->getLinkageName() !=
"" && SP->
getName() != SP->getLinkageName() &&
497addAccelName(Unit, NameTableKind, SP->getLinkageName(), Die);
499// If this is an Objective-C selector name add it to the ObjC accelerator 507// Also add the base method name to the name table. 512/// Check whether we should create a DIE for the given Scope, return true 513/// if we don't create a DIE (the corresponding DIE is null). 515if (Scope->isAbstractScope())
518// We don't create a DIE if there is no Range. 526// We don't create a DIE if we have a single Range and the end label 533if (
auto *SkelCU =
CU.getSkeleton())
534if (
CU.getCUNode()->getSplitDebugInlining())
542void DwarfDebug::constructAbstractSubprogramScopeDIE(
DwarfCompileUnit &SrcCU,
544assert(Scope && Scope->getScopeNode());
545assert(Scope->isAbstractScope());
546assert(!Scope->getInlinedAt());
548auto *SP = cast<DISubprogram>(Scope->getScopeNode());
550// Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 551// was inlined from another compile unit. 553// Avoid building the original CU if it won't be used 556auto &
CU = getOrCreateDwarfCompileUnit(SP->getUnit());
557if (
auto *SkelCU =
CU.getSkeleton()) {
559 .constructAbstractSubprogramScopeDIE(Scope);
560if (
CU.getCUNode()->getSplitDebugInlining())
561 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
563CU.constructAbstractSubprogramScopeDIE(Scope);
567/// Represents a parameter whose call site value can be described by applying a 568/// debug expression to a register in the forwarded register worklist. 570 /// The described parameter register. 573 /// Debug expression that has been built up when walking through the 574 /// instruction chain that produces the parameter's value. 578/// Register worklist for finding call site values. 580/// Container for the set of registers known to be clobbered on the path to a 584/// Append the expression \p Addition to \p Original and return the result. 588// Avoid multiple DW_OP_stack_values. 596/// Emit call site parameter entries that are described by the given value and 598template <
typename ValT>
602for (
auto Param : DescribedParams) {
603bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
605// TODO: Entry value operations can currently not be combined with any 606// other expressions, so we can't emit call site entries in those cases. 610// If a parameter's call site value is produced by a chain of 611// instructions we may have already created an expression for the 612// parameter when walking through the instructions. Append that to the 618"Combined debug expression is invalid");
627/// Add \p Reg to the worklist, if it's not already present, and mark that the 628/// given parameter registers' values can (potentially) be described using 629/// that register and an debug expression. 633auto &ParamsForFwdReg = Worklist[Reg];
634for (
auto Param : ParamsToAdd) {
637returnD.ParamReg == Param.ParamReg;
639"Same parameter described twice by forwarding reg");
641// If a parameter's call site value is produced by a chain of 642// instructions we may have already created an expression for the 643// parameter when walking through the instructions. Append that to the 646 ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
650/// Interpret values loaded into registers by \p CurMI. 663// If an instruction defines more than one item in the worklist, we may run 664// into situations where a worklist register's value is (potentially) 665// described by the previous value of another register that is also defined 666// by that instruction. 668// This can for example occur in cases like this: 671// $r0, $r1 = mvrr $r1, 456 672// call @foo, $r0, $r1 674// When describing $r1's value for the mvrr instruction, we need to make sure 675// that we don't finalize an entry value for $r0, as that is dependent on the 676// previous value of $r1 (123 rather than 456). 678// In order to not have to distinguish between those cases when finalizing 679// entry values, we simply postpone adding new parameter registers to the 680// worklist, by first keeping them in this temporary container until the 681// instruction has been handled. 684// If the MI is an instruction defining one or more parameters' forwarding 685// registers, add those defines. 689if (
MI.isDebugInstr())
693if (MO.getReg().isPhysical()) {
694for (
auto &FwdReg : ForwardedRegWorklist)
695if (
TRI.regsOverlap(FwdReg.first, MO.getReg()))
696 Defs.
insert(FwdReg.first);
698 NewClobberedRegUnits.
insert(Unit);
703// Set of worklist registers that are defined by this instruction. 706 getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
707if (FwdRegDefs.
empty()) {
708// Any definitions by this instruction will clobber earlier reg movements. 709 ClobberedRegUnits.
insert(NewClobberedRegUnits.
begin(),
710 NewClobberedRegUnits.
end());
714// It's possible that we find a copy from a non-volatile register to the param 715// register, which is clobbered in the meantime. Test for clobbered reg unit 716// overlaps before completing. 717auto IsRegClobberedInMeantime = [&](
Register Reg) ->
bool {
718for (
auto &RegUnit : ClobberedRegUnits)
719if (
TRI.hasRegUnit(Reg, RegUnit))
724for (
auto ParamFwdReg : FwdRegDefs) {
725if (
auto ParamValue =
TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
726if (ParamValue->first.isImm()) {
727 int64_t Val = ParamValue->first.getImm();
729 ForwardedRegWorklist[ParamFwdReg], Params);
730 }
elseif (ParamValue->first.isReg()) {
731Register RegLoc = ParamValue->first.getReg();
732Register SP = TLI.getStackPointerRegisterToSaveRestore();
734bool IsSPorFP = (RegLoc == SP) || (RegLoc ==
FP);
735if (!IsRegClobberedInMeantime(RegLoc) &&
736 (
TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP)) {
739 ForwardedRegWorklist[ParamFwdReg], Params);
741// ParamFwdReg was described by the non-callee saved register 742// RegLoc. Mark that the call site values for the parameters are 743// dependent on that register instead of ParamFwdReg. Since RegLoc 744// may be a register that will be handled in this iteration, we 745// postpone adding the items to the worklist, and instead keep them 746// in a temporary container. 748 ForwardedRegWorklist[ParamFwdReg]);
754// Remove all registers that this instruction defines from the worklist. 755for (
auto ParamFwdReg : FwdRegDefs)
756 ForwardedRegWorklist.
erase(ParamFwdReg);
758// Any definitions by this instruction will clobber earlier reg movements. 759 ClobberedRegUnits.
insert(NewClobberedRegUnits.
begin(),
760 NewClobberedRegUnits.
end());
762// Now that we are done handling this instruction, add items from the 763// temporary worklist to the real one. 764for (
auto &New : TmpWorklistItems)
766 TmpWorklistItems.
clear();
773// Skip bundle headers. 777// If the next instruction is a call we can not interpret parameter's 778// forwarding registers or we finished the interpretation of all 783if (ForwardedRegWorklist.
empty())
786// Avoid NOP description. 790interpretValues(CurMI, ForwardedRegWorklist, Params, ClobberedRegUnits);
795/// Try to interpret values loaded into registers that forward parameters 796/// for \p CallMI. Store parameters with interpreted value into \p Params. 801auto CSInfo = CalleesMap.
find(CallMI);
803// There is no information for the call instruction. 804if (CSInfo == CalleesMap.end())
809// Skip the call instruction. 817// Add all the forwarding registers into the ForwardedRegWorklist. 818for (
constauto &ArgReg : CSInfo->second.ArgRegPairs) {
820 ForwardedRegWorklist.
insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
822assert(InsertedReg &&
"Single register used to forward two arguments?");
826// Do not emit CSInfo for undef forwarding registers. 827for (
constauto &MO : CallMI->
uses())
828if (MO.isReg() && MO.isUndef())
829 ForwardedRegWorklist.
erase(MO.getReg());
831// We erase, from the ForwardedRegWorklist, those forwarding registers for 832// which we successfully describe a loaded value (by using 833// the describeLoadedValue()). For those remaining arguments in the working 834// list, for which we do not describe a loaded value by 835// the describeLoadedValue(), we try to generate an entry value expression 836// for their call site value description, if the call is within the entry MBB. 837// TODO: Handle situations when call site parameter value can be described 838// as the entry value within basic blocks other than the first one. 841// Search for a loading value in forwarding registers inside call delay slot. 845// Only one-instruction delay slot is supported. 848assert(std::next(Suc) == BundleEnd &&
849"More than one instruction in call delay slot");
850// Try to interpret value loaded by instruction. 855// Search for a loading value in forwarding registers. 857// Try to interpret values loaded by instruction. 862// Emit the call site parameter's value as an entry value. 863if (ShouldTryEmitEntryVals) {
864// Create an expression where the register's entry value is used. 867for (
auto &RegEntry : ForwardedRegWorklist) {
874void DwarfDebug::constructCallSiteEntryDIEs(
constDISubprogram &SP,
877// Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if 878// the subprogram is required to have one. 879if (!SP.areAllCallsDescribed() || !SP.isDefinition())
882// Use DW_AT_call_all_calls to express that call site entries are present 883// for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls 884// because one of its requirements is not met: call site entries for 885// optimized-out calls are elided. 886CU.addFlag(ScopeDIE,
CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
889assert(
TII &&
"TargetInstrInfo not found: cannot label tail calls");
891// Delay slot support check. 893if (!
MI.isBundledWithSucc())
895auto Suc = std::next(
MI.getIterator());
897 (void)CallInstrBundle;
899 (void)DelaySlotBundle;
900// Ensure that label after call is following delay slot instruction. 901// Ex. CALL_INSTRUCTION { 902// DELAY_SLOT_INSTRUCTION } 906"Call and its successor instruction don't have same label after.");
910// Emit call site entries for each call or tail call in the function. 913// Bundles with call in them will pass the isCall() test below but do not 914// have callee operand information so skip them here. Iterator will 915// eventually reach the call MI. 919// Skip instructions which aren't calls. Both calls and tail-calling jump 920// instructions (e.g TAILJMPd64) are classified correctly here. 921if (!
MI.isCandidateForAdditionalCallInfo())
924// Skip instructions marked as frame setup, as they are not interesting to 929// Check if delay slot support is enabled. 930if (
MI.hasDelaySlot() && !delaySlotSupported(*&
MI))
933// If this is a direct call, find the callee's subprogram. 934// In the case of an indirect call find the register that holds 944if (CalleeOp.
isReg()) {
945 CallReg = CalleeOp.
getReg();
949 CalleeDecl = dyn_cast<Function>(CalleeOp.
getGlobal());
955// TODO: Omit call site entries for runtime calls (objc_msgSend, etc). 959// If MI is in a bundle, the label was created after the bundle since 960// EmitFunctionBody iterates over top-level MIs. Get that top-level MI 961// to search for that label below. 965// For non-tail calls, the return PC is needed to disambiguate paths in 966// the call graph which could lead to some target function. For tail 967// calls, no return PC information is needed, unless tuning for GDB in 968// DWARF4 mode in which case we fake a return PC for compatibility. 970 (!IsTail ||
CU.useGNUAnalogForDwarf5Feature())
974// For tail calls, it's necessary to record the address of the branch 975// instruction so that the debugger can show where the tail call occurred. 979assert((IsTail || PCAddr) &&
"Non-tail call without return PC");
982 << (CalleeDecl ? CalleeDecl->
getName()
986 << (IsTail ?
" [IsTail]" :
"") <<
"\n");
988DIE &CallSiteDIE =
CU.constructCallSiteEntryDIE(
989 ScopeDIE, CalleeSP, IsTail, PCAddr, CallAddr, CallReg);
991// Optionally emit call-site-param debug info. 994// Try to interpret values of call site parameters. 996CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
1003if (!
U.hasDwarfPubSections())
1006U.addFlag(
D, dwarf::DW_AT_GNU_pubnames);
1009void DwarfDebug::finishUnitAttributes(
constDICompileUnit *DIUnit,
1017 std::string ProducerWithFlags =
Producer.str() +
" " +
Flags.str();
1018 NewCU.
addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
1020 NewCU.
addString(Die, dwarf::DW_AT_producer, Producer);
1022 NewCU.
addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1024 NewCU.
addString(Die, dwarf::DW_AT_name, FN);
1026if (!SysRoot.
empty())
1027 NewCU.
addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
1030 NewCU.
addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
1033// Add DW_str_offsets_base to the unit DIE, except for split units. 1039// If we're using split dwarf the compilation dir is going to be in the 1040// skeleton CU and so we don't need to duplicate it here. 1041if (!CompilationDir.
empty())
1042 NewCU.
addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1043 addGnuPubAttributes(NewCU, Die);
1048 NewCU.
addFlag(Die, dwarf::DW_AT_APPLE_optimized);
1052 NewCU.
addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
1055 NewCU.
addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1056 dwarf::DW_FORM_data1, RVer);
1060// This CU is either a clang module DWO or a skeleton CU. 1061 NewCU.
addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
1064// This is a prefabricated skeleton CU. 1066 ? dwarf::DW_AT_dwo_name
1067 : dwarf::DW_AT_GNU_dwo_name;
1072// Create new DwarfCompileUnit for the given metadata node with tag 1073// DW_TAG_compile_unit. 1075DwarfDebug::getOrCreateDwarfCompileUnit(
constDICompileUnit *DIUnit) {
1076if (
auto *
CU = CUMap.lookup(DIUnit))
1084return *CUMap.begin()->second;
1088auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
1089 InfoHolder.
getUnits().size(), DIUnit,
Asm,
this, &InfoHolder);
1091 InfoHolder.
addUnit(std::move(OwnedUnit));
1093// LTO with assembly output shares a single line table amongst multiple CUs. 1094// To avoid the compilation directory being ambiguous, let the line table 1095// explicitly describe the directory of all files, never relying on the 1096// compilation directory. 1106 finishUnitAttributes(DIUnit, NewCU);
1110 CUMap.insert({DIUnit, &NewCU});
1111 CUDieMap.insert({&NewCU.
getUnitDie(), &NewCU});
1115/// Sort and unique GVEs by comparing their fragment offset. 1120// Sort order: first null exprs, then exprs without fragment 1121// info, then sort by fragment offset in bits. 1122// FIXME: Come up with a more comprehensive comparator so 1123// the sorting isn't non-deterministic, and so the following 1124// std::unique call works correctly. 1125if (!
A.Expr || !
B.Expr)
1127auto FragmentA =
A.Expr->getFragmentInfo();
1128auto FragmentB =
B.Expr->getFragmentInfo();
1129if (!FragmentA || !FragmentB)
1131return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
1136returnA.Expr ==
B.Expr;
1142// Emit all Dwarf sections that should come prior to the content. Create 1143// global DIEs and emit initial debug info sections. This is invoked by 1144// the target AsmPrinter. 1151unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
1152 M->debug_compile_units_end());
1153if (NumDebugCUs == 0)
1156assert(NumDebugCUs > 0 &&
"Asm unexpectedly initialized");
1157 SingleCU = NumDebugCUs == 1;
1163for (
auto *GVE : GVs)
1164 GVMap[GVE->getVariable()].push_back({&
Global, GVE->getExpression()});
1167// Create the symbol that designates the start of the unit's contribution 1168// to the string offsets table. In a split DWARF scenario, only the skeleton 1169// unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol). 1175// Create the symbols that designates the start of the DWARF v5 range list 1176// and locations list tables. They are located past the table headers. 1187// Create the symbol that points to the first entry following the debug 1188// address table (.debug_addr) header. 1193if (CUNode->getImportedEntities().empty() &&
1194 CUNode->getEnumTypes().empty() && CUNode->getRetainedTypes().empty() &&
1195 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1201for (
auto *GVE : CUNode->getGlobalVariables()) {
1202// Don't bother adding DIGlobalVariableExpressions listed in the CU if we 1203// already know about the variable and it isn't adding a constant 1205auto &GVMapEntry = GVMap[GVE->getVariable()];
1206auto *Expr = GVE->getExpression();
1207if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1208 GVMapEntry.push_back({
nullptr, Expr});
1212for (
auto *GVE : CUNode->getGlobalVariables()) {
1214if (Processed.
insert(GV).second)
1218for (
auto *Ty : CUNode->getEnumTypes())
1219CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1221for (
auto *Ty : CUNode->getRetainedTypes()) {
1222// The retained types array by design contains pointers to 1223// MDNodes rather than DIRefs. Unique them here. 1224if (
DIType *RT = dyn_cast<DIType>(Ty))
1225// There is no point in force-emitting a forward declaration. 1226CU.getOrCreateTypeDIE(RT);
1231void DwarfDebug::finishEntityDefinitions() {
1232for (
constauto &Entity : ConcreteEntities) {
1233DIE *Die = Entity->getDIE();
1235// FIXME: Consider the time-space tradeoff of just storing the unit pointer 1236// in the ConcreteEntities list, rather than looking it up again here. 1237// DIE::getUnit isn't simple - it walks parent pointers, etc. 1240 Unit->finishEntityDefinition(Entity.get());
1244void DwarfDebug::finishSubprogramDefinitions() {
1248 getOrCreateDwarfCompileUnit(SP->getUnit()),
1253void DwarfDebug::finalizeModuleInfo() {
1256 finishSubprogramDefinitions();
1258 finishEntityDefinitions();
1260bool HasEmittedSplitCU =
false;
1262// Handle anything that needs to be done on a per-unit basis after 1263// all other generation. 1264for (
constauto &
P : CUMap) {
1265auto &TheCU = *
P.second;
1266if (TheCU.getCUNode()->isDebugDirectivesOnly())
1268// Emit DW_AT_containing_type attribute to connect types with their 1269// vtable holding type. 1270 TheCU.constructContainingTypeDIEs();
1272// Add CU specific attributes if we need to add any. 1273// If we're splitting the dwarf out now that we've got the entire 1274// CU then add the dwo id to it. 1275auto *SkCU = TheCU.getSkeleton();
1277bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1280 (void)HasEmittedSplitCU;
1282"Multiple CUs emitted into a single dwo file");
1283 HasEmittedSplitCU =
true;
1285 ? dwarf::DW_AT_dwo_name
1286 : dwarf::DW_AT_GNU_dwo_name;
1287 finishUnitAttributes(TheCU.getCUNode(), TheCU);
1289 TheCU.addString(TheCU.getUnitDie(), attrDWOName, DWOName);
1290 SkCU->addString(SkCU->getUnitDie(), attrDWOName, DWOName);
1291// Emit a unique identifier for this CU. Include the DWO file name in the 1292// hash to avoid the case where two (almost) empty compile units have the 1293// same contents. This can happen if link-time optimization removes nearly 1294// all (unused) code from a CU. 1301 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1302 dwarf::DW_FORM_data8,
ID);
1303 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1304 dwarf::DW_FORM_data8,
ID);
1309 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1313 finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1316// If we have code split among multiple sections or non-contiguous 1317// ranges of code then emit a DW_AT_ranges attribute on the unit that will 1318// remain in the .o file, otherwise add a DW_AT_low_pc. 1319// FIXME: We should use ranges allow reordering of code ala 1320// .subsections_via_symbols in mach-o. This would mean turning on 1321// ranges for all subprogram DIEs for mach-o. 1324if (
unsigned NumRanges = TheCU.getRanges().size()) {
1325// PTX does not support subtracting labels from the code section in the 1326// debug_loc section. To work around this, the NVPTX backend needs the 1327// compile unit to have no low_pc in order to have a zero base_address 1328// when handling debug_loc in cuda-gdb. 1331// A DW_AT_low_pc attribute may also be specified in combination with 1332// DW_AT_ranges to specify the default base address for use in 1333// location lists (see Section 2.6.2) and range lists (see Section 1335U.addUInt(
U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1338U.setBaseAddress(TheCU.getRanges().front().Begin);
1339U.attachRangesOrLowHighPC(
U.getUnitDie(), TheCU.takeRanges());
1343// We don't keep track of which addresses are used in which CU so this 1344// is a bit pessimistic under LTO. 1346U.addAddrTableBase();
1349if (
U.hasRangeLists())
1353U.addSectionLabel(
U.getUnitDie(), dwarf::DW_AT_loclists_base,
1359auto *CUNode = cast<DICompileUnit>(
P.first);
1360// If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros" 1362if (CUNode->getMacros()) {
1363if (UseDebugMacroSection) {
1365 TheCU.addSectionDelta(
1366 TheCU.getUnitDie(), dwarf::DW_AT_macros,
U.getMacroLabelBegin(),
1370 ? dwarf::DW_AT_macros
1371 : dwarf::DW_AT_GNU_macros;
1372U.addSectionLabel(
U.getUnitDie(), MacrosAttr,
U.getMacroLabelBegin(),
1377 TheCU.addSectionDelta(
1378 TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1379U.getMacroLabelBegin(),
1382U.addSectionLabel(
U.getUnitDie(), dwarf::DW_AT_macro_info,
1383U.getMacroLabelBegin(),
1389// Emit all frontend-produced Skeleton CUs, i.e., Clang modules. 1391if (CUNode->getDWOId())
1392 getOrCreateDwarfCompileUnit(CUNode);
1394// Compute DIE offsets and sizes. 1399// Now that offsets are computed, can replace DIEs in debug_names Entry with 1404// Emit all Dwarf sections that should come after the content. 1406// Terminate the pending line table. 1413for (
constauto &
P : CUMap) {
1414constauto *CUNode = cast<DICompileUnit>(
P.first);
1417// Emit imported entities. 1418for (
auto *IE : CUNode->getImportedEntities()) {
1419assert(!isa_and_nonnull<DILocalScope>(IE->getScope()) &&
1420"Unexpected function-local entity in 'imports' CU field.");
1421CU->getOrCreateImportedEntityDIE(IE);
1423for (
constauto *
D :
CU->getDeferredLocalDecls()) {
1424if (
auto *IE = dyn_cast<DIImportedEntity>(
D))
1425CU->getOrCreateImportedEntityDIE(IE);
1431CU->createBaseTypeDIEs();
1434// If we aren't actually generating debug info (check beginModule - 1435// conditionalized on the presence of the llvm.dbg.cu metadata node) 1439// Finalize the debug info for the module. 1440 finalizeModuleInfo();
1443// Emit debug_loc.dwo/debug_loclists.dwo section. 1446// Emit debug_loc/debug_loclists section. 1449// Corresponding abbreviations into a abbrev section. 1450 emitAbbreviations();
1452// Emit all the DIEs into a debug info section. 1455// Emit info into a debug aranges section. 1456if (UseARangesSection)
1459// Emit info into a debug ranges section. 1463// Emit info into a debug macinfo.dwo section. 1464 emitDebugMacinfoDWO();
1466// Emit info into a debug macinfo/macro section. 1474 emitDebugAbbrevDWO();
1476 emitDebugRangesDWO();
1481// Emit info into the dwarf accelerator table sections. 1486 emitAccelNamespaces();
1490 emitAccelDebugNames();
1498// Emit the pubnames and pubtypes sections if requested. 1499 emitDebugPubSections();
1502// FIXME: AbstractVariables.clear(); 1507if (
CU.getExistingAbstractEntity(Node))
1512CU.createAbstractEntity(Node, Scope);
1517if (
constauto *LV = dyn_cast<DILocalVariable>(
N))
1519elseif (
constauto *L = dyn_cast<DILabel>(
N))
1521elseif (
constauto *IE = dyn_cast<DIImportedEntity>(
N))
1526// Ensure the scope is not a DILexicalBlockFile. 1527return cast<DILocalScope>(S)->getNonLexicalBlockFileScope();
1530// Collect variable information from side table maintained by MF. 1531void DwarfDebug::collectVariableInfoFromMFTable(
1534LLVM_DEBUG(
dbgs() <<
"DwarfDebug: collecting variables from MF side table\n");
1538assert(
VI.Var->isValidLocationForIntrinsic(
VI.Loc) &&
1539"Expected inlined-at fields to agree");
1541 InlinedEntity Var(
VI.Var,
VI.Loc->getInlinedAt());
1545// If variable scope is not found then skip this variable. 1548 <<
", no variable scope found\n");
1552 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first,
Scope->getScopeNode());
1554// If we have already seen information for this variable, add to what we 1557auto *PreviousMMI = std::get_if<Loc::MMI>(PreviousLoc);
1558auto *PreviousEntryValue = std::get_if<Loc::EntryValue>(PreviousLoc);
1559// Previous and new locations are both stack slots (MMI). 1560if (PreviousMMI &&
VI.inStackSlot())
1561 PreviousMMI->addFrameIndexExpr(
VI.Expr,
VI.getStackSlot());
1562// Previous and new locations are both entry values. 1563elseif (PreviousEntryValue &&
VI.inEntryValueRegister())
1564 PreviousEntryValue->addExpr(
VI.getEntryValueRegister(), *
VI.Expr);
1566// Locations differ, this should (rarely) happen in optimized async 1568// Prefer whichever location has an EntryValue. 1573 <<
", conflicting fragment location types\n");
1578auto RegVar = std::make_unique<DbgVariable>(
1579 cast<DILocalVariable>(Var.first), Var.second);
1580if (
VI.inStackSlot())
1587 MFVars.
insert({Var, RegVar.get()});
1588 ConcreteEntities.push_back(std::move(RegVar));
1592/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its 1593/// enclosing lexical scope. The check ensures there are no other instructions 1594/// in the same lexical scope preceding the DBG_VALUE and that its range is 1595/// either open or otherwise rolls off the end of the scope. 1600assert(
DbgValue->getDebugLoc() &&
"DBG_VALUE without a debug location");
1604// Scope doesn't exist; this is a dead DBG_VALUE. 1608if (LSRange.size() == 0)
1612// If the scope starts before the DBG_VALUE then we may have a negative 1613// result. Otherwise the location is live coming into the scope and we 1614// can skip the following checks. 1615if (!Ordering.isBefore(
DbgValue, LScopeBegin)) {
1616// Exit if the lexical scope begins outside of the current block. 1621for (++Pred; Pred !=
MBB->
rend(); ++Pred) {
1624auto PredDL = Pred->getDebugLoc();
1625if (!PredDL || Pred->isMetaInstruction())
1627// Check whether the instruction preceding the DBG_VALUE is in the same 1628// (sub)scope as the DBG_VALUE. 1629if (
DL->getScope() == PredDL->getScope())
1632if (!PredScope || LScope->dominates(PredScope))
1637// If the range of the DBG_VALUE is open-ended, report success. 1641// Single, constant DBG_VALUEs in the prologue are promoted to be live 1642// throughout the function. This is a hack, presumably for DWARF v2 and not 1643// necessarily correct. It would be much better to use a dbg.declare instead 1644// if we know the constant is live throughout the scope. 1650// Test if the location terminates before the end of the scope. 1652if (Ordering.isBefore(RangeEnd, LScopeEnd))
1655// There's a single location which starts at the scope start, and ends at or 1656// after the scope end. 1660/// Build the location list for all DBG_VALUEs in the function that 1661/// describe the same variable. The resulting DebugLocEntries will have 1662/// strict monotonically increasing begin addresses and will never 1663/// overlap. If the resulting list has only one entry that is valid 1664/// throughout variable's scope return true. 1666// See the definition of DbgValueHistoryMap::Entry for an explanation of the 1667// different kinds of history map entries. One thing to be aware of is that if 1668// a debug value is ended by another entry (rather than being valid until the 1669// end of the function), that entry's instruction may or may not be included in 1670// the range, depending on if the entry is a clobbering entry (it has an 1671// instruction that clobbers one or more preceding locations), or if it is an 1672// (overlapping) debug value entry. This distinction can be seen in the example 1673// below. The first debug value is ended by the clobbering entry 2, and the 1674// second and third debug values are ended by the overlapping debug value entry 1679// History map entries [type, end index, mi] 1681// 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)] 1682// 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)] 1683// 2 | | [Clobber, $reg0 = [...], -, -] 1684// 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)] 1685// 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)] 1687// Output [start, end) [Value...]: 1689// [0-1) [(reg0, fragment 0, 32)] 1690// [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)] 1691// [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)] 1692// [4-) [(@g, fragment 0, 96)] 1696 std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1698bool isSafeForSingleLocation =
true;
1702for (
auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1705// Remove all values that are no longer live. 1706size_tIndex = std::distance(EB, EI);
1707erase_if(OpenRanges, [&](OpenRange &R) {
returnR.first <=
Index; });
1709// If we are dealing with a clobbering entry, this iteration will result in 1710// a location list entry starting after the clobbering instruction. 1714"Forgot label before/after instruction starting a range!");
1717if (std::next(EI) == Entries.end()) {
1721 EndMI = EI->getInstr();
1723elseif (std::next(EI)->isClobber())
1727assert(EndLabel &&
"Forgot label after instruction ending a range!");
1729if (EI->isDbgValue())
1732// If this history map entry has a debug value, add that to the list of 1733// open ranges and check if its location is valid for a single value 1735if (EI->isDbgValue()) {
1736// Do not add undef debug values, as they are redundant information in 1737// the location list entries. An undef debug results in an empty location 1738// description. If there are any non-undef fragments then padding pieces 1739// with empty location descriptions will automatically be inserted, and if 1740// all fragments are undef then the whole location list entry is 1742if (!
Instr->isUndefDebugValue()) {
1746// TODO: Add support for single value fragment locations. 1747if (
Instr->getDebugExpression()->isFragment())
1748 isSafeForSingleLocation =
false;
1751 StartDebugMI =
Instr;
1753 isSafeForSingleLocation =
false;
1757// Location list entries with empty location descriptions are redundant 1758// information in DWARF, so do not emit those. 1759if (OpenRanges.
empty())
1762// Omit entries with empty ranges as they do not have any effect in DWARF. 1763if (StartLabel == EndLabel) {
1764LLVM_DEBUG(
dbgs() <<
"Omitting location list entry with empty range.\n");
1769for (
auto &R : OpenRanges)
1772// With Basic block sections, it is posssible that the StartLabel and the 1773// Instr are not in the same section. This happens when the StartLabel is 1774// the function begin label and the dbg value appears in a basic block 1775// that is not the entry. In this case, the range needs to be split to 1776// span each individual section in the range from StartLabel to EndLabel. 1779for (
constauto &[MBBSectionId, MBBSectionRange] :
1781if (
Instr->getParent()->getSectionID() == MBBSectionId) {
1782DebugLoc.emplace_back(MBBSectionRange.BeginLabel, EndLabel, Values);
1785DebugLoc.emplace_back(MBBSectionRange.BeginLabel,
1786 MBBSectionRange.EndLabel, Values);
1789DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1792// Attempt to coalesce the ranges of two otherwise identical 1796dbgs() << CurEntry->getValues().size() <<
" Values:\n";
1797for (
auto &
Value : CurEntry->getValues())
1802auto PrevEntry = std::next(CurEntry);
1803if (PrevEntry !=
DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1807if (!isSafeForSingleLocation ||
1817// Check here to see if loclist can be merged into a single range. If not, 1818// we must keep the split loclists per section. This does exactly what 1819// MergeRanges does without sections. We don't actually merge the ranges 1820// as the split ranges must be kept intact if this cannot be collapsed 1821// into a single range. 1826 RangeMBB = Entries.begin()->getInstr()->getParent();
1829"Range MBB not found in MBBSectionRanges!");
1831auto *NextEntry = std::next(CurEntry);
1832auto NextRangeIt = std::next(RangeIt);
1833while (NextEntry !=
DebugLoc.end()) {
1836// CurEntry should end the current section and NextEntry should start 1837// the next section and the Values must match for these two ranges to be 1838// merged. Do not match the section label end if it is the entry block 1839// section. This is because the end label for the Debug Loc and the 1840// Function end label could be different. 1842 CurEntry->getEndSym() != RangeIt->second.EndLabel) ||
1843 NextEntry->getBeginSym() != NextRangeIt->second.BeginLabel ||
1844 CurEntry->getValues() != NextEntry->getValues())
1846 RangeIt = NextRangeIt;
1847 NextRangeIt = std::next(RangeIt);
1848 CurEntry = NextEntry;
1849 NextEntry = std::next(CurEntry);
1859 ensureAbstractEntityIsCreatedIfScoped(TheCU,
Node,
Scope.getScopeNode());
1860if (isa<const DILocalVariable>(
Node)) {
1861 ConcreteEntities.push_back(
1862 std::make_unique<DbgVariable>(cast<const DILocalVariable>(
Node),
1865 cast<DbgVariable>(ConcreteEntities.back().get()));
1866 }
elseif (isa<const DILabel>(
Node)) {
1867 ConcreteEntities.push_back(
1868 std::make_unique<DbgLabel>(cast<const DILabel>(
Node),
1871 cast<DbgLabel>(ConcreteEntities.back().get()));
1873return ConcreteEntities.back().get();
1876// Find variables for each lexical scope. 1880// Grab the variable info that was squirreled away in the MMI side-table. 1881 collectVariableInfoFromMFTable(TheCU, Processed);
1884 InlinedEntity
IV =
I.first;
1888// Instruction ranges, specifying where IV is accessible. 1889constauto &HistoryMapEntries =
I.second;
1891// Try to find any non-empty variable location. Do not create a concrete 1892// entity if there are no locations. 1902// If variable scope is not found then skip this variable. 1907DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1908 *Scope, LocalVar,
IV.second));
1910constMachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1913// Check if there is a single DBG_VALUE, valid throughout the var's scope. 1914// If the history map contains a single debug value, there may be an 1915// additional entry which clobbers the debug value. 1916size_t HistSize = HistoryMapEntries.size();
1917bool SingleValueWithClobber =
1918 HistSize == 2 && HistoryMapEntries[1].isClobber();
1919if (HistSize == 1 || SingleValueWithClobber) {
1921 SingleValueWithClobber ? HistoryMapEntries[1].getInstr() :
nullptr;
1928// Handle multiple DBG_VALUE instructions describing one variable. 1931// Build the location list for this variable. 1933bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1935// Check whether buildLocationList managed to merge all locations to one 1936// that is valid throughout the variable's scope. If so, produce single 1938if (isValidSingleLocation) {
1939 RegVar->emplace<
Loc::Single>(Entries[0].getValues()[0]);
1943// If the variable has a DIBasicType, extract it. Basic types cannot have 1944// unique identifiers, so don't bother resolving the type with the 1949// Finalize the entry by lowering it into a DWARF bytestream. 1950for (
auto &Entry : Entries)
1954// For each InlinedEntity collected from DBG_LABEL instructions, convert to 1955// DWARF-related DbgLabel. 1957 InlinedEntity IL =
I.first;
1964// The scope could have an extra lexical block file. 1966Label->getScope()->getNonLexicalBlockFileScope();
1967// Get inlined DILocation if it is inlined label. 1972// If label scope is not found then skip this label. 1977 /// At this point, the temporary label is created. 1978 /// Save the temporary label to DbgLabel entity to get the 1979 /// actually address when generating Dwarf DIE. 1981 createConcreteEntity(TheCU, *Scope, Label, IL.second,
Sym);
1984// Collect info for retained nodes. 1985for (
constDINode *DN : SP->getRetainedNodes()) {
1987if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
1988if (!Processed.
insert(InlinedEntity(DN,
nullptr)).second)
1992 createConcreteEntity(TheCU, *LexS, DN,
nullptr);
1994 LocalDeclsPerLS[
LS].insert(DN);
1999// Process beginning of an instruction. 2006// Delay slot support check. 2008if (!
MI.isBundledWithSucc())
2010auto Suc = std::next(
MI.getIterator());
2012// Ensure that delay slot instruction is successor of the call instruction. 2013// Ex. CALL_INSTRUCTION { 2014// DELAY_SLOT_INSTRUCTION } 2015assert(Suc->isBundledWithPred() &&
2016"Call bundle instructions are out of order");
2020// When describing calls, we need a label for the call instruction. 2021if (!NoDebug && SP->areAllCallsDescribed() &&
2023 (!
MI->hasDelaySlot() || delaySlotSupported(*
MI))) {
2026// For tail calls, we need the address of the branch instruction for 2030// For non-tail calls, we need the return address for the call for 2031// DW_AT_call_return_pc. Under GDB tuning, this information is needed for 2032// tail calls as well. 2043// Check if source location changes, but ignore DBG_VALUE and CFI locations. 2044// If the instruction is part of the function frame setup code, do not emit 2045// any line record, as there is no correspondence with any user code. 2054// First time FrameDestroy has been seen in this basic block 2060// When we emit a line-0 record, we don't update PrevInstLoc; so look at 2061// the last line number actually emitted, to see if it was line 0. 2062unsigned LastAsmLine =
2066// In rare situations, we might want to place the end of the prologue 2067// somewhere that doesn't have a source location already. It should be in 2069assert(
MI->getParent() == &*
MI->getMF()->begin());
2070 recordSourceLine(SP->getScopeLine(), 0, SP,
2075bool PrevInstInSameSection =
2078bool ForceIsStmt = ForceIsStmtInstrs.contains(
MI);
2079if (
DL ==
PrevInstLoc && PrevInstInSameSection && !ForceIsStmt) {
2080// If we have an ongoing unspecified location, nothing to do here. 2083// We have an explicit location, same as the previous location. 2084// But we might be coming back to it after a line 0 record. 2085if ((LastAsmLine == 0 &&
DL.getLine() != 0) || Flags) {
2086// Reinstate the source location but not marked as a statement. 2088 recordSourceLine(
DL.getLine(),
DL.getCol(), Scope, Flags);
2094// We have an unspecified location, which might want to be line 0. 2095// If we have already emitted a line-0 record, don't repeat it. 2096if (LastAsmLine == 0)
2098// If user said Don't Do That, don't do that. 2101// See if we have a reason to emit a line-0 record now. 2102// Reasons to emit a line-0 record include: 2103// - User asked for it (UnknownLocations). 2104// - Instruction has a label, so it's referenced from somewhere else, 2105// possibly debug information; we want it to have a source location. 2106// - Instruction is at the top of a block; we don't want to inherit the 2107// location from the physically previous (maybe unrelated) block. 2110// Preserve the file and column numbers, if we can, to save space in 2111// the encoded line table. 2112// Do not update PrevInstLoc, it remembers the last non-0 line. 2113constMDNode *Scope =
nullptr;
2119 recordSourceLine(
/*Line=*/0, Column, Scope,
/*Flags=*/0);
2124// We have an explicit location, different from the previous location. 2125// Don't repeat a line-0 record, but otherwise emit the new location. 2126// (The new location might be an explicit line 0, which we do emit.) 2127if (
DL.getLine() == 0 && LastAsmLine == 0)
2133// If the line changed, we call that a new statement; unless we went to 2134// line 0 and came back, in which case it is not a new statement. 2136if (
DL.getLine() && (
DL.getLine() != OldLine || ForceIsStmt))
2140 recordSourceLine(
DL.getLine(),
DL.getCol(), Scope, Flags);
2142// If we're not at line 0, remember this location. 2147static std::pair<const MachineInstr *, bool>
2149// First known non-DBG_VALUE and non-frame setup location marks 2150// the beginning of the function body. 2155// Some instructions may be inserted into prologue after this function. Must 2156// keep prologue for these cases. 2157bool IsEmptyPrologue =
2158 !(
F.hasPrologueData() ||
F.getMetadata(LLVMContext::MD_func_sanitize));
2160// Helper lambda to examine each instruction and potentially return it 2161// as the prologue_end point. 2163 -> std::optional<std::pair<const MachineInstr *, bool>> {
2164// Is this instruction trivial data shuffling or frame-setup? 2166bool isTrivRemat =
TII.isTriviallyReMaterializable(
MI);
2169if (!isFrameSetup &&
MI.getDebugLoc()) {
2170// Scan forward to try to find a non-zero line number. The 2171// prologue_end marks the first breakpoint in the function after the 2172// frame setup, and a compiler-generated line 0 location is not a 2173// meaningful breakpoint. If none is found, return the first 2174// location after the frame setup. 2175if (
MI.getDebugLoc().getLine())
2176return std::make_pair(&
MI, IsEmptyPrologue);
2179// Keep track of the first "non-trivial" instruction seen, i.e. anything 2180// that doesn't involve shuffling data around or is a frame-setup. 2181if (!
isCopy && !isTrivRemat && !isFrameSetup && !NonTrivialInst)
2182 NonTrivialInst = &
MI;
2184 IsEmptyPrologue =
false;
2188// Examine all the instructions at the start of the function. This doesn't 2189// necessarily mean just the entry block: unoptimised code can fall-through 2190// into an initial loop, and it makes sense to put the initial breakpoint on 2191// the first instruction of such a loop. However, if we pass branches, we're 2192// better off synthesising an early prologue_end. 2193auto CurBlock = MF->
begin();
2194auto CurInst = CurBlock->begin();
2196// Find the initial instruction, we're guaranteed one by the caller, but not 2197// which block it's in. 2198while (CurBlock->empty())
2199 CurInst = (++CurBlock)->begin();
2200assert(CurInst != CurBlock->end());
2202// Helper function for stepping through the initial sequence of 2203// unconditionally executed instructions. 2204auto getNextInst = [&CurBlock, &CurInst, MF]() ->
bool {
2205// We've reached the end of the block. Did we just look at a terminator? 2206if (CurInst->isTerminator()) {
2207// Some kind of "real" control flow is occurring. At the very least 2208// we would have to start exploring the CFG, a good signal that the 2213// If we've already fallen through into a loop, don't fall through 2214// further, use a backup-location. 2215if (CurBlock->pred_size() > 1)
2218// Fall-through from entry to the next block. This is common at -O0 when 2219// there's no initialisation in the function. Bail if we're also at the 2220// end of the function, or the remaining blocks have no instructions. 2221// Skip empty blocks, in rare cases the entry can be empty, and 2222// other optimisations may add empty blocks that the control flow falls 2226if (CurBlock == MF->
end())
2228 }
while (CurBlock->empty());
2229 CurInst = CurBlock->begin();
2234// Check whether this non-meta instruction a good position for prologue_end. 2235if (!CurInst->isMetaInstruction()) {
2236auto FoundInst = ExamineInst(*CurInst);
2241// Try to continue searching, but use a backup-location if substantive 2242// computation is happening. 2243auto NextInst = std::next(CurInst);
2244if (NextInst != CurInst->getParent()->end()) {
2245// Continue examining the current block. 2254// We couldn't find any source-location, suggesting all meaningful information 2255// got optimised away. Set the prologue_end to be the first non-trivial 2256// instruction, which will get the scope line number. This is better than 2258// Only do this in the entry block, as we'll be giving it the scope line for 2259// the function. Return IsEmptyPrologue==true if we've picked the first 2261if (NonTrivialInst && NonTrivialInst->
getParent() == &*MF->
begin()) {
2262 IsEmptyPrologue = NonTrivialInst == &*MF->
begin()->begin();
2263return std::make_pair(NonTrivialInst, IsEmptyPrologue);
2266// If the entry path is empty, just don't have a prologue_end at all. 2267return std::make_pair(
nullptr, IsEmptyPrologue);
2270/// Register a source line with debug info. Returns the unique label that was 2271/// emitted and which provides correspondence to the source line list. 2273constMDNode *S,
unsigned Flags,
unsigned CUID,
2275ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
2278unsigned Discriminator = 0;
2279if (
auto *Scope = cast_or_null<DIScope>(S)) {
2280 Fn = Scope->getFilename();
2281if (Line != 0 && DwarfVersion >= 4)
2282if (
auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
2283 Discriminator = LBF->getDiscriminator();
2286 .getOrCreateSourceID(Scope->getFile());
2288 Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
2294// Don't deal with functions that have no instructions. 2300bool IsEmptyPrologue = PrologEnd.second;
2302// If the prolog is empty, no need to generate scope line for the proc. 2303if (IsEmptyPrologue) {
2304// If there's nowhere to put a prologue_end flag, emit a scope line in case 2305// there are simply no source locations anywhere in the function. 2307// Avoid trying to assign prologue_end to a line-zero location. 2308// Instructions with no DebugLoc at all are fine, they'll be given the 2309// scope line nuumber. 2311if (!
DL ||
DL->getLine() != 0)
2314// Later, don't place the prologue_end flag on this line-zero location. 2319// Ensure the compile unit is created if the function is called before 2322 (void)getOrCreateDwarfCompileUnit(SP->getUnit());
2323// We'd like to list the prologue as "not statements" but GDB behaves 2324// poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 2330/// For the function \p MF, finds the set of instructions which may represent a 2331/// change in line number from one or more of the preceding MBBs. Stores the 2332/// resulting set of instructions, which should have is_stmt set, in 2333/// ForceIsStmtInstrs. 2335 ForceIsStmtInstrs.clear();
2337// For this function, we try to find MBBs where the last source line in every 2338// block predecessor matches the first line seen in the block itself; for 2339// every such MBB, we set is_stmt=false on the first line in the block, and 2340// for every other block we set is_stmt=true on the first line. 2341// For example, if we have the block %bb.3, which has 2 predecesors %bb.1 and 2344// $r3 = MOV64ri 12, debug-location !DILocation(line: 4) 2345// JMP %bb.3, debug-location !DILocation(line: 5) 2347// $r3 = MOV64ri 24, debug-location !DILocation(line: 5) 2351// $r1 = ADD $r2, $r3, debug-location !DILocation(line: 5) 2352// When we examine %bb.3, we first check to see if it contains any 2353// instructions with debug locations, and select the first such instruction; 2354// in this case, the ADD, with line=5. We then examine both of its 2355// predecessors to see what the last debug-location in them is. For each 2356// predecessor, if they do not contain any debug-locations, or if the last 2357// debug-location before jumping to %bb.3 does not have line=5, then the ADD 2358// in %bb.3 must use IsStmt. In this case, all predecessors have a 2359// debug-location with line=5 as the last debug-location before jumping to 2360// %bb.3, so we do not set is_stmt for the ADD instruction - we know that 2361// whichever MBB we have arrived from, the line has not changed. 2365// We only need to the predecessors of MBBs that could have is_stmt set by 2369// We use const_cast even though we won't actually modify MF, because some 2370// methods we need take a non-const MBB. 2374for (
auto &
MI :
MBB) {
2375if (
MI.getDebugLoc() &&
MI.getDebugLoc()->getLine()) {
2377 PredMBBsToExamine.
insert(Pred);
2384// For each predecessor MBB, we examine the last line seen before each branch 2385// or logical fallthrough. We use analyzeBranch to handle cases where 2386// different branches have different outgoing lines (i.e. if there are 2387// multiple branches that each have their own source location); otherwise we 2388// just use the last line in the block. 2389for (
auto *
MBB : PredMBBsToExamine) {
2391auto MBBInstrIt = PotentialIsStmtMBBInstrs.
find(Succ);
2392if (MBBInstrIt == PotentialIsStmtMBBInstrs.
end())
2395if (
MI->getDebugLoc()->getLine() == OutgoingLine)
2397 PotentialIsStmtMBBInstrs.
erase(MBBInstrIt);
2398 ForceIsStmtInstrs.insert(
MI);
2400// If this block is empty, we conservatively assume that its fallthrough 2401// successor needs is_stmt; we could check MBB's predecessors to see if it 2402// has a consistent entry line, but this seems unlikely to be worthwhile. 2405 CheckMBBEdge(Succ, 0);
2408// If MBB has no successors that are in the "potential" set, due to one or 2409// more of them having confirmed is_stmt, we can skip this check early. 2411 return PotentialIsStmtMBBInstrs.contains(SuccMBB);
2414// If we can't determine what DLs this branch's successors use, just treat 2415// all the successors as coming from the last DebugLoc. 2422// For a conditional branch followed by unconditional branch where the 2423// unconditional branch has a DebugLoc, that loc is the outgoing loc to 2424// the the false destination only; otherwise, both destinations share an 2426if (!AnalyzeFailed && !
Cond.empty() && FBB !=
nullptr &&
2429assert(MIIt->isBranch() &&
"Bad result from analyzeBranch?");
2430 CheckMBBEdge(FBB, FBBLine);
2434// For all other cases, all successors share the last outgoing DebugLoc. 2439// If we don't find an outgoing loc, this block will start with a line 0. 2440// It is possible that we have a block that has no DebugLoc, but acts as a 2441// simple passthrough between two blocks that end and start with the same 2444// JMP %bb.2, debug-location !10 2448// $r1 = ADD $r2, $r3, debug-location !10 2449// If these blocks were merged into a single block, we would not attach 2450// is_stmt to the ADD, but with this logic that only checks the immediate 2451// predecessor, we will; we make this tradeoff because doing a full dataflow 2452// analysis would be expensive, and these situations are probably not common 2453// enough for this to be worthwhile. 2454unsigned LastLine = 0;
2456if (
autoDL = MIIt->getDebugLoc();
DL &&
DL->getLine()) {
2457 LastLine =
DL->getLine();
2462for (
auto *Succ : SuccessorBBs)
2463 CheckMBBEdge(Succ, LastLine);
2467// Gather pre-function debug information. Assumes being called immediately 2468// after the function entry point has been emitted. 2478 FunctionLineTableLabel =
CU.emitFuncLineTableOffsets()
2485// Record beginning of function. 2489 findForceIsStmtInstrs(MF);
2494// Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 2495// belongs to so that we add to the correct per-cu line table in the 2498// Use a single line table if we are generating assembly. 2501returnCU.getUniqueID();
2505constauto &CURanges =
CU->getRanges();
2506auto &LineTable =
Asm->
OutStreamer->getContext().getMCDwarfLineTable(
2508// Add the last range label for the given CU. 2509 LineTable.getMCLineSections().addEndEntry(
2510const_cast<MCSymbol *
>(CURanges.back().End));
2514// If we don't have a subprogram for this function then there will be a hole 2515// in the range information. Keep note of this by setting the previously used 2516// section to nullptr. 2517// Terminate the pending line table. 2524// Gather and emit post-function debug information. 2529"endFunction should be called with the same function as beginFunction");
2531// Set DwarfDwarfCompileUnitID in MCContext to default value. 2544 collectEntityInfo(TheCU, SP, Processed);
2546// Add the range of this function to the list of ranges for the CU. 2547// With basic block sections, add ranges for all basic block sections. 2549 TheCU.
addRange({R.second.BeginLabel, R.second.EndLabel});
2551// Under -gmlt, skip building the subprogram if there are no inlined 2552// subroutines inside it. But with -fdebug-info-for-profiling, the subprogram 2553// is still needed as we need its source location. 2570constauto *SP = cast<DISubprogram>(AScope->getScopeNode());
2571for (
constDINode *DN : SP->getRetainedNodes()) {
2573// Ensure LexicalScope is created for the scope of this node. 2575assert(LexS &&
"Expected the LexicalScope to be created.");
2576if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
2577// Collect info for variables/labels that were optimized out. 2578if (!Processed.
insert(InlinedEntity(DN,
nullptr)).second ||
2583// Remember the node if this is a local declarations. 2584 LocalDeclsPerLS[LS].insert(DN);
2588"getOrCreateAbstractScope() inserted an abstract subprogram scope");
2590 constructAbstractSubprogramScopeDIE(TheCU, AScope);
2593 ProcessedSPNodes.insert(SP);
2599 SkelCU->constructSubprogramScopeDIE(SP, FnScope, FunctionLineTableLabel);
2601 FunctionLineTableLabel =
nullptr;
2603// Construct call site entries. 2604 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
2607// Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 2608// DbgVariables except those that are also in AbstractVariables (since they 2609// can be used cross-function) 2612 LocalDeclsPerLS.clear();
2617// Register a source line with debug info. Returns the unique label that was 2618// emitted and which provides correspondence to the source line list. 2619void DwarfDebug::recordSourceLine(
unsigned Line,
unsigned Col,
constMDNode *S,
2621 ::recordSourceLine(*
Asm, Line, Col, S, Flags,
2626//===----------------------------------------------------------------------===// 2628//===----------------------------------------------------------------------===// 2630// Emit the debug info section. 2631void DwarfDebug::emitDebugInfo() {
2633 Holder.
emitUnits(
/* UseOffsets */false);
2636// Emit the abbreviation section. 2637void DwarfDebug::emitAbbreviations() {
2643void DwarfDebug::emitStringOffsetsTableHeader() {
2650template <
typename AccelTableT>
2651void DwarfDebug::emitAccel(AccelTableT &Accel,
MCSection *Section,
2655// Emit the full data. 2659void DwarfDebug::emitAccelDebugNames() {
2660// Don't emit anything if we have no compilation units to index. 2661if (getUnits().empty())
2667// Emit visible names into a hashed accelerator table section. 2668void DwarfDebug::emitAccelNames() {
2673// Emit objective C classes and categories into a hashed accelerator table 2675void DwarfDebug::emitAccelObjC() {
2680// Emit namespace dies into a hashed accelerator table. 2681void DwarfDebug::emitAccelNamespaces() {
2682 emitAccel(AccelNamespace,
2687// Emit type dies into a hashed accelerator table. 2688void DwarfDebug::emitAccelTypes() {
2693// Public name handling. 2694// The format for the various pubnames: 2696// dwarf pubnames - offset/name pairs where the offset is the offset into the CU 2697// for the DIE that is named. 2699// gnu pubnames - offset/index value/name tuples where the offset is the offset 2700// into the CU and the index value is computed according to the type of value 2701// for the DIE that is named. 2703// For type units the offset is the offset of the skeleton DIE. For split dwarf 2704// it's the offset within the debug_info/debug_types dwo section, however, the 2705// reference in the pubname header doesn't change. 2707/// computeIndexValue - Compute the gdb index value for the DIE and CU. 2710// Entities that ended up only in a Type Unit reference the CU instead (since 2711// the pub entry has offsets within the CU there's no real offset that can be 2712// provided anyway). As it happens all such entities (namespaces and types, 2713// types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out 2714// not to be true it would be necessary to persist this information from the 2715// point at which the entry is added to the index data structure - since by 2716// the time the index is built from that, the original type/namespace DIE in a 2717// type unit has already been destroyed so it can't be queried for properties 2719if (Die->
getTag() == dwarf::DW_TAG_compile_unit)
2724// We could have a specification DIE that has our most of our knowledge, 2725// look for that now. 2727DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
2734case dwarf::DW_TAG_class_type:
2735case dwarf::DW_TAG_structure_type:
2736case dwarf::DW_TAG_union_type:
2737case dwarf::DW_TAG_enumeration_type:
2743case dwarf::DW_TAG_typedef:
2744case dwarf::DW_TAG_base_type:
2745case dwarf::DW_TAG_subrange_type:
2746case dwarf::DW_TAG_template_alias:
2748case dwarf::DW_TAG_namespace:
2750case dwarf::DW_TAG_subprogram:
2752case dwarf::DW_TAG_variable:
2754case dwarf::DW_TAG_enumerator:
2762/// emitDebugPubSections - Emit visible names and types into debug pubnames and 2763/// pubtypes sections. 2764void DwarfDebug::emitDebugPubSections() {
2765for (
constauto &NU : CUMap) {
2776 emitDebugPubSection(GnuStyle,
"Names", TheU, TheU->
getGlobalNames());
2781 emitDebugPubSection(GnuStyle,
"Types", TheU, TheU->
getGlobalTypes());
2788CU.getDebugSectionOffset());
2793void DwarfDebug::emitDebugPubSection(
bool GnuStyle,
StringRefName,
2801"pub" +
Name,
"Length of Public " +
Name +
" Info");
2807 emitSectionReference(*TheU);
2812// Emit the pubnames for this compilation unit. 2814for (
constauto &GI : Globals)
2817returnA.second->getOffset() <
B.second->getOffset();
2819for (
constauto &[
Name, Entity] : Vec) {
2840/// Emit null-terminated strings into a debug str section. 2841void DwarfDebug::emitDebugStr() {
2842MCSection *StringOffsetsSection =
nullptr;
2844 emitStringOffsetsTableHeader();
2849 StringOffsetsSection,
/* UseRelativeOffsets = */true);
2856auto Comment = Comments.begin();
2857autoEnd = Comments.end();
2859// The expressions are inserted into a byte stream rather early (see 2860// DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that 2861// need to reference a base_type DIE the offset of that DIE is not yet known. 2862// To deal with this we instead insert a placeholder early and then extract 2863// it here and replace it with the real reference. 2872for (
constauto &
Op : Expr) {
2874"3 operand ops not yet supported");
2882// Make sure comments stay aligned. 2883for (
unsigned J = 0; J <
Length; ++J)
2888 Streamer.
emitInt8(
Data.getData()[J], Comment !=
End ? *(Comment++) :
"");
2899auto *DIExpr =
Value.getExpression();
2903// If the DIExpr is an Entry Value, we want to follow the same code path 2904// regardless of whether the DBG_VALUE is variadic or not. 2905if (DIExpr && DIExpr->isEntryValue()) {
2906// Entry values can only be a single register with no additional DIExpr, 2907// so just add it directly. 2922auto EmitValueLocEntry = [&DwarfExpr, &
BT,
2926if (
BT && (
BT->getEncoding() == dwarf::DW_ATE_signed ||
2927BT->getEncoding() == dwarf::DW_ATE_signed_char))
2931 }
elseif (Entry.isLocation()) {
2933if (Location.isIndirect())
2939 }
elseif (Entry.isTargetIndexLocation()) {
2941// TODO TargetIndexLocation is a target-independent. Currently only the 2942// WebAssembly-specific encoding is supported. 2945 }
elseif (Entry.isConstantFP()) {
2948 DwarfExpr.
addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);
2949 }
elseif (Entry.getConstantFP()
2952 .getBitWidth() <= 64
/*bits*/) {
2954 Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
2957dbgs() <<
"Skipped DwarfExpression creation for ConstantFP of size" 2958 << Entry.getConstantFP()
2969if (!
Value.isVariadic()) {
2970if (!EmitValueLocEntry(
Value.getLocEntries()[0], ExprCursor))
2976// If any of the location entries are registers with the value 0, then the 2977// location is undefined. 2979 return Entry.isLocation() && !Entry.getLoc().getReg();
2984 std::move(ExprCursor),
2985 [EmitValueLocEntry, &
Value](
unsignedIdx,
2987return EmitValueLocEntry(
Value.getLocEntries()[
Idx], Cursor);
2996"location list entries without values are redundant");
2997assert(Begin != End &&
"unexpected location list entry with empty range");
3002if (
Value.isFragment()) {
3003// Emit all fragments that belong to the same variable and range. 3005returnP.isFragment();
3006 }) &&
"all values are expected to be fragments");
3009for (
constauto &Fragment : Values)
3013assert(Values.
size() == 1 &&
"only fragments may have >1 value");
3027elseif (DebugLocs.
getBytes(Entry).
size() <= std::numeric_limits<uint16_t>::max())
3030// The entry is too big to fit into 16 bit, drop it as there is nothing we 3040// Emit the header of a DWARF 5 range list table list table. Returns the symbol 3041// that designates the end of the table for the caller to emit when the table is 3047 Asm->OutStreamer->AddComment(
"Offset entry count");
3053 Asm->getDwarfOffsetByteSize());
3058// Emit the header of a DWARF 5 locations list table. Returns the symbol that 3059// designates the end of the table for the caller to emit when the table is 3067 Asm->OutStreamer->AddComment(
"Offset entry count");
3068 Asm->emitInt32(DebugLocs.getLists().size());
3069 Asm->OutStreamer->emitLabel(DebugLocs.getSym());
3071for (
constauto &
List : DebugLocs.getLists())
3072 Asm->emitLabelDifference(
List.Label, DebugLocs.getSym(),
3073 Asm->getDwarfOffsetByteSize());
3078template <
typename Ranges,
typename PayloadEmitter>
3084bool ShouldUseBaseAddress,
3085 PayloadEmitter EmitPayload) {
3087autoSize = Asm->MAI->getCodePointerSize();
3090// Emit our symbol so we can find the beginning of the range. 3091 Asm->OutStreamer->emitLabel(
Sym);
3093// Gather all the ranges that apply to the same section so they can share 3094// a base address entry. 3098for (
constauto &
Range : R)
3099 SectionRanges[&
Range.Begin->getSection()].push_back(&
Range);
3102bool BaseIsSet =
false;
3103for (
constauto &
P : SectionRanges) {
3105if ((Asm->TM.getTargetTriple().isNVPTX() && DD.
tuneForGDB())) {
3106// PTX does not support subtracting labels from the code section in the 3107// debug_loc section. To work around this, the NVPTX backend needs the 3108// compile unit to have no low_pc in order to have a zero base_address 3109// when handling debug_loc in cuda-gdb. Additionally, cuda-gdb doesn't 3110// seem to handle setting a per-variable base to zero. To make cuda-gdb 3111// happy, just emit labels with no base while having no compile unit 3115 }
elseif (!
Base && ShouldUseBaseAddress) {
3116constMCSymbol *Begin =
P.second.front()->Begin;
3121 Asm->OutStreamer->emitIntValue(-1,
Size);
3122 Asm->OutStreamer->AddComment(
" base address");
3123 Asm->OutStreamer->emitSymbolValue(
Base,
Size);
3124 }
elseif (NewBase != Begin ||
P.second.size() > 1) {
3125// Only use a base address if 3126// * the existing pool address doesn't match (NewBase != Begin) 3127// * or, there's more than one entry to share the base address 3130 Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
3131 Asm->emitInt8(BaseAddressx);
3132 Asm->OutStreamer->AddComment(
" base address index");
3135 }
elseif (BaseIsSet && !UseDwarf5) {
3138 Asm->OutStreamer->emitIntValue(-1,
Size);
3139 Asm->OutStreamer->emitIntValue(0,
Size);
3142for (
constauto *RS :
P.second) {
3145assert(Begin &&
"Range without a begin symbol?");
3146assert(
End &&
"Range without an end symbol?");
3149// Emit offset_pair when we have a base. 3150 Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
3151 Asm->emitInt8(OffsetPair);
3152 Asm->OutStreamer->AddComment(
" starting offset");
3153 Asm->emitLabelDifferenceAsULEB128(Begin,
Base);
3154 Asm->OutStreamer->AddComment(
" ending offset");
3155 Asm->emitLabelDifferenceAsULEB128(
End,
Base);
3157 Asm->emitLabelDifference(Begin,
Base,
Size);
3160 }
elseif (UseDwarf5) {
3161 Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
3162 Asm->emitInt8(StartxLength);
3163 Asm->OutStreamer->AddComment(
" start index");
3165 Asm->OutStreamer->AddComment(
" length");
3166 Asm->emitLabelDifferenceAsULEB128(
End, Begin);
3168 Asm->OutStreamer->emitSymbolValue(Begin,
Size);
3169 Asm->OutStreamer->emitSymbolValue(
End,
Size);
3176 Asm->OutStreamer->AddComment(StringifyEnum(
EndOfList));
3179// Terminate the list with two 0 values. 3180 Asm->OutStreamer->emitIntValue(0,
Size);
3181 Asm->OutStreamer->emitIntValue(0,
Size);
3185// Handles emission of both debug_loclist / debug_loclist.dwo 3188 *
List.CU, dwarf::DW_LLE_base_addressx,
3189 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
3191/* ShouldUseBaseAddress */true,
3193 DD.emitDebugLocEntryLocation(E, List.CU);
3197void DwarfDebug::emitDebugLocImpl(
MCSection *Sec) {
3214// Emit locations into the .debug_loc/.debug_loclists section. 3215void DwarfDebug::emitDebugLoc() {
3222// Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section. 3223void DwarfDebug::emitDebugLocDWO() {
3237// GDB only supports startx_length in pre-standard split-DWARF. 3238// (in v5 standard loclists, it currently* /only/ supports base_address + 3239// offset_pair, so the implementations can't really share much since they 3240// need to use different representations) 3241// * as of October 2018, at least 3243// In v5 (see emitLocList), this uses SectionLabels to reuse existing 3244// addresses in the address pool to minimize object size/relocations. 3248// Also the pre-standard encoding is slightly different, emitting this as 3249// an address-length entry here, but its a ULEB128 in DWARFv5 loclists. 3261// Emit a debug aranges section, containing a CU lookup for any 3262// address we can tie back to a CU. 3263void DwarfDebug::emitDebugARanges() {
3264if (ArangeLabels.empty())
3267// Provides a unique id per text section. 3270// Filter labels by section. 3271for (
constSymbolCU &SCU : ArangeLabels) {
3272if (SCU.Sym->isInSection()) {
3273// Make a note of this symbol and it's section. 3274MCSection *Section = &SCU.Sym->getSection();
3275 SectionMap[Section].push_back(SCU);
3277// Some symbols (e.g. common/bss on mach-o) can have no section but still 3278// appear in the output. This sucks as we rely on sections to build 3279// arange spans. We can do it without, but it's icky. 3280 SectionMap[
nullptr].push_back(SCU);
3286for (
auto &
I : SectionMap) {
3291// If we have no section (e.g. common), just write out 3292// individual spans for each symbol. 3296 Span.
Start = Cur.Sym;
3299 Spans[Cur.CU].push_back(Span);
3304// Insert a final terminator. 3307// Build spans between each label. 3309for (
size_t n = 1, e =
List.size(); n < e; n++) {
3313// Try and build the longest span we can within the same CU. 3314if (Cur.
CU != Prev.
CU) {
3316 Span.
Start = StartSym;
3319 Spans[Prev.
CU].push_back(Span);
3325// Start the dwarf aranges section. 3331// Build a list of CUs used. 3332 std::vector<DwarfCompileUnit *> CUs;
3333for (
constauto &it : Spans) {
3338// Sort the CU list (again, to ensure consistent output order). 3340returnA->getUniqueID() <
B->getUniqueID();
3343// Emit an arange table for each CU we used. 3345 std::vector<ArangeSpan> &
List = Spans[
CU];
3347// Describe the skeleton CU's offset and length, not the dwo file's. 3348if (
auto *Skel =
CU->getSkeleton())
3351// Emit size of content not including length itself. 3352unsigned ContentSize =
3353sizeof(int16_t) +
// DWARF ARange version number 3356sizeof(int8_t) +
// Pointer Size (in bytes) 3357sizeof(int8_t);
// Segment Size (in bytes) 3359unsigned TupleSize = PtrSize * 2;
3361// 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 3366 ContentSize += (
List.size() + 1) * TupleSize;
3368// For each compile unit, write the list of spans it covers. 3373 emitSectionReference(*
CU);
3384// Calculate the size as being from the span start to its end. 3386// If the size is zero, then round it up to one byte. The DWARF 3387// specification requires that entries in this table have nonzero 3389auto SizeRef = SymSize.find(Span.Start);
3390if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
3393// For symbols without an end marker (e.g. common), we 3394// write a single arange entry containing just that one symbol. 3396if (SizeRef == SymSize.end() || SizeRef->second == 0)
3399Size = SizeRef->second;
3411/// Emit a single range list. We handle both DWARF v5 and earlier. 3415 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
3416 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
3418List.CU->getCUNode()->getRangesBaseAddress() ||
3430return !Pair.second->getCUNode()->isDebugDirectivesOnly();
3446/// Emit address ranges into the .debug_ranges section or into the DWARF v5 3447/// .debug_rnglists section. 3448void DwarfDebug::emitDebugRanges() {
3449constauto &Holder =
useSplitDwarf() ? SkeletonHolder : InfoHolder;
3451 emitDebugRangesImpl(Holder,
3457void DwarfDebug::emitDebugRangesDWO() {
3458 emitDebugRangesImpl(InfoHolder,
3462/// Emit the header of a DWARF 5 macro section, or the GNU extension for 3466enum HeaderFlagMask {
3467#define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID, 3468#include "llvm/BinaryFormat/Dwarf.def" 3470 Asm->OutStreamer->AddComment(
"Macro information version");
3471 Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
3472// We emit the line offset flag unconditionally here, since line offset should 3473// be mostly present. 3474if (Asm->isDwarf64()) {
3475 Asm->OutStreamer->AddComment(
"Flags: 64 bit, debug_line_offset present");
3476 Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
3478 Asm->OutStreamer->AddComment(
"Flags: 32 bit, debug_line_offset present");
3479 Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
3481 Asm->OutStreamer->AddComment(
"debug_line_offset");
3483 Asm->emitDwarfLengthOrOffset(0);
3485 Asm->emitDwarfSymbolReference(
CU.getLineTableStartSym());
3488void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes,
DwarfCompileUnit &U) {
3489for (
auto *MN : Nodes) {
3490if (
auto *M = dyn_cast<DIMacro>(MN))
3492elseif (
auto *
F = dyn_cast<DIMacroFile>(MN))
3493 emitMacroFile(*
F, U);
3499void DwarfDebug::emitMacro(
DIMacro &M) {
3503// There should be one space between the macro name and the macro value in 3504// define entries. In undef entries, only the macro name is emitted. 3507if (UseDebugMacroSection) {
3510 ? dwarf::DW_MACRO_define_strx
3511 : dwarf::DW_MACRO_undef_strx;
3521 ? dwarf::DW_MACRO_GNU_define_indirect
3522 : dwarf::DW_MACRO_GNU_undef_indirect;
3542void DwarfDebug::emitMacroFileImpl(
3544StringRef (*MacroFormToString)(
unsigned Form)) {
3564// DWARFv5 macro and DWARFv4 macinfo share some common encodings, 3565// so for readibility/uniformity, We are explicitly emitting those. 3567if (UseDebugMacroSection)
3569F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
3576void DwarfDebug::emitDebugMacinfoImpl(
MCSection *Section) {
3577for (
constauto &
P : CUMap) {
3578auto &TheCU = *
P.second;
3581auto *CUNode = cast<DICompileUnit>(
P.first);
3582 DIMacroNodeArray Macros = CUNode->getMacros();
3587if (UseDebugMacroSection)
3589 handleMacroNodes(Macros, U);
3595/// Emit macros into a debug macinfo/macro section. 3596void DwarfDebug::emitDebugMacinfo() {
3598 emitDebugMacinfoImpl(UseDebugMacroSection
3599 ? ObjLower.getDwarfMacroSection()
3600 : ObjLower.getDwarfMacinfoSection());
3603void DwarfDebug::emitDebugMacinfoDWO() {
3605 emitDebugMacinfoImpl(UseDebugMacroSection
3606 ? ObjLower.getDwarfMacroDWOSection()
3607 : ObjLower.getDwarfMacinfoDWOSection());
3610// DWARF5 Experimental Separate Dwarf emitters. 3612void DwarfDebug::initSkeletonUnit(
constDwarfUnit &U,
DIE &Die,
3613 std::unique_ptr<DwarfCompileUnit> NewU) {
3615if (!CompilationDir.
empty())
3616 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
3617 addGnuPubAttributes(*NewU, Die);
3619 SkeletonHolder.
addUnit(std::move(NewU));
3624auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
3625CU.getUniqueID(),
CU.getCUNode(),
Asm,
this, &SkeletonHolder,
3635 initSkeletonUnit(
CU, NewCU.
getUnitDie(), std::move(OwnedUnit));
3640// Emit the .debug_info.dwo section for separated dwarf. This contains the 3641// compile units that would normally be in debug_info. 3642void DwarfDebug::emitDebugInfoDWO() {
3644// Don't emit relocations into the dwo file. 3645 InfoHolder.
emitUnits(
/* UseOffsets */true);
3648// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 3649// abbreviations for the .debug_info.dwo section. 3650void DwarfDebug::emitDebugAbbrevDWO() {
3655void DwarfDebug::emitDebugLineDWO() {
3657 SplitTypeUnitFileTable.
Emit(
3662void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
3669// Emit the .debug_str.dwo section for separated dwarf. This contains the 3670// string section and is identical in format to traditional .debug_str 3672void DwarfDebug::emitDebugStrDWO() {
3674 emitStringOffsetsTableHeaderDWO();
3678 OffSec,
/* UseRelativeOffsets = */false);
3681// Emit address pool. 3682void DwarfDebug::emitDebugAddr() {
3693return &SplitTypeUnitFileTable;
3699// ... take the least significant 8 bytes and return those. Our MD5 3700// implementation always returns its results in little endian, so we actually 3701// need the "high" word. 3704return Result.high();
3710// Fast path if we're building some type units and one has already used the 3711// address pool we know we're going to throw away all this work anyway, so 3712// don't bother building dependent types. 3713if (!TypeUnitsUnderConstruction.empty() && AddrPool.
hasBeenUsed())
3716auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
3718CU.addDIETypeSignature(RefDie, Ins.first->second);
3723bool TopLevelType = TypeUnitsUnderConstruction.empty();
3726auto OwnedUnit = std::make_unique<DwarfTypeUnit>(
3727CU,
Asm,
this, &InfoHolder, NumTypeUnitsCreated++, getDwoLineTable(
CU));
3730 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
3732 NewTU.
addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3737 Ins.first->second = Signature;
3740// Although multiple type units can have the same signature, they are not 3741// guranteed to be bit identical. When LLDB uses .debug_names it needs to 3742// know from which CU a type unit came from. These two attrbutes help it to 3745if (!CompilationDir.
empty())
3746 NewTU.
addString(UnitDie, dwarf::DW_AT_comp_dir, CompilationDir);
3747 NewTU.
addString(UnitDie, dwarf::DW_AT_dwo_name,
3761// Non-split type units reuse the compile unit's line table. 3762CU.applyStmtList(UnitDie);
3765// Add DW_AT_str_offsets_base to the type unit DIE, but not for split type 3773auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
3774 TypeUnitsUnderConstruction.clear();
3776// Types referencing entries in the address table cannot be placed in type 3779 AccelTypeUnitsDebugNames.
clear();
3780// Remove all the types built while building this type. 3781// This is pessimistic as some of these types might not be dependent on 3782// the type that used an address. 3783for (
constauto &
TU : TypeUnitsToAdd)
3784 TypeSignatures.erase(
TU.second);
3786// Construct this type in the CU directly. 3787// This is inefficient because all the dependent types will be rebuilt 3788// from scratch, including building them in type units, discovering that 3789// they depend on addresses, throwing them out and rebuilding them. 3791CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
3792CU.updateAcceleratorTables(CTy->
getScope(), CTy, RefDie);
3796// If the type wasn't dependent on fission addresses, finish adding the type 3797// and all its dependent types. 3798for (
auto &
TU : TypeUnitsToAdd) {
3811 AccelTypeUnitsDebugNames.
clear();
3814CU.addDIETypeSignature(RefDie, Signature);
3817// Add the Name along with its companion DIE to the appropriate accelerator 3818// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for 3819// AccelTableKind::Apple, we use the table we got as an argument). If 3820// accelerator tables are disabled, this function does nothing. 3821template <
typename DataT>
3822void DwarfDebug::addAccelNameImpl(
3827 Unit.getUnitDie().getTag() == dwarf::DW_TAG_skeleton_unit ||
Name.empty())
3844assert(((&Current == &AccelTypeUnitsDebugNames) ||
3845 ((&Current == &AccelDebugNames) &&
3846 (Unit.getUnitDie().getTag() != dwarf::DW_TAG_type_unit))) &&
3847"Kind is CU but TU is being processed.");
3848assert(((&Current == &AccelDebugNames) ||
3849 ((&Current == &AccelTypeUnitsDebugNames) &&
3850 (Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit))) &&
3851"Kind is TU but CU is being processed.");
3852// The type unit can be discarded, so need to add references to final 3853// acceleration table once we know it's complete and we emit it. 3854 Current.
addName(
Ref, Die, Unit.getUniqueID(),
3855 Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit);
3869 addAccelNameImpl(Unit, NameTableKind, AccelNames,
Name, Die);
3876// ObjC names go only into the Apple accelerator tables. 3878 addAccelNameImpl(Unit, NameTableKind, AccelObjC,
Name, Die);
3885 addAccelNameImpl(Unit, NameTableKind, AccelNamespace,
Name, Die);
3891constDIE &Die,
char Flags) {
3892 addAccelNameImpl(Unit, NameTableKind, AccelTypes,
Name, Die);
3901return dwarf::Form::DW_FORM_sec_offset;
3903"DWARF64 is not defined prior DWARFv3");
3905 : dwarf::Form::DW_FORM_data4;
3909return SectionLabels.lookup(S);
3913if (SectionLabels.insert(std::make_pair(&S->
getSection(), S)).second)
3918std::optional<MD5::MD5Result>
3923 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
3927// Convert the string checksum to an MD5Result for the streamer. 3928// The verifier validates the checksum so we assume it's okay. 3929// An MD5 checksum is 16 bytes. 3930 std::string ChecksumString = fromHex(Checksum->Value);
3932 std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.data());
3957auto PrevLoc =
Asm->
OutStreamer->getContext().getCurrentDwarfLoc();
3958if (PrevLoc.getLine()) {
3960 PrevLoc.getFileNum(), 0, PrevLoc.getColumn(), 0, 0, 0,
StringRef());
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define clEnumVal(ENUMVAL, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
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))
static SmallVectorImpl< DwarfCompileUnit::GlobalExpr > & sortGlobalExprs(SmallVectorImpl< DwarfCompileUnit::GlobalExpr > &GVEs)
Sort and unique GVEs by comparing their fragment offset.
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 void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col, const MDNode *S, unsigned Flags, unsigned CUID, uint16_t DwarfVersion, ArrayRef< std::unique_ptr< DwarfCompileUnit > > DCUs)
Register a source line with debug info.
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))
static void interpretValues(const MachineInstr *CurMI, FwdRegWorklist &ForwardedRegWorklist, ParamSet &Params, ClobberedRegSet &ClobberedRegUnits)
Interpret values loaded into registers by CurMI.
static bool interpretNextInstr(const MachineInstr *CurMI, FwdRegWorklist &ForwardedRegWorklist, ParamSet &Params, ClobberedRegSet &ClobberedRegUnits)
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))
static AccelTableKind computeAccelTableKind(unsigned DwarfVersion, bool GenerateTypeUnits, DebuggerKind Tuning, const Triple &TT)
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 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 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 void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R, const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair, unsigned StartxLength, unsigned EndOfList, StringRef(*StringifyEnum)(unsigned), bool ShouldUseBaseAddress, PayloadEmitter EmitPayload)
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
Module.h This file contains the declarations for the Module class.
#define DWARF2_FLAG_IS_STMT
#define DWARF2_FLAG_PROLOGUE_END
#define DWARF2_FLAG_EPILOGUE_BEGIN
unsigned const TargetRegisterInfo * TRI
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
This file contains some functions that are useful when dealing with strings.
This file describes how to lower LLVM code to machine code.
static bool isCopy(MachineInstr *MI)
static const uint32_t IV[8]
Class recording the (high level) value of a variable.
This class holds an abstract representation of an Accelerator Table, consisting of a sequence of buck...
void addName(DwarfStringPoolEntryRef Name, Types &&... Args)
unsigned getIndex(const MCSymbol *Sym, bool TLS=false)
Returns the index into the address pool with the given label/symbol.
void emit(AsmPrinter &Asm, MCSection *AddrSection)
void setLabel(MCSymbol *Sym)
void resetUsedFlag(bool HasBeenUsed=false)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
std::vector< T > vec() const
size_t size() const
size - Get the array size.
This class is intended to be used as a driving class for all asm writers.
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
void emitULEB128(uint64_t Value, const char *Desc=nullptr, unsigned PadTo=0) const
Emit the specified unsigned leb128 value.
void emitDwarfSymbolReference(const MCSymbol *Label, bool ForceOffset=false) const
Emit a reference to a symbol for use in dwarf.
MapVector< MBBSectionID, MBBSectionRange > MBBSectionRanges
DwarfDebug * getDwarfDebug()
void emitDwarfLengthOrOffset(uint64_t Value) const
Emit 32- or 64-bit value depending on the DWARF format.
unsigned int getUnitLengthFieldByteSize() const
Returns 4 for DWARF32 and 12 for DWARF64.
TargetMachine & TM
Target machine description.
MCSymbol * getFunctionBegin() const
void emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) const
Emit something like ".long Hi-Lo" where the size in bytes of the directive is specified by Size and H...
const MCAsmInfo * MAI
Target Asm Printer information.
MachineFunction * MF
The current machine function.
void emitDwarfOffset(const MCSymbol *Label, uint64_t Offset) const
Emit something like ".long Label + Offset" or ".quad Label + Offset" depending on the DWARF format.
void emitInt8(int Value) const
Emit a byte directive and value.
bool hasDebugInfo() const
Returns true if valid debug info is present.
void emitDwarfUnitLength(uint64_t Length, const Twine &Comment) const
Emit a unit length field.
MCContext & OutContext
This is the context for the output file that we are streaming.
MCSymbol * createTempSymbol(const Twine &Name) const
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
void emitLabelReference(const MCSymbol *Label, unsigned Size, bool IsSectionRelative=false) const
Emit something like ".long Label" where the size in bytes of the directive is specified by Size and L...
unsigned int getDwarfOffsetByteSize() const
Returns 4 for DWARF32 and 8 for DWARF64.
MCSymbol * getFunctionEnd() const
void emitInt16(int Value) const
Emit a short directive and value.
const DataLayout & getDataLayout() const
Return information about data layout.
uint16_t getDwarfVersion() const
void emitInt8(uint8_t Byte, const Twine &Comment) override
const bool GenerateComments
Only verbose textual output needs comments.
virtual void emitULEB128(uint64_t DWord, const Twine &Comment="", unsigned PadTo=0)=0
virtual void emitSLEB128(uint64_t DWord, const Twine &Comment="")=0
virtual void emitInt8(uint8_t Byte, const Twine &Comment="")=0
virtual unsigned emitDIERef(const DIE &D)=0
Basic type, like 'int' or 'float'.
bool getDebugInfoForProfiling() const
bool isDebugDirectivesOnly() const
StringRef getFlags() const
static std::optional< DebugNameTableKind > getNameTableKind(StringRef Str)
unsigned getRuntimeVersion() const
bool getSplitDebugInlining() const
StringRef getSysRoot() const
StringRef getProducer() const
unsigned getSourceLanguage() const
uint64_t getDWOId() const
StringRef getSplitDebugFilename() const
static std::optional< DebugEmissionKind > getEmissionKind(StringRef Str)
An object containing the capability of hashing and adding hash attributes onto a DIE.
uint64_t computeCUSignature(StringRef DWOName, const DIE &Die)
Computes the CU signature.
void setSection(MCSection *Section)
Set the section that this DIEUnit will be emitted into.
A structured debug information entry.
DIEValue findAttribute(dwarf::Attribute Attribute) const
Find a value in the DIE with the attribute given.
const DIE * getUnitDie() const
Climb up the parent chain to get the compile unit or type unit DIE that this DIE belongs to.
dwarf::Tag getTag() const
Holds a DIExpression and keeps track of how many operands have been consumed so far.
bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
unsigned getNumElements() const
bool isImplicit() const
Return whether this is an implicit location description.
static std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
static std::optional< const DIExpression * > convertToNonVariadicExpression(const DIExpression *Expr)
If Expr is a valid single-location expression, i.e.
ArrayRef< uint64_t > getElements() const
DIMacroNodeArray getElements() const
Tagged DWARF-like metadata node.
Base class for scope-like contexts.
StringRef getFilename() const
StringRef getName() const
StringRef getDirectory() const
std::optional< StringRef > getSource() const
DIScope * getScope() const
DIScope * getScope() const
void addTypeUnitSignature(DwarfTypeUnit &U)
Add a type unit Signature.
void convertDieToOffset()
Convert DIE entries to explicit offset.
void addTypeUnitSymbol(DwarfTypeUnit &U)
Add a type unit start symbol.
void addTypeEntries(DWARF5AccelTable &Table)
A DataExtractor (typically for an in-memory copy of an object-file section) plus a relocation map for...
This class represents an Operation in the Expression.
std::optional< unsigned > getSubCode() const
uint64_t getEndOffset() const
Encoding
Size and signedness of expression operations' operands.
const Description & getDescription() const
uint64_t getOperandEndOffset(unsigned Idx) const
uint64_t getRawOperand(unsigned Idx) const
bool isLittleEndian() const
Layout endianness...
Used for tracking debug info about call site parameters.
This class is defined as the common parent of DbgVariable and DbgLabel such that it could levarage po...
bool hasNonEmptyLocation(const Entries &Entries) const
Test whether a vector of entries features any non-empty locations.
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.
This class is used to track local variable information.
const DILocalVariable * getVariable() const
const DIType * getType() const
Base class for debug information backends.
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< std::string > getComments(const Entry &E) const
ArrayRef< Entry > getEntries(const List &L) const
ArrayRef< char > getBytes(const Entry &E) const
MCSymbol * getSym() const
void setSym(MCSymbol *Sym)
ArrayRef< List > getLists() const
MDNode * getScope() const
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
void constructAbstractSubprogramScopeDIE(LexicalScope *Scope)
void addRange(RangeSpan Range)
addRange - Add an address range to the list of ranges for this unit.
void createAbstractEntity(const DINode *Node, LexicalScope *Scope)
DIE & constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope, MCSymbol *LineTableSym)
Construct a DIE for this subprogram 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
bool hasDwarfPubSections() const
Collects and handles dwarf debug information.
bool useSegmentedStringOffsetsTable() const
Returns whether to generate a string offsets table with (possibly shared) contributions from each CU ...
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.
bool emitDebugEntryValues() const
uint16_t getDwarfVersion() const
Returns the Dwarf Version.
void emitDebugLocEntry(ByteStreamer &Streamer, const DebugLocStream::Entry &Entry, const DwarfCompileUnit *CU)
Emit an entry for the debug loc section.
void addAccelNamespace(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
void setCurrentDWARF5AccelTable(const DWARF5AccelTableKind Kind)
Sets the current DWARF5AccelTable to use.
bool alwaysUseRanges(const DwarfCompileUnit &) const
Returns whether range encodings should be used for single entry range lists.
void beginModule(Module *M) override
Emit all Dwarf sections that should come prior to the content.
void addSubprogramNames(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, const DISubprogram *SP, DIE &Die)
bool useAllLinkageNames() const
Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
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
void skippedNonDebugFunction() override
void addArangeLabel(SymbolCU SCU)
Add a label so that arange data can be generated for it.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
AddressPool & getAddressPool()
DWARF5AccelTable & getCurrentDWARF5AccelTable()
Returns either CU or TU DWARF5AccelTable.
bool useSectionsAsReferences() const
Returns whether to use sections as labels rather than temp symbols.
const DebugLocStream & getDebugLocs() const
Returns the entries for the .debug_loc section.
bool shareAcrossDWOCUs() const
void terminateLineTable(const DwarfCompileUnit *CU)
Terminate the line table by adding the last range label.
void endFunctionImpl(const MachineFunction *MF) override
Gather and emit post-function debug information.
void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry, const DwarfCompileUnit *CU)
Emit the location for a debug loc entry, including the size header.
const MCSymbol * getSectionLabel(const MCSection *S)
static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, const DbgValueLoc &Value, DwarfExpression &DwarfExpr)
bool useSplitDwarf() const
Returns whether or not to change the current debug info for the split dwarf proposal support.
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.
void addAccelName(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
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.
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.
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.
void finalize()
This needs to be called last to commit any pending changes.
void addFragmentOffset(const DIExpression *Expr)
If applicable, emit an empty DW_OP_piece / DW_OP_bit_piece to advance to the fragment described by Ex...
void setMemoryLocationKind()
Lock this down to become a memory location description.
std::optional< uint8_t > TagOffset
void addConstantFP(const APFloat &Value, const AsmPrinter &AP)
Emit an floating point constant.
bool addMachineRegExpression(const TargetRegisterInfo &TRI, DIExpressionCursor &Expr, llvm::Register MachineReg, unsigned FragmentOffsetInBits=0)
Emit a machine register location.
void addUnsignedConstant(uint64_t Value)
Emit an unsigned constant.
void addExpression(DIExpressionCursor &&Expr)
Emit all remaining operations in the DIExpressionCursor.
void addSignedConstant(int64_t Value)
Emit a signed constant.
void addWasmLocation(unsigned Index, uint64_t Offset)
Emit location information expressed via WebAssembly location + offset The Index is an identifier for ...
void beginEntryValueExpression(DIExpressionCursor &ExprCursor)
Begin emission of an entry value dwarf operation.
void addScopeLabel(LexicalScope *LS, DbgLabel *Label)
void addUnit(std::unique_ptr< DwarfCompileUnit > U)
Add a unit to the list of CUs.
void computeSizeAndOffsets()
Compute the size and offset of all the DIEs.
void setRnglistsTableBaseSym(MCSymbol *Sym)
DenseMap< LexicalScope *, ScopeVars > & getScopeVariables()
unsigned computeSizeAndOffsetsForUnit(DwarfUnit *TheU)
Compute the size and offset of all the DIEs in the given unit.
void emitUnits(bool UseOffsets)
Emit all of the units to the section listed with the given abbreviation section.
void emitUnit(DwarfUnit *TheU, bool UseOffsets)
Emit the given unit to its section.
const SmallVectorImpl< RangeSpanList > & getRangeLists() const
getRangeLists - Get the vector of range lists.
MCSymbol * getStringOffsetsStartSym() const
MCSymbol * getRnglistsTableBaseSym() const
DwarfStringPool & getStringPool()
Returns the string pool.
void emitAbbrevs(MCSection *)
Emit a set of abbreviations to the specific section.
void emitStrings(MCSection *StrSection, MCSection *OffsetSection=nullptr, bool UseRelativeOffsets=false)
Emit all of the strings to the section given.
DenseMap< LexicalScope *, LabelList > & getScopeLabels()
void addScopeVariable(LexicalScope *LS, DbgVariable *Var)
DenseMap< const DILocalScope *, DIE * > & getAbstractScopeDIEs()
const SmallVectorImpl< std::unique_ptr< DwarfCompileUnit > > & getUnits()
DwarfStringPoolEntryRef: Dwarf string pool entry reference.
unsigned getIndex() const
MCSymbol * getSymbol() const
EntryRef getEntry(AsmPrinter &Asm, StringRef Str)
Get a reference to an entry in the string pool.
EntryRef getIndexedEntry(AsmPrinter &Asm, StringRef Str)
Same as getEntry, except that you can use EntryRef::getIndex to obtain a unique ID of this entry (e....
void emitStringOffsetsTableHeader(AsmPrinter &Asm, MCSection *OffsetSection, MCSymbol *StartSym)
void setTypeSignature(uint64_t Signature)
void setType(const DIE *Ty)
This dwarf writer support class manages information associated with a source file.
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
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.
DISubprogram * getSubprogram() const
Get the attached subprogram.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
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.
LexicalScope - This class is used to track scope information.
SmallVectorImpl< InsnRange > & getRanges()
const DILocalScope * getScopeNode() const
LexicalScopes - This class provides interface to collect and use lexical scoping information from mac...
LexicalScope * getOrCreateAbstractScope(const DILocalScope *Scope)
getOrCreateAbstractScope - Find or create an abstract lexical scope.
LexicalScope * findLexicalScope(const DILocation *DL)
findLexicalScope - Find lexical scope, either regular or inlined, for the given DebugLoc.
ArrayRef< LexicalScope * > getAbstractScopesList() const
getAbstractScopesList - Return a reference to list of abstract scopes.
LexicalScope * findInlinedScope(const DILocalScope *N, const DILocation *IA)
findInlinedScope - Find an inlined scope for the given scope/inlined-at.
LexicalScope * findAbstractScope(const DILocalScope *N)
findAbstractScope - Find an abstract scope or return null.
bool empty()
empty - Return true if there is any lexical scope information available.
LexicalScope * getCurrentFunctionScope() const
getCurrentFunctionScope - Return lexical scope for the current function.
Single value location description.
Single(DbgValueLoc ValueLoc)
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
uint16_t getDwarfVersion() const
dwarf::DwarfFormat getDwarfFormat() const
void maybeSetRootFile(StringRef Directory, StringRef FileName, std::optional< MD5::MD5Result > Checksum, std::optional< StringRef > Source)
void Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params, MCSection *Section) const
static void make(MCStreamer *MCOS, MCSection *Section)
MCSection * getDwarfLoclistsSection() const
MCSection * getDwarfAccelTypesSection() const
MCSection * getDwarfGnuPubNamesSection() const
MCSection * getDwarfStrOffDWOSection() const
MCSection * getDwarfRangesSection() const
MCSection * getDwarfAccelNamespaceSection() const
MCSection * getDwarfLineDWOSection() const
MCSection * getDwarfStrOffSection() const
MCSection * getDwarfInfoDWOSection() const
MCSection * getDwarfTypesDWOSection() const
MCSection * getDwarfPubNamesSection() const
MCSection * getDwarfMacroSection() const
MCSection * getDwarfStrSection() const
MCSection * getDwarfLoclistsDWOSection() const
MCSection * getDwarfMacinfoDWOSection() const
MCSection * getDwarfRnglistsSection() const
MCSection * getDwarfAddrSection() const
MCSection * getDwarfInfoSection() const
MCSection * getDwarfPubTypesSection() const
MCSection * getDwarfTypesSection(uint64_t Hash) const
MCSection * getDwarfGnuPubTypesSection() const
MCSection * getDwarfStrDWOSection() const
MCSection * getDwarfAccelNamesSection() const
MCSection * getDwarfAbbrevDWOSection() const
MCSection * getDwarfRnglistsDWOSection() const
MCSection * getDwarfAbbrevSection() const
MCSection * getDwarfMacinfoSection() const
MCSection * getDwarfLocDWOSection() const
MCSection * getDwarfARangesSection() const
MCSection * getDwarfAccelObjCSection() const
MCSection * getDwarfLocSection() const
MCSection * getDwarfMacroDWOSection() const
Instances of this class represent a uniqued identifier for a section in the current translation unit.
MCSymbol * getBeginSymbol()
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
std::string SplitDwarfFile
void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
succ_iterator succ_begin()
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
iterator_range< pred_iterator > predecessors()
Align getAlignment() const
Return alignment of the basic block.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const CallSiteInfoMap & getCallSitesInfo() const
bool hasBBSections() const
Returns true if this function has basic block sections enabled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & back() const
VariableDbgInfoMapTy & getVariableDbgInfo()
const MachineBasicBlock & front() const
MachineBasicBlock iterator that automatically skips over MIs that are inside bundles (i....
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
bool isCall(QueryType Type=AnyInBundle) const
iterator_range< mop_iterator > uses()
Returns a range that includes all operands which may be register uses.
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...
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
const Module * getModule() 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.
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Root of the metadata hierarchy.
A Module instance is used to store all the information related to an LLVM module.
iterator_range< debug_compile_units_iterator > debug_compile_units() const
Return an iterator for all DICompileUnits listed in this Module's llvm.dbg.cu named metadata node and...
unsigned getDwarfVersion() const
Returns the Dwarf Version by checking module flags.
bool isDwarf64() const
Returns the DWARF format by checking module flags.
Wrapper class representing virtual and physical registers.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
bool empty() const
Determine if the SetVector is empty or not.
Implements a dense probed hash-table based set with some number of buckets stored inline.
A SetVector that performs no allocations if smaller than a certain size.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
const_iterator begin() const
const_iterator end() const
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
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",...
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
TargetInstrInfo - Interface to description of machine instruction set.
const Triple & getTargetTriple() const
MCTargetOptions MCOptions
Machine level options.
DebuggerKind DebuggerTuning
Which debugger to tune for.
bool ShouldEmitDebugEntryValues() const
NOTE: There are targets that still do not support the debug entry values production.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetLowering * getTargetLowering() const
Triple - Helper class for working with autoconf configuration names.
bool isNVPTX() const
Tests whether the target is NVPTX (32- or 64-bit).
bool isWasm() const
Tests whether the target is wasm (32- and 64-bit).
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
StringRef getName() const
Return a constant reference to the value's name.
void dump() const
Support for debugging, callable in GDB: V->dump()
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
reverse_self_iterator getReverseIterator()
self_iterator getIterator()
StringRef RangeListEncodingString(unsigned Encoding)
StringRef GDBIndexEntryLinkageString(GDBIndexEntryLinkage Linkage)
StringRef MacroString(unsigned Encoding)
StringRef LocListEncodingString(unsigned Encoding)
StringRef GnuMacroString(unsigned Encoding)
StringRef MacinfoString(unsigned Encoding)
StringRef OperationEncodingString(unsigned Encoding)
StringRef GDBIndexEntryKindString(GDBIndexEntryKind Kind)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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)
bool isCPlusPlus(SourceLanguage S)
@ DW_ARANGES_VERSION
Section version number for .debug_aranges.
@ DW_PUBNAMES_VERSION
Section version number for .debug_pubnames.
@ DWARF_VERSION
Other constants.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
MCSymbol * emitListsTableHeaderStart(MCStreamer &S)
NodeAddr< InstrNode * > Instr
This is an optimization pass for GlobalISel generic memory operations.
bool operator<(int64_t V1, const APSInt &V2)
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.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
auto unique(Range &&R, Predicate P)
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void sort(IteratorTy Start, IteratorTy End)
AccelTableKind
The kind of accelerator tables we should emit.
@ Default
Platform default.
@ Apple
.apple_names, .apple_namespaces, .apple_types, .apple_objc.
@ Dwarf
DWARF v5 .debug_names.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
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...
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...
@ Global
Append to llvm.global_dtors.
@ Ref
The access may reference the value stored in memory.
void emitAppleAccelTable(AsmPrinter *Asm, AccelTable< DataT > &Contents, StringRef Prefix, const MCSymbol *SecBegin)
Emit an Apple Accelerator Table consisting of entries in the specified AccelTable.
void emitDWARF5AccelTable(AsmPrinter *Asm, DWARF5AccelTable &Contents, const DwarfDebug &DD, ArrayRef< std::unique_ptr< DwarfCompileUnit > > CUs)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
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.
Implement std::hash so that hash_code can be used in STL containers.
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.
Description of the encoding of one expression Op.
SmallVector< Encoding > Op
Encoding for Op operands.
A pair of GlobalVariable and DIExpression.
Represents an entry-value location, or a fragment of one.
Single location defined by (potentially multiple) EntryValueInfo.
Single location defined by (potentially multiple) MMI entries.
void addFrameIndexExpr(const DIExpression *Expr, int FI)
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.
Helper used to pair up a symbol and its DWARF compile unit.
This struct describes target specific location.
Describes an entry of the various gnu_pub* debug sections.