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