Path: blob/main/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
35271 views
//===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains support for writing dwarf debug info into asm files.9//10//===----------------------------------------------------------------------===//1112#include "DwarfDebug.h"13#include "ByteStreamer.h"14#include "DIEHash.h"15#include "DwarfCompileUnit.h"16#include "DwarfExpression.h"17#include "DwarfUnit.h"18#include "llvm/ADT/APInt.h"19#include "llvm/ADT/Statistic.h"20#include "llvm/ADT/StringExtras.h"21#include "llvm/ADT/Twine.h"22#include "llvm/CodeGen/AsmPrinter.h"23#include "llvm/CodeGen/DIE.h"24#include "llvm/CodeGen/LexicalScopes.h"25#include "llvm/CodeGen/MachineBasicBlock.h"26#include "llvm/CodeGen/MachineFunction.h"27#include "llvm/CodeGen/MachineModuleInfo.h"28#include "llvm/CodeGen/MachineOperand.h"29#include "llvm/CodeGen/TargetInstrInfo.h"30#include "llvm/CodeGen/TargetLowering.h"31#include "llvm/CodeGen/TargetRegisterInfo.h"32#include "llvm/CodeGen/TargetSubtargetInfo.h"33#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"34#include "llvm/DebugInfo/DWARF/DWARFExpression.h"35#include "llvm/IR/Constants.h"36#include "llvm/IR/Function.h"37#include "llvm/IR/GlobalVariable.h"38#include "llvm/IR/Module.h"39#include "llvm/MC/MCAsmInfo.h"40#include "llvm/MC/MCContext.h"41#include "llvm/MC/MCSection.h"42#include "llvm/MC/MCStreamer.h"43#include "llvm/MC/MCSymbol.h"44#include "llvm/MC/MCTargetOptions.h"45#include "llvm/MC/MachineLocation.h"46#include "llvm/MC/SectionKind.h"47#include "llvm/Support/Casting.h"48#include "llvm/Support/CommandLine.h"49#include "llvm/Support/Debug.h"50#include "llvm/Support/ErrorHandling.h"51#include "llvm/Support/MD5.h"52#include "llvm/Support/raw_ostream.h"53#include "llvm/Target/TargetLoweringObjectFile.h"54#include "llvm/Target/TargetMachine.h"55#include "llvm/TargetParser/Triple.h"56#include <algorithm>57#include <cstddef>58#include <iterator>59#include <optional>60#include <string>6162using namespace llvm;6364#define DEBUG_TYPE "dwarfdebug"6566STATISTIC(NumCSParams, "Number of dbg call site params created");6768static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(69"use-dwarf-ranges-base-address-specifier", cl::Hidden,70cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));7172static cl::opt<bool> GenerateARangeSection("generate-arange-section",73cl::Hidden,74cl::desc("Generate dwarf aranges"),75cl::init(false));7677static cl::opt<bool>78GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,79cl::desc("Generate DWARF4 type units."),80cl::init(false));8182static cl::opt<bool> SplitDwarfCrossCuReferences(83"split-dwarf-cross-cu-references", cl::Hidden,84cl::desc("Enable cross-cu references in DWO files"), cl::init(false));8586enum DefaultOnOff { Default, Enable, Disable };8788static cl::opt<DefaultOnOff> UnknownLocations(89"use-unknown-locations", cl::Hidden,90cl::desc("Make an absence of debug location information explicit."),91cl::values(clEnumVal(Default, "At top of block or after label"),92clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),93cl::init(Default));9495static cl::opt<AccelTableKind> AccelTables(96"accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),97cl::values(clEnumValN(AccelTableKind::Default, "Default",98"Default for platform"),99clEnumValN(AccelTableKind::None, "Disable", "Disabled."),100clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),101clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),102cl::init(AccelTableKind::Default));103104static cl::opt<DefaultOnOff>105DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,106cl::desc("Use inlined strings rather than string section."),107cl::values(clEnumVal(Default, "Default for platform"),108clEnumVal(Enable, "Enabled"),109clEnumVal(Disable, "Disabled")),110cl::init(Default));111112static cl::opt<bool>113NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,114cl::desc("Disable emission .debug_ranges section."),115cl::init(false));116117static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(118"dwarf-sections-as-references", cl::Hidden,119cl::desc("Use sections+offset as references rather than labels."),120cl::values(clEnumVal(Default, "Default for platform"),121clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),122cl::init(Default));123124static cl::opt<bool>125UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden,126cl::desc("Emit the GNU .debug_macro format with DWARF <5"),127cl::init(false));128129static cl::opt<DefaultOnOff> DwarfOpConvert(130"dwarf-op-convert", cl::Hidden,131cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"),132cl::values(clEnumVal(Default, "Default for platform"),133clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),134cl::init(Default));135136enum LinkageNameOption {137DefaultLinkageNames,138AllLinkageNames,139AbstractLinkageNames140};141142static cl::opt<LinkageNameOption>143DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,144cl::desc("Which DWARF linkage-name attributes to emit."),145cl::values(clEnumValN(DefaultLinkageNames, "Default",146"Default for platform"),147clEnumValN(AllLinkageNames, "All", "All"),148clEnumValN(AbstractLinkageNames, "Abstract",149"Abstract subprograms")),150cl::init(DefaultLinkageNames));151152static cl::opt<DwarfDebug::MinimizeAddrInV5> MinimizeAddrInV5Option(153"minimize-addr-in-v5", cl::Hidden,154cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more "155"address pool entry sharing to reduce relocations/object size"),156cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default",157"Default address minimization strategy"),158clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges",159"Use rnglists for contiguous ranges if that allows "160"using a pre-existing base address"),161clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions,162"Expressions",163"Use exprloc addrx+offset expressions for any "164"address with a prior base address"),165clEnumValN(DwarfDebug::MinimizeAddrInV5::Form, "Form",166"Use addrx+offset extension form for any address "167"with a prior base address"),168clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled",169"Stuff")),170cl::init(DwarfDebug::MinimizeAddrInV5::Default));171172static constexpr unsigned ULEB128PadSize = 4;173174void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {175getActiveStreamer().emitInt8(176Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)177: dwarf::OperationEncodingString(Op));178}179180void DebugLocDwarfExpression::emitSigned(int64_t Value) {181getActiveStreamer().emitSLEB128(Value, Twine(Value));182}183184void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {185getActiveStreamer().emitULEB128(Value, Twine(Value));186}187188void DebugLocDwarfExpression::emitData1(uint8_t Value) {189getActiveStreamer().emitInt8(Value, Twine(Value));190}191192void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {193assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");194getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);195}196197bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,198llvm::Register MachineReg) {199// This information is not available while emitting .debug_loc entries.200return false;201}202203void DebugLocDwarfExpression::enableTemporaryBuffer() {204assert(!IsBuffering && "Already buffering?");205if (!TmpBuf)206TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);207IsBuffering = true;208}209210void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }211212unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {213return TmpBuf ? TmpBuf->Bytes.size() : 0;214}215216void DebugLocDwarfExpression::commitTemporaryBuffer() {217if (!TmpBuf)218return;219for (auto Byte : enumerate(TmpBuf->Bytes)) {220const char *Comment = (Byte.index() < TmpBuf->Comments.size())221? TmpBuf->Comments[Byte.index()].c_str()222: "";223OutBS.emitInt8(Byte.value(), Comment);224}225TmpBuf->Bytes.clear();226TmpBuf->Comments.clear();227}228229const DIType *DbgVariable::getType() const {230return getVariable()->getType();231}232233/// Get .debug_loc entry for the instruction range starting at MI.234static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {235const DIExpression *Expr = MI->getDebugExpression();236auto SingleLocExprOpt = DIExpression::convertToNonVariadicExpression(Expr);237const bool IsVariadic = !SingleLocExprOpt;238// If we have a variadic debug value instruction that is equivalent to a239// non-variadic instruction, then convert it to non-variadic form here.240if (!IsVariadic && !MI->isNonListDebugValue()) {241assert(MI->getNumDebugOperands() == 1 &&242"Mismatched DIExpression and debug operands for debug instruction.");243Expr = *SingleLocExprOpt;244}245assert(MI->getNumOperands() >= 3);246SmallVector<DbgValueLocEntry, 4> DbgValueLocEntries;247for (const MachineOperand &Op : MI->debug_operands()) {248if (Op.isReg()) {249MachineLocation MLoc(Op.getReg(),250MI->isNonListDebugValue() && MI->isDebugOffsetImm());251DbgValueLocEntries.push_back(DbgValueLocEntry(MLoc));252} else if (Op.isTargetIndex()) {253DbgValueLocEntries.push_back(254DbgValueLocEntry(TargetIndexLocation(Op.getIndex(), Op.getOffset())));255} else if (Op.isImm())256DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getImm()));257else if (Op.isFPImm())258DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getFPImm()));259else if (Op.isCImm())260DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getCImm()));261else262llvm_unreachable("Unexpected debug operand in DBG_VALUE* instruction!");263}264return DbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);265}266267static uint64_t getFragmentOffsetInBits(const DIExpression &Expr) {268std::optional<DIExpression::FragmentInfo> Fragment = Expr.getFragmentInfo();269return Fragment ? Fragment->OffsetInBits : 0;270}271272bool llvm::operator<(const FrameIndexExpr &LHS, const FrameIndexExpr &RHS) {273return getFragmentOffsetInBits(*LHS.Expr) <274getFragmentOffsetInBits(*RHS.Expr);275}276277bool llvm::operator<(const EntryValueInfo &LHS, const EntryValueInfo &RHS) {278return getFragmentOffsetInBits(LHS.Expr) < getFragmentOffsetInBits(RHS.Expr);279}280281Loc::Single::Single(DbgValueLoc ValueLoc)282: ValueLoc(std::make_unique<DbgValueLoc>(ValueLoc)),283Expr(ValueLoc.getExpression()) {284if (!Expr->getNumElements())285Expr = nullptr;286}287288Loc::Single::Single(const MachineInstr *DbgValue)289: Single(getDebugLocValue(DbgValue)) {}290291const std::set<FrameIndexExpr> &Loc::MMI::getFrameIndexExprs() const {292return FrameIndexExprs;293}294295void Loc::MMI::addFrameIndexExpr(const DIExpression *Expr, int FI) {296FrameIndexExprs.insert({FI, Expr});297assert((FrameIndexExprs.size() == 1 ||298llvm::all_of(FrameIndexExprs,299[](const FrameIndexExpr &FIE) {300return FIE.Expr && FIE.Expr->isFragment();301})) &&302"conflicting locations for variable");303}304305static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,306bool GenerateTypeUnits,307DebuggerKind Tuning,308const Triple &TT) {309// Honor an explicit request.310if (AccelTables != AccelTableKind::Default)311return AccelTables;312313// Generating DWARF5 acceleration table.314// Currently Split dwarf and non ELF format is not supported.315if (GenerateTypeUnits && (DwarfVersion < 5 || !TT.isOSBinFormatELF()))316return AccelTableKind::None;317318// Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5319// always implies debug_names. For lower standard versions we use apple320// accelerator tables on apple platforms and debug_names elsewhere.321if (DwarfVersion >= 5)322return AccelTableKind::Dwarf;323if (Tuning == DebuggerKind::LLDB)324return TT.isOSBinFormatMachO() ? AccelTableKind::Apple325: AccelTableKind::Dwarf;326return AccelTableKind::None;327}328329DwarfDebug::DwarfDebug(AsmPrinter *A)330: DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),331InfoHolder(A, "info_string", DIEValueAllocator),332SkeletonHolder(A, "skel_string", DIEValueAllocator),333IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {334const Triple &TT = Asm->TM.getTargetTriple();335336// Make sure we know our "debugger tuning". The target option takes337// precedence; fall back to triple-based defaults.338if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)339DebuggerTuning = Asm->TM.Options.DebuggerTuning;340else if (IsDarwin)341DebuggerTuning = DebuggerKind::LLDB;342else if (TT.isPS())343DebuggerTuning = DebuggerKind::SCE;344else if (TT.isOSAIX())345DebuggerTuning = DebuggerKind::DBX;346else347DebuggerTuning = DebuggerKind::GDB;348349if (DwarfInlinedStrings == Default)350UseInlineStrings = TT.isNVPTX() || tuneForDBX();351else352UseInlineStrings = DwarfInlinedStrings == Enable;353354UseLocSection = !TT.isNVPTX();355356HasAppleExtensionAttributes = tuneForLLDB();357358// Handle split DWARF.359HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();360361// SCE defaults to linkage names only for abstract subprograms.362if (DwarfLinkageNames == DefaultLinkageNames)363UseAllLinkageNames = !tuneForSCE();364else365UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;366367unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;368unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber369: MMI->getModule()->getDwarfVersion();370// Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.371DwarfVersion =372TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);373374bool Dwarf64 = DwarfVersion >= 3 && // DWARF64 was introduced in DWARFv3.375TT.isArch64Bit(); // DWARF64 requires 64-bit relocations.376377// Support DWARF64378// 1: For ELF when requested.379// 2: For XCOFF64: the AIX assembler will fill in debug section lengths380// according to the DWARF64 format for 64-bit assembly, so we must use381// DWARF64 in the compiler too for 64-bit mode.382Dwarf64 &=383((Asm->TM.Options.MCOptions.Dwarf64 || MMI->getModule()->isDwarf64()) &&384TT.isOSBinFormatELF()) ||385TT.isOSBinFormatXCOFF();386387if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())388report_fatal_error("XCOFF requires DWARF64 for 64-bit mode!");389390UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();391392// Use sections as references. Force for NVPTX.393if (DwarfSectionsAsReferences == Default)394UseSectionsAsReferences = TT.isNVPTX();395else396UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;397398// Don't generate type units for unsupported object file formats.399GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() ||400A->TM.getTargetTriple().isOSBinFormatWasm()) &&401GenerateDwarfTypeUnits;402403TheAccelTableKind = computeAccelTableKind(404DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());405406// Work around a GDB bug. GDB doesn't support the standard opcode;407// SCE doesn't support GNU's; LLDB prefers the standard opcode, which408// is defined as of DWARF 3.409// See GDB bug 11616 - DW_OP_form_tls_address is unimplemented410// https://sourceware.org/bugzilla/show_bug.cgi?id=11616411UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;412413UseDWARF2Bitfields = DwarfVersion < 4;414415// The DWARF v5 string offsets table has - possibly shared - contributions416// from each compile and type unit each preceded by a header. The string417// offsets table used by the pre-DWARF v5 split-DWARF implementation uses418// a monolithic string offsets table without any header.419UseSegmentedStringOffsetsTable = DwarfVersion >= 5;420421// Emit call-site-param debug info for GDB and LLDB, if the target supports422// the debug entry values feature. It can also be enabled explicitly.423EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();424425// It is unclear if the GCC .debug_macro extension is well-specified426// for split DWARF. For now, do not allow LLVM to emit it.427UseDebugMacroSection =428DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());429if (DwarfOpConvert == Default)430EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO()));431else432EnableOpConvert = (DwarfOpConvert == Enable);433434// Split DWARF would benefit object size significantly by trading reductions435// in address pool usage for slightly increased range list encodings.436if (DwarfVersion >= 5)437MinimizeAddr = MinimizeAddrInV5Option;438439Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);440Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64441: dwarf::DWARF32);442}443444// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.445DwarfDebug::~DwarfDebug() = default;446447static bool isObjCClass(StringRef Name) {448return Name.starts_with("+") || Name.starts_with("-");449}450451static bool hasObjCCategory(StringRef Name) {452if (!isObjCClass(Name))453return false;454455return Name.contains(") ");456}457458static void getObjCClassCategory(StringRef In, StringRef &Class,459StringRef &Category) {460if (!hasObjCCategory(In)) {461Class = In.slice(In.find('[') + 1, In.find(' '));462Category = "";463return;464}465466Class = In.slice(In.find('[') + 1, In.find('('));467Category = In.slice(In.find('[') + 1, In.find(' '));468}469470static StringRef getObjCMethodName(StringRef In) {471return In.slice(In.find(' ') + 1, In.find(']'));472}473474// Add the various names to the Dwarf accelerator table names.475void DwarfDebug::addSubprogramNames(476const DwarfUnit &Unit,477const DICompileUnit::DebugNameTableKind NameTableKind,478const DISubprogram *SP, DIE &Die) {479if (getAccelTableKind() != AccelTableKind::Apple &&480NameTableKind != DICompileUnit::DebugNameTableKind::Apple &&481NameTableKind == DICompileUnit::DebugNameTableKind::None)482return;483484if (!SP->isDefinition())485return;486487if (SP->getName() != "")488addAccelName(Unit, NameTableKind, SP->getName(), Die);489490// If the linkage name is different than the name, go ahead and output that as491// well into the name table. Only do that if we are going to actually emit492// that name.493if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&494(useAllLinkageNames() || InfoHolder.getAbstractScopeDIEs().lookup(SP)))495addAccelName(Unit, NameTableKind, SP->getLinkageName(), Die);496497// If this is an Objective-C selector name add it to the ObjC accelerator498// too.499if (isObjCClass(SP->getName())) {500StringRef Class, Category;501getObjCClassCategory(SP->getName(), Class, Category);502addAccelObjC(Unit, NameTableKind, Class, Die);503if (Category != "")504addAccelObjC(Unit, NameTableKind, Category, Die);505// Also add the base method name to the name table.506addAccelName(Unit, NameTableKind, getObjCMethodName(SP->getName()), Die);507}508}509510/// Check whether we should create a DIE for the given Scope, return true511/// if we don't create a DIE (the corresponding DIE is null).512bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {513if (Scope->isAbstractScope())514return false;515516// We don't create a DIE if there is no Range.517const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();518if (Ranges.empty())519return true;520521if (Ranges.size() > 1)522return false;523524// We don't create a DIE if we have a single Range and the end label525// is null.526return !getLabelAfterInsn(Ranges.front().second);527}528529template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {530F(CU);531if (auto *SkelCU = CU.getSkeleton())532if (CU.getCUNode()->getSplitDebugInlining())533F(*SkelCU);534}535536bool DwarfDebug::shareAcrossDWOCUs() const {537return SplitDwarfCrossCuReferences;538}539540void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,541LexicalScope *Scope) {542assert(Scope && Scope->getScopeNode());543assert(Scope->isAbstractScope());544assert(!Scope->getInlinedAt());545546auto *SP = cast<DISubprogram>(Scope->getScopeNode());547548// Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram549// was inlined from another compile unit.550if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())551// Avoid building the original CU if it won't be used552SrcCU.constructAbstractSubprogramScopeDIE(Scope);553else {554auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());555if (auto *SkelCU = CU.getSkeleton()) {556(shareAcrossDWOCUs() ? CU : SrcCU)557.constructAbstractSubprogramScopeDIE(Scope);558if (CU.getCUNode()->getSplitDebugInlining())559SkelCU->constructAbstractSubprogramScopeDIE(Scope);560} else561CU.constructAbstractSubprogramScopeDIE(Scope);562}563}564565/// Represents a parameter whose call site value can be described by applying a566/// debug expression to a register in the forwarded register worklist.567struct FwdRegParamInfo {568/// The described parameter register.569unsigned ParamReg;570571/// Debug expression that has been built up when walking through the572/// instruction chain that produces the parameter's value.573const DIExpression *Expr;574};575576/// Register worklist for finding call site values.577using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>;578/// Container for the set of registers known to be clobbered on the path to a579/// call site.580using ClobberedRegSet = SmallSet<Register, 16>;581582/// Append the expression \p Addition to \p Original and return the result.583static const DIExpression *combineDIExpressions(const DIExpression *Original,584const DIExpression *Addition) {585std::vector<uint64_t> Elts = Addition->getElements().vec();586// Avoid multiple DW_OP_stack_values.587if (Original->isImplicit() && Addition->isImplicit())588llvm::erase(Elts, dwarf::DW_OP_stack_value);589const DIExpression *CombinedExpr =590(Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;591return CombinedExpr;592}593594/// Emit call site parameter entries that are described by the given value and595/// debug expression.596template <typename ValT>597static void finishCallSiteParams(ValT Val, const DIExpression *Expr,598ArrayRef<FwdRegParamInfo> DescribedParams,599ParamSet &Params) {600for (auto Param : DescribedParams) {601bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;602603// TODO: Entry value operations can currently not be combined with any604// other expressions, so we can't emit call site entries in those cases.605if (ShouldCombineExpressions && Expr->isEntryValue())606continue;607608// If a parameter's call site value is produced by a chain of609// instructions we may have already created an expression for the610// parameter when walking through the instructions. Append that to the611// base expression.612const DIExpression *CombinedExpr =613ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)614: Expr;615assert((!CombinedExpr || CombinedExpr->isValid()) &&616"Combined debug expression is invalid");617618DbgValueLoc DbgLocVal(CombinedExpr, DbgValueLocEntry(Val));619DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);620Params.push_back(CSParm);621++NumCSParams;622}623}624625/// Add \p Reg to the worklist, if it's not already present, and mark that the626/// given parameter registers' values can (potentially) be described using627/// that register and an debug expression.628static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,629const DIExpression *Expr,630ArrayRef<FwdRegParamInfo> ParamsToAdd) {631auto I = Worklist.insert({Reg, {}});632auto &ParamsForFwdReg = I.first->second;633for (auto Param : ParamsToAdd) {634assert(none_of(ParamsForFwdReg,635[Param](const FwdRegParamInfo &D) {636return D.ParamReg == Param.ParamReg;637}) &&638"Same parameter described twice by forwarding reg");639640// If a parameter's call site value is produced by a chain of641// instructions we may have already created an expression for the642// parameter when walking through the instructions. Append that to the643// new expression.644const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);645ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});646}647}648649/// Interpret values loaded into registers by \p CurMI.650static void interpretValues(const MachineInstr *CurMI,651FwdRegWorklist &ForwardedRegWorklist,652ParamSet &Params,653ClobberedRegSet &ClobberedRegUnits) {654655const MachineFunction *MF = CurMI->getMF();656const DIExpression *EmptyExpr =657DIExpression::get(MF->getFunction().getContext(), {});658const auto &TRI = *MF->getSubtarget().getRegisterInfo();659const auto &TII = *MF->getSubtarget().getInstrInfo();660const auto &TLI = *MF->getSubtarget().getTargetLowering();661662// If an instruction defines more than one item in the worklist, we may run663// into situations where a worklist register's value is (potentially)664// described by the previous value of another register that is also defined665// by that instruction.666//667// This can for example occur in cases like this:668//669// $r1 = mov 123670// $r0, $r1 = mvrr $r1, 456671// call @foo, $r0, $r1672//673// When describing $r1's value for the mvrr instruction, we need to make sure674// that we don't finalize an entry value for $r0, as that is dependent on the675// previous value of $r1 (123 rather than 456).676//677// In order to not have to distinguish between those cases when finalizing678// entry values, we simply postpone adding new parameter registers to the679// worklist, by first keeping them in this temporary container until the680// instruction has been handled.681FwdRegWorklist TmpWorklistItems;682683// If the MI is an instruction defining one or more parameters' forwarding684// registers, add those defines.685ClobberedRegSet NewClobberedRegUnits;686auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,687SmallSetVector<unsigned, 4> &Defs) {688if (MI.isDebugInstr())689return;690691for (const MachineOperand &MO : MI.all_defs()) {692if (MO.getReg().isPhysical()) {693for (auto &FwdReg : ForwardedRegWorklist)694if (TRI.regsOverlap(FwdReg.first, MO.getReg()))695Defs.insert(FwdReg.first);696for (MCRegUnit Unit : TRI.regunits(MO.getReg()))697NewClobberedRegUnits.insert(Unit);698}699}700};701702// Set of worklist registers that are defined by this instruction.703SmallSetVector<unsigned, 4> FwdRegDefs;704705getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);706if (FwdRegDefs.empty()) {707// Any definitions by this instruction will clobber earlier reg movements.708ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),709NewClobberedRegUnits.end());710return;711}712713// It's possible that we find a copy from a non-volatile register to the param714// register, which is clobbered in the meantime. Test for clobbered reg unit715// overlaps before completing.716auto IsRegClobberedInMeantime = [&](Register Reg) -> bool {717for (auto &RegUnit : ClobberedRegUnits)718if (TRI.hasRegUnit(Reg, RegUnit))719return true;720return false;721};722723for (auto ParamFwdReg : FwdRegDefs) {724if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) {725if (ParamValue->first.isImm()) {726int64_t Val = ParamValue->first.getImm();727finishCallSiteParams(Val, ParamValue->second,728ForwardedRegWorklist[ParamFwdReg], Params);729} else if (ParamValue->first.isReg()) {730Register RegLoc = ParamValue->first.getReg();731Register SP = TLI.getStackPointerRegisterToSaveRestore();732Register FP = TRI.getFrameRegister(*MF);733bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);734if (!IsRegClobberedInMeantime(RegLoc) &&735(TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP)) {736MachineLocation MLoc(RegLoc, /*Indirect=*/IsSPorFP);737finishCallSiteParams(MLoc, ParamValue->second,738ForwardedRegWorklist[ParamFwdReg], Params);739} else {740// ParamFwdReg was described by the non-callee saved register741// RegLoc. Mark that the call site values for the parameters are742// dependent on that register instead of ParamFwdReg. Since RegLoc743// may be a register that will be handled in this iteration, we744// postpone adding the items to the worklist, and instead keep them745// in a temporary container.746addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second,747ForwardedRegWorklist[ParamFwdReg]);748}749}750}751}752753// Remove all registers that this instruction defines from the worklist.754for (auto ParamFwdReg : FwdRegDefs)755ForwardedRegWorklist.erase(ParamFwdReg);756757// Any definitions by this instruction will clobber earlier reg movements.758ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),759NewClobberedRegUnits.end());760761// Now that we are done handling this instruction, add items from the762// temporary worklist to the real one.763for (auto &New : TmpWorklistItems)764addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second);765TmpWorklistItems.clear();766}767768static bool interpretNextInstr(const MachineInstr *CurMI,769FwdRegWorklist &ForwardedRegWorklist,770ParamSet &Params,771ClobberedRegSet &ClobberedRegUnits) {772// Skip bundle headers.773if (CurMI->isBundle())774return true;775776// If the next instruction is a call we can not interpret parameter's777// forwarding registers or we finished the interpretation of all778// parameters.779if (CurMI->isCall())780return false;781782if (ForwardedRegWorklist.empty())783return false;784785// Avoid NOP description.786if (CurMI->getNumOperands() == 0)787return true;788789interpretValues(CurMI, ForwardedRegWorklist, Params, ClobberedRegUnits);790791return true;792}793794/// Try to interpret values loaded into registers that forward parameters795/// for \p CallMI. Store parameters with interpreted value into \p Params.796static void collectCallSiteParameters(const MachineInstr *CallMI,797ParamSet &Params) {798const MachineFunction *MF = CallMI->getMF();799const auto &CalleesMap = MF->getCallSitesInfo();800auto CSInfo = CalleesMap.find(CallMI);801802// There is no information for the call instruction.803if (CSInfo == CalleesMap.end())804return;805806const MachineBasicBlock *MBB = CallMI->getParent();807808// Skip the call instruction.809auto I = std::next(CallMI->getReverseIterator());810811FwdRegWorklist ForwardedRegWorklist;812813const DIExpression *EmptyExpr =814DIExpression::get(MF->getFunction().getContext(), {});815816// Add all the forwarding registers into the ForwardedRegWorklist.817for (const auto &ArgReg : CSInfo->second.ArgRegPairs) {818bool InsertedReg =819ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})820.second;821assert(InsertedReg && "Single register used to forward two arguments?");822(void)InsertedReg;823}824825// Do not emit CSInfo for undef forwarding registers.826for (const auto &MO : CallMI->uses())827if (MO.isReg() && MO.isUndef())828ForwardedRegWorklist.erase(MO.getReg());829830// We erase, from the ForwardedRegWorklist, those forwarding registers for831// which we successfully describe a loaded value (by using832// the describeLoadedValue()). For those remaining arguments in the working833// list, for which we do not describe a loaded value by834// the describeLoadedValue(), we try to generate an entry value expression835// for their call site value description, if the call is within the entry MBB.836// TODO: Handle situations when call site parameter value can be described837// as the entry value within basic blocks other than the first one.838bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();839840// Search for a loading value in forwarding registers inside call delay slot.841ClobberedRegSet ClobberedRegUnits;842if (CallMI->hasDelaySlot()) {843auto Suc = std::next(CallMI->getIterator());844// Only one-instruction delay slot is supported.845auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator());846(void)BundleEnd;847assert(std::next(Suc) == BundleEnd &&848"More than one instruction in call delay slot");849// Try to interpret value loaded by instruction.850if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params, ClobberedRegUnits))851return;852}853854// Search for a loading value in forwarding registers.855for (; I != MBB->rend(); ++I) {856// Try to interpret values loaded by instruction.857if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params, ClobberedRegUnits))858return;859}860861// Emit the call site parameter's value as an entry value.862if (ShouldTryEmitEntryVals) {863// Create an expression where the register's entry value is used.864DIExpression *EntryExpr = DIExpression::get(865MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});866for (auto &RegEntry : ForwardedRegWorklist) {867MachineLocation MLoc(RegEntry.first);868finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);869}870}871}872873void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,874DwarfCompileUnit &CU, DIE &ScopeDIE,875const MachineFunction &MF) {876// Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if877// the subprogram is required to have one.878if (!SP.areAllCallsDescribed() || !SP.isDefinition())879return;880881// Use DW_AT_call_all_calls to express that call site entries are present882// for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls883// because one of its requirements is not met: call site entries for884// optimized-out calls are elided.885CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));886887const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();888assert(TII && "TargetInstrInfo not found: cannot label tail calls");889890// Delay slot support check.891auto delaySlotSupported = [&](const MachineInstr &MI) {892if (!MI.isBundledWithSucc())893return false;894auto Suc = std::next(MI.getIterator());895auto CallInstrBundle = getBundleStart(MI.getIterator());896(void)CallInstrBundle;897auto DelaySlotBundle = getBundleStart(Suc);898(void)DelaySlotBundle;899// Ensure that label after call is following delay slot instruction.900// Ex. CALL_INSTRUCTION {901// DELAY_SLOT_INSTRUCTION }902// LABEL_AFTER_CALL903assert(getLabelAfterInsn(&*CallInstrBundle) ==904getLabelAfterInsn(&*DelaySlotBundle) &&905"Call and its successor instruction don't have same label after.");906return true;907};908909// Emit call site entries for each call or tail call in the function.910for (const MachineBasicBlock &MBB : MF) {911for (const MachineInstr &MI : MBB.instrs()) {912// Bundles with call in them will pass the isCall() test below but do not913// have callee operand information so skip them here. Iterator will914// eventually reach the call MI.915if (MI.isBundle())916continue;917918// Skip instructions which aren't calls. Both calls and tail-calling jump919// instructions (e.g TAILJMPd64) are classified correctly here.920if (!MI.isCandidateForCallSiteEntry())921continue;922923// Skip instructions marked as frame setup, as they are not interesting to924// the user.925if (MI.getFlag(MachineInstr::FrameSetup))926continue;927928// Check if delay slot support is enabled.929if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))930return;931932// If this is a direct call, find the callee's subprogram.933// In the case of an indirect call find the register that holds934// the callee.935const MachineOperand &CalleeOp = TII->getCalleeOperand(MI);936if (!CalleeOp.isGlobal() &&937(!CalleeOp.isReg() || !CalleeOp.getReg().isPhysical()))938continue;939940unsigned CallReg = 0;941const DISubprogram *CalleeSP = nullptr;942const Function *CalleeDecl = nullptr;943if (CalleeOp.isReg()) {944CallReg = CalleeOp.getReg();945if (!CallReg)946continue;947} else {948CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());949if (!CalleeDecl || !CalleeDecl->getSubprogram())950continue;951CalleeSP = CalleeDecl->getSubprogram();952}953954// TODO: Omit call site entries for runtime calls (objc_msgSend, etc).955956bool IsTail = TII->isTailCall(MI);957958// If MI is in a bundle, the label was created after the bundle since959// EmitFunctionBody iterates over top-level MIs. Get that top-level MI960// to search for that label below.961const MachineInstr *TopLevelCallMI =962MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;963964// For non-tail calls, the return PC is needed to disambiguate paths in965// the call graph which could lead to some target function. For tail966// calls, no return PC information is needed, unless tuning for GDB in967// DWARF4 mode in which case we fake a return PC for compatibility.968const MCSymbol *PCAddr =969(!IsTail || CU.useGNUAnalogForDwarf5Feature())970? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))971: nullptr;972973// For tail calls, it's necessary to record the address of the branch974// instruction so that the debugger can show where the tail call occurred.975const MCSymbol *CallAddr =976IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr;977978assert((IsTail || PCAddr) && "Non-tail call without return PC");979980LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "981<< (CalleeDecl ? CalleeDecl->getName()982: StringRef(MF.getSubtarget()983.getRegisterInfo()984->getName(CallReg)))985<< (IsTail ? " [IsTail]" : "") << "\n");986987DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(988ScopeDIE, CalleeSP, IsTail, PCAddr, CallAddr, CallReg);989990// Optionally emit call-site-param debug info.991if (emitDebugEntryValues()) {992ParamSet Params;993// Try to interpret values of call site parameters.994collectCallSiteParameters(&MI, Params);995CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);996}997}998}999}10001001void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {1002if (!U.hasDwarfPubSections())1003return;10041005U.addFlag(D, dwarf::DW_AT_GNU_pubnames);1006}10071008void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,1009DwarfCompileUnit &NewCU) {1010DIE &Die = NewCU.getUnitDie();1011StringRef FN = DIUnit->getFilename();10121013StringRef Producer = DIUnit->getProducer();1014StringRef Flags = DIUnit->getFlags();1015if (!Flags.empty() && !useAppleExtensionAttributes()) {1016std::string ProducerWithFlags = Producer.str() + " " + Flags.str();1017NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);1018} else1019NewCU.addString(Die, dwarf::DW_AT_producer, Producer);10201021NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,1022DIUnit->getSourceLanguage());1023NewCU.addString(Die, dwarf::DW_AT_name, FN);1024StringRef SysRoot = DIUnit->getSysRoot();1025if (!SysRoot.empty())1026NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);1027StringRef SDK = DIUnit->getSDK();1028if (!SDK.empty())1029NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);10301031if (!useSplitDwarf()) {1032// Add DW_str_offsets_base to the unit DIE, except for split units.1033if (useSegmentedStringOffsetsTable())1034NewCU.addStringOffsetsStart();10351036NewCU.initStmtList();10371038// If we're using split dwarf the compilation dir is going to be in the1039// skeleton CU and so we don't need to duplicate it here.1040if (!CompilationDir.empty())1041NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);1042addGnuPubAttributes(NewCU, Die);1043}10441045if (useAppleExtensionAttributes()) {1046if (DIUnit->isOptimized())1047NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);10481049StringRef Flags = DIUnit->getFlags();1050if (!Flags.empty())1051NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);10521053if (unsigned RVer = DIUnit->getRuntimeVersion())1054NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,1055dwarf::DW_FORM_data1, RVer);1056}10571058if (DIUnit->getDWOId()) {1059// This CU is either a clang module DWO or a skeleton CU.1060NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,1061DIUnit->getDWOId());1062if (!DIUnit->getSplitDebugFilename().empty()) {1063// This is a prefabricated skeleton CU.1064dwarf::Attribute attrDWOName = getDwarfVersion() >= 51065? dwarf::DW_AT_dwo_name1066: dwarf::DW_AT_GNU_dwo_name;1067NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());1068}1069}1070}1071// Create new DwarfCompileUnit for the given metadata node with tag1072// DW_TAG_compile_unit.1073DwarfCompileUnit &1074DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {1075if (auto *CU = CUMap.lookup(DIUnit))1076return *CU;10771078if (useSplitDwarf() &&1079!shareAcrossDWOCUs() &&1080(!DIUnit->getSplitDebugInlining() ||1081DIUnit->getEmissionKind() == DICompileUnit::FullDebug) &&1082!CUMap.empty()) {1083return *CUMap.begin()->second;1084}1085CompilationDir = DIUnit->getDirectory();10861087auto OwnedUnit = std::make_unique<DwarfCompileUnit>(1088InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);1089DwarfCompileUnit &NewCU = *OwnedUnit;1090InfoHolder.addUnit(std::move(OwnedUnit));10911092// LTO with assembly output shares a single line table amongst multiple CUs.1093// To avoid the compilation directory being ambiguous, let the line table1094// explicitly describe the directory of all files, never relying on the1095// compilation directory.1096if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)1097Asm->OutStreamer->emitDwarfFile0Directive(1098CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()),1099DIUnit->getSource(), NewCU.getUniqueID());11001101if (useSplitDwarf()) {1102NewCU.setSkeleton(constructSkeletonCU(NewCU));1103NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());1104} else {1105finishUnitAttributes(DIUnit, NewCU);1106NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());1107}11081109CUMap.insert({DIUnit, &NewCU});1110CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});1111return NewCU;1112}11131114/// Sort and unique GVEs by comparing their fragment offset.1115static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &1116sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {1117llvm::sort(1118GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {1119// Sort order: first null exprs, then exprs without fragment1120// info, then sort by fragment offset in bits.1121// FIXME: Come up with a more comprehensive comparator so1122// the sorting isn't non-deterministic, and so the following1123// std::unique call works correctly.1124if (!A.Expr || !B.Expr)1125return !!B.Expr;1126auto FragmentA = A.Expr->getFragmentInfo();1127auto FragmentB = B.Expr->getFragmentInfo();1128if (!FragmentA || !FragmentB)1129return !!FragmentB;1130return FragmentA->OffsetInBits < FragmentB->OffsetInBits;1131});1132GVEs.erase(llvm::unique(GVEs,1133[](DwarfCompileUnit::GlobalExpr A,1134DwarfCompileUnit::GlobalExpr B) {1135return A.Expr == B.Expr;1136}),1137GVEs.end());1138return GVEs;1139}11401141// Emit all Dwarf sections that should come prior to the content. Create1142// global DIEs and emit initial debug info sections. This is invoked by1143// the target AsmPrinter.1144void DwarfDebug::beginModule(Module *M) {1145DebugHandlerBase::beginModule(M);11461147if (!Asm || !MMI->hasDebugInfo())1148return;11491150unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),1151M->debug_compile_units_end());1152assert(NumDebugCUs > 0 && "Asm unexpectedly initialized");1153assert(MMI->hasDebugInfo() &&1154"DebugInfoAvailabilty unexpectedly not initialized");1155SingleCU = NumDebugCUs == 1;1156DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>1157GVMap;1158for (const GlobalVariable &Global : M->globals()) {1159SmallVector<DIGlobalVariableExpression *, 1> GVs;1160Global.getDebugInfo(GVs);1161for (auto *GVE : GVs)1162GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});1163}11641165// Create the symbol that designates the start of the unit's contribution1166// to the string offsets table. In a split DWARF scenario, only the skeleton1167// unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).1168if (useSegmentedStringOffsetsTable())1169(useSplitDwarf() ? SkeletonHolder : InfoHolder)1170.setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));117111721173// Create the symbols that designates the start of the DWARF v5 range list1174// and locations list tables. They are located past the table headers.1175if (getDwarfVersion() >= 5) {1176DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;1177Holder.setRnglistsTableBaseSym(1178Asm->createTempSymbol("rnglists_table_base"));11791180if (useSplitDwarf())1181InfoHolder.setRnglistsTableBaseSym(1182Asm->createTempSymbol("rnglists_dwo_table_base"));1183}11841185// Create the symbol that points to the first entry following the debug1186// address table (.debug_addr) header.1187AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));1188DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));11891190for (DICompileUnit *CUNode : M->debug_compile_units()) {1191if (CUNode->getImportedEntities().empty() &&1192CUNode->getEnumTypes().empty() && CUNode->getRetainedTypes().empty() &&1193CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())1194continue;11951196DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);11971198// Global Variables.1199for (auto *GVE : CUNode->getGlobalVariables()) {1200// Don't bother adding DIGlobalVariableExpressions listed in the CU if we1201// already know about the variable and it isn't adding a constant1202// expression.1203auto &GVMapEntry = GVMap[GVE->getVariable()];1204auto *Expr = GVE->getExpression();1205if (!GVMapEntry.size() || (Expr && Expr->isConstant()))1206GVMapEntry.push_back({nullptr, Expr});1207}12081209DenseSet<DIGlobalVariable *> Processed;1210for (auto *GVE : CUNode->getGlobalVariables()) {1211DIGlobalVariable *GV = GVE->getVariable();1212if (Processed.insert(GV).second)1213CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));1214}12151216for (auto *Ty : CUNode->getEnumTypes())1217CU.getOrCreateTypeDIE(cast<DIType>(Ty));12181219for (auto *Ty : CUNode->getRetainedTypes()) {1220// The retained types array by design contains pointers to1221// MDNodes rather than DIRefs. Unique them here.1222if (DIType *RT = dyn_cast<DIType>(Ty))1223// There is no point in force-emitting a forward declaration.1224CU.getOrCreateTypeDIE(RT);1225}1226}1227}12281229void DwarfDebug::finishEntityDefinitions() {1230for (const auto &Entity : ConcreteEntities) {1231DIE *Die = Entity->getDIE();1232assert(Die);1233// FIXME: Consider the time-space tradeoff of just storing the unit pointer1234// in the ConcreteEntities list, rather than looking it up again here.1235// DIE::getUnit isn't simple - it walks parent pointers, etc.1236DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());1237assert(Unit);1238Unit->finishEntityDefinition(Entity.get());1239}1240}12411242void DwarfDebug::finishSubprogramDefinitions() {1243for (const DISubprogram *SP : ProcessedSPNodes) {1244assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);1245forBothCUs(1246getOrCreateDwarfCompileUnit(SP->getUnit()),1247[&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });1248}1249}12501251void DwarfDebug::finalizeModuleInfo() {1252const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();12531254finishSubprogramDefinitions();12551256finishEntityDefinitions();12571258// Include the DWO file name in the hash if there's more than one CU.1259// This handles ThinLTO's situation where imported CUs may very easily be1260// duplicate with the same CU partially imported into another ThinLTO unit.1261StringRef DWOName;1262if (CUMap.size() > 1)1263DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;12641265bool HasEmittedSplitCU = false;12661267// Handle anything that needs to be done on a per-unit basis after1268// all other generation.1269for (const auto &P : CUMap) {1270auto &TheCU = *P.second;1271if (TheCU.getCUNode()->isDebugDirectivesOnly())1272continue;1273// Emit DW_AT_containing_type attribute to connect types with their1274// vtable holding type.1275TheCU.constructContainingTypeDIEs();12761277// Add CU specific attributes if we need to add any.1278// If we're splitting the dwarf out now that we've got the entire1279// CU then add the dwo id to it.1280auto *SkCU = TheCU.getSkeleton();12811282bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();12831284if (HasSplitUnit) {1285(void)HasEmittedSplitCU;1286assert((shareAcrossDWOCUs() || !HasEmittedSplitCU) &&1287"Multiple CUs emitted into a single dwo file");1288HasEmittedSplitCU = true;1289dwarf::Attribute attrDWOName = getDwarfVersion() >= 51290? dwarf::DW_AT_dwo_name1291: dwarf::DW_AT_GNU_dwo_name;1292finishUnitAttributes(TheCU.getCUNode(), TheCU);1293TheCU.addString(TheCU.getUnitDie(), attrDWOName,1294Asm->TM.Options.MCOptions.SplitDwarfFile);1295SkCU->addString(SkCU->getUnitDie(), attrDWOName,1296Asm->TM.Options.MCOptions.SplitDwarfFile);1297// Emit a unique identifier for this CU.1298uint64_t ID =1299DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());1300if (getDwarfVersion() >= 5) {1301TheCU.setDWOId(ID);1302SkCU->setDWOId(ID);1303} else {1304TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,1305dwarf::DW_FORM_data8, ID);1306SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,1307dwarf::DW_FORM_data8, ID);1308}13091310if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {1311const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();1312SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,1313Sym, Sym);1314}1315} else if (SkCU) {1316finishUnitAttributes(SkCU->getCUNode(), *SkCU);1317}13181319// If we have code split among multiple sections or non-contiguous1320// ranges of code then emit a DW_AT_ranges attribute on the unit that will1321// remain in the .o file, otherwise add a DW_AT_low_pc.1322// FIXME: We should use ranges allow reordering of code ala1323// .subsections_via_symbols in mach-o. This would mean turning on1324// ranges for all subprogram DIEs for mach-o.1325DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;13261327if (unsigned NumRanges = TheCU.getRanges().size()) {1328if (NumRanges > 1 && useRangesSection())1329// A DW_AT_low_pc attribute may also be specified in combination with1330// DW_AT_ranges to specify the default base address for use in1331// location lists (see Section 2.6.2) and range lists (see Section1332// 2.17.3).1333U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);1334else1335U.setBaseAddress(TheCU.getRanges().front().Begin);1336U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());1337}13381339// We don't keep track of which addresses are used in which CU so this1340// is a bit pessimistic under LTO.1341if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())1342U.addAddrTableBase();13431344if (getDwarfVersion() >= 5) {1345if (U.hasRangeLists())1346U.addRnglistsBase();13471348if (!DebugLocs.getLists().empty() && !useSplitDwarf()) {1349U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,1350DebugLocs.getSym(),1351TLOF.getDwarfLoclistsSection()->getBeginSymbol());1352}1353}13541355auto *CUNode = cast<DICompileUnit>(P.first);1356// If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"1357// attribute.1358if (CUNode->getMacros()) {1359if (UseDebugMacroSection) {1360if (useSplitDwarf())1361TheCU.addSectionDelta(1362TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),1363TLOF.getDwarfMacroDWOSection()->getBeginSymbol());1364else {1365dwarf::Attribute MacrosAttr = getDwarfVersion() >= 51366? dwarf::DW_AT_macros1367: dwarf::DW_AT_GNU_macros;1368U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),1369TLOF.getDwarfMacroSection()->getBeginSymbol());1370}1371} else {1372if (useSplitDwarf())1373TheCU.addSectionDelta(1374TheCU.getUnitDie(), dwarf::DW_AT_macro_info,1375U.getMacroLabelBegin(),1376TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());1377else1378U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,1379U.getMacroLabelBegin(),1380TLOF.getDwarfMacinfoSection()->getBeginSymbol());1381}1382}1383}13841385// Emit all frontend-produced Skeleton CUs, i.e., Clang modules.1386for (auto *CUNode : MMI->getModule()->debug_compile_units())1387if (CUNode->getDWOId())1388getOrCreateDwarfCompileUnit(CUNode);13891390// Compute DIE offsets and sizes.1391InfoHolder.computeSizeAndOffsets();1392if (useSplitDwarf())1393SkeletonHolder.computeSizeAndOffsets();13941395// Now that offsets are computed, can replace DIEs in debug_names Entry with1396// an actual offset.1397AccelDebugNames.convertDieToOffset();1398}13991400// Emit all Dwarf sections that should come after the content.1401void DwarfDebug::endModule() {1402// Terminate the pending line table.1403if (PrevCU)1404terminateLineTable(PrevCU);1405PrevCU = nullptr;1406assert(CurFn == nullptr);1407assert(CurMI == nullptr);14081409for (const auto &P : CUMap) {1410const auto *CUNode = cast<DICompileUnit>(P.first);1411DwarfCompileUnit *CU = &*P.second;14121413// Emit imported entities.1414for (auto *IE : CUNode->getImportedEntities()) {1415assert(!isa_and_nonnull<DILocalScope>(IE->getScope()) &&1416"Unexpected function-local entity in 'imports' CU field.");1417CU->getOrCreateImportedEntityDIE(IE);1418}1419for (const auto *D : CU->getDeferredLocalDecls()) {1420if (auto *IE = dyn_cast<DIImportedEntity>(D))1421CU->getOrCreateImportedEntityDIE(IE);1422else1423llvm_unreachable("Unexpected local retained node!");1424}14251426// Emit base types.1427CU->createBaseTypeDIEs();1428}14291430// If we aren't actually generating debug info (check beginModule -1431// conditionalized on the presence of the llvm.dbg.cu metadata node)1432if (!Asm || !MMI->hasDebugInfo())1433return;14341435// Finalize the debug info for the module.1436finalizeModuleInfo();14371438if (useSplitDwarf())1439// Emit debug_loc.dwo/debug_loclists.dwo section.1440emitDebugLocDWO();1441else1442// Emit debug_loc/debug_loclists section.1443emitDebugLoc();14441445// Corresponding abbreviations into a abbrev section.1446emitAbbreviations();14471448// Emit all the DIEs into a debug info section.1449emitDebugInfo();14501451// Emit info into a debug aranges section.1452if (GenerateARangeSection)1453emitDebugARanges();14541455// Emit info into a debug ranges section.1456emitDebugRanges();14571458if (useSplitDwarf())1459// Emit info into a debug macinfo.dwo section.1460emitDebugMacinfoDWO();1461else1462// Emit info into a debug macinfo/macro section.1463emitDebugMacinfo();14641465emitDebugStr();14661467if (useSplitDwarf()) {1468emitDebugStrDWO();1469emitDebugInfoDWO();1470emitDebugAbbrevDWO();1471emitDebugLineDWO();1472emitDebugRangesDWO();1473}14741475emitDebugAddr();14761477// Emit info into the dwarf accelerator table sections.1478switch (getAccelTableKind()) {1479case AccelTableKind::Apple:1480emitAccelNames();1481emitAccelObjC();1482emitAccelNamespaces();1483emitAccelTypes();1484break;1485case AccelTableKind::Dwarf:1486emitAccelDebugNames();1487break;1488case AccelTableKind::None:1489break;1490case AccelTableKind::Default:1491llvm_unreachable("Default should have already been resolved.");1492}14931494// Emit the pubnames and pubtypes sections if requested.1495emitDebugPubSections();14961497// clean up.1498// FIXME: AbstractVariables.clear();1499}15001501void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,1502const DINode *Node, const MDNode *ScopeNode) {1503if (CU.getExistingAbstractEntity(Node))1504return;15051506if (LexicalScope *Scope =1507LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))1508CU.createAbstractEntity(Node, Scope);1509}15101511static const DILocalScope *getRetainedNodeScope(const MDNode *N) {1512const DIScope *S;1513if (const auto *LV = dyn_cast<DILocalVariable>(N))1514S = LV->getScope();1515else if (const auto *L = dyn_cast<DILabel>(N))1516S = L->getScope();1517else if (const auto *IE = dyn_cast<DIImportedEntity>(N))1518S = IE->getScope();1519else1520llvm_unreachable("Unexpected retained node!");15211522// Ensure the scope is not a DILexicalBlockFile.1523return cast<DILocalScope>(S)->getNonLexicalBlockFileScope();1524}15251526// Collect variable information from side table maintained by MF.1527void DwarfDebug::collectVariableInfoFromMFTable(1528DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {1529SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;1530LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");1531for (const auto &VI : Asm->MF->getVariableDbgInfo()) {1532if (!VI.Var)1533continue;1534assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&1535"Expected inlined-at fields to agree");15361537InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());1538Processed.insert(Var);1539LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);15401541// If variable scope is not found then skip this variable.1542if (!Scope) {1543LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()1544<< ", no variable scope found\n");1545continue;1546}15471548ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());15491550// If we have already seen information for this variable, add to what we1551// already know.1552if (DbgVariable *PreviousLoc = MFVars.lookup(Var)) {1553auto *PreviousMMI = std::get_if<Loc::MMI>(PreviousLoc);1554auto *PreviousEntryValue = std::get_if<Loc::EntryValue>(PreviousLoc);1555// Previous and new locations are both stack slots (MMI).1556if (PreviousMMI && VI.inStackSlot())1557PreviousMMI->addFrameIndexExpr(VI.Expr, VI.getStackSlot());1558// Previous and new locations are both entry values.1559else if (PreviousEntryValue && VI.inEntryValueRegister())1560PreviousEntryValue->addExpr(VI.getEntryValueRegister(), *VI.Expr);1561else {1562// Locations differ, this should (rarely) happen in optimized async1563// coroutines.1564// Prefer whichever location has an EntryValue.1565if (PreviousLoc->holds<Loc::MMI>())1566PreviousLoc->emplace<Loc::EntryValue>(VI.getEntryValueRegister(),1567*VI.Expr);1568LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()1569<< ", conflicting fragment location types\n");1570}1571continue;1572}15731574auto RegVar = std::make_unique<DbgVariable>(1575cast<DILocalVariable>(Var.first), Var.second);1576if (VI.inStackSlot())1577RegVar->emplace<Loc::MMI>(VI.Expr, VI.getStackSlot());1578else1579RegVar->emplace<Loc::EntryValue>(VI.getEntryValueRegister(), *VI.Expr);1580LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()1581<< "\n");1582InfoHolder.addScopeVariable(Scope, RegVar.get());1583MFVars.insert({Var, RegVar.get()});1584ConcreteEntities.push_back(std::move(RegVar));1585}1586}15871588/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its1589/// enclosing lexical scope. The check ensures there are no other instructions1590/// in the same lexical scope preceding the DBG_VALUE and that its range is1591/// either open or otherwise rolls off the end of the scope.1592static bool validThroughout(LexicalScopes &LScopes,1593const MachineInstr *DbgValue,1594const MachineInstr *RangeEnd,1595const InstructionOrdering &Ordering) {1596assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");1597auto MBB = DbgValue->getParent();1598auto DL = DbgValue->getDebugLoc();1599auto *LScope = LScopes.findLexicalScope(DL);1600// Scope doesn't exist; this is a dead DBG_VALUE.1601if (!LScope)1602return false;1603auto &LSRange = LScope->getRanges();1604if (LSRange.size() == 0)1605return false;16061607const MachineInstr *LScopeBegin = LSRange.front().first;1608// If the scope starts before the DBG_VALUE then we may have a negative1609// result. Otherwise the location is live coming into the scope and we1610// can skip the following checks.1611if (!Ordering.isBefore(DbgValue, LScopeBegin)) {1612// Exit if the lexical scope begins outside of the current block.1613if (LScopeBegin->getParent() != MBB)1614return false;16151616MachineBasicBlock::const_reverse_iterator Pred(DbgValue);1617for (++Pred; Pred != MBB->rend(); ++Pred) {1618if (Pred->getFlag(MachineInstr::FrameSetup))1619break;1620auto PredDL = Pred->getDebugLoc();1621if (!PredDL || Pred->isMetaInstruction())1622continue;1623// Check whether the instruction preceding the DBG_VALUE is in the same1624// (sub)scope as the DBG_VALUE.1625if (DL->getScope() == PredDL->getScope())1626return false;1627auto *PredScope = LScopes.findLexicalScope(PredDL);1628if (!PredScope || LScope->dominates(PredScope))1629return false;1630}1631}16321633// If the range of the DBG_VALUE is open-ended, report success.1634if (!RangeEnd)1635return true;16361637// Single, constant DBG_VALUEs in the prologue are promoted to be live1638// throughout the function. This is a hack, presumably for DWARF v2 and not1639// necessarily correct. It would be much better to use a dbg.declare instead1640// if we know the constant is live throughout the scope.1641if (MBB->pred_empty() &&1642all_of(DbgValue->debug_operands(),1643[](const MachineOperand &Op) { return Op.isImm(); }))1644return true;16451646// Test if the location terminates before the end of the scope.1647const MachineInstr *LScopeEnd = LSRange.back().second;1648if (Ordering.isBefore(RangeEnd, LScopeEnd))1649return false;16501651// There's a single location which starts at the scope start, and ends at or1652// after the scope end.1653return true;1654}16551656/// Build the location list for all DBG_VALUEs in the function that1657/// describe the same variable. The resulting DebugLocEntries will have1658/// strict monotonically increasing begin addresses and will never1659/// overlap. If the resulting list has only one entry that is valid1660/// throughout variable's scope return true.1661//1662// See the definition of DbgValueHistoryMap::Entry for an explanation of the1663// different kinds of history map entries. One thing to be aware of is that if1664// a debug value is ended by another entry (rather than being valid until the1665// end of the function), that entry's instruction may or may not be included in1666// the range, depending on if the entry is a clobbering entry (it has an1667// instruction that clobbers one or more preceding locations), or if it is an1668// (overlapping) debug value entry. This distinction can be seen in the example1669// below. The first debug value is ended by the clobbering entry 2, and the1670// second and third debug values are ended by the overlapping debug value entry1671// 4.1672//1673// Input:1674//1675// History map entries [type, end index, mi]1676//1677// 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]1678// 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]1679// 2 | | [Clobber, $reg0 = [...], -, -]1680// 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]1681// 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]1682//1683// Output [start, end) [Value...]:1684//1685// [0-1) [(reg0, fragment 0, 32)]1686// [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]1687// [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]1688// [4-) [(@g, fragment 0, 96)]1689bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,1690const DbgValueHistoryMap::Entries &Entries) {1691using OpenRange =1692std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;1693SmallVector<OpenRange, 4> OpenRanges;1694bool isSafeForSingleLocation = true;1695const MachineInstr *StartDebugMI = nullptr;1696const MachineInstr *EndMI = nullptr;16971698for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {1699const MachineInstr *Instr = EI->getInstr();17001701// Remove all values that are no longer live.1702size_t Index = std::distance(EB, EI);1703erase_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });17041705// If we are dealing with a clobbering entry, this iteration will result in1706// a location list entry starting after the clobbering instruction.1707const MCSymbol *StartLabel =1708EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);1709assert(StartLabel &&1710"Forgot label before/after instruction starting a range!");17111712const MCSymbol *EndLabel;1713if (std::next(EI) == Entries.end()) {1714const MachineBasicBlock &EndMBB = Asm->MF->back();1715EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionID()].EndLabel;1716if (EI->isClobber())1717EndMI = EI->getInstr();1718}1719else if (std::next(EI)->isClobber())1720EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());1721else1722EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());1723assert(EndLabel && "Forgot label after instruction ending a range!");17241725if (EI->isDbgValue())1726LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");17271728// If this history map entry has a debug value, add that to the list of1729// open ranges and check if its location is valid for a single value1730// location.1731if (EI->isDbgValue()) {1732// Do not add undef debug values, as they are redundant information in1733// the location list entries. An undef debug results in an empty location1734// description. If there are any non-undef fragments then padding pieces1735// with empty location descriptions will automatically be inserted, and if1736// all fragments are undef then the whole location list entry is1737// redundant.1738if (!Instr->isUndefDebugValue()) {1739auto Value = getDebugLocValue(Instr);1740OpenRanges.emplace_back(EI->getEndIndex(), Value);17411742// TODO: Add support for single value fragment locations.1743if (Instr->getDebugExpression()->isFragment())1744isSafeForSingleLocation = false;17451746if (!StartDebugMI)1747StartDebugMI = Instr;1748} else {1749isSafeForSingleLocation = false;1750}1751}17521753// Location list entries with empty location descriptions are redundant1754// information in DWARF, so do not emit those.1755if (OpenRanges.empty())1756continue;17571758// Omit entries with empty ranges as they do not have any effect in DWARF.1759if (StartLabel == EndLabel) {1760LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");1761continue;1762}17631764SmallVector<DbgValueLoc, 4> Values;1765for (auto &R : OpenRanges)1766Values.push_back(R.second);17671768// With Basic block sections, it is posssible that the StartLabel and the1769// Instr are not in the same section. This happens when the StartLabel is1770// the function begin label and the dbg value appears in a basic block1771// that is not the entry. In this case, the range needs to be split to1772// span each individual section in the range from StartLabel to EndLabel.1773if (Asm->MF->hasBBSections() && StartLabel == Asm->getFunctionBegin() &&1774!Instr->getParent()->sameSection(&Asm->MF->front())) {1775const MCSymbol *BeginSectionLabel = StartLabel;17761777for (const MachineBasicBlock &MBB : *Asm->MF) {1778if (MBB.isBeginSection() && &MBB != &Asm->MF->front())1779BeginSectionLabel = MBB.getSymbol();17801781if (MBB.sameSection(Instr->getParent())) {1782DebugLoc.emplace_back(BeginSectionLabel, EndLabel, Values);1783break;1784}1785if (MBB.isEndSection())1786DebugLoc.emplace_back(BeginSectionLabel, MBB.getEndSymbol(), Values);1787}1788} else {1789DebugLoc.emplace_back(StartLabel, EndLabel, Values);1790}17911792// Attempt to coalesce the ranges of two otherwise identical1793// DebugLocEntries.1794auto CurEntry = DebugLoc.rbegin();1795LLVM_DEBUG({1796dbgs() << CurEntry->getValues().size() << " Values:\n";1797for (auto &Value : CurEntry->getValues())1798Value.dump();1799dbgs() << "-----\n";1800});18011802auto PrevEntry = std::next(CurEntry);1803if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))1804DebugLoc.pop_back();1805}18061807if (!isSafeForSingleLocation ||1808!validThroughout(LScopes, StartDebugMI, EndMI, getInstOrdering()))1809return false;18101811if (DebugLoc.size() == 1)1812return true;18131814if (!Asm->MF->hasBBSections())1815return false;18161817// Check here to see if loclist can be merged into a single range. If not,1818// we must keep the split loclists per section. This does exactly what1819// MergeRanges does without sections. We don't actually merge the ranges1820// as the split ranges must be kept intact if this cannot be collapsed1821// into a single range.1822const MachineBasicBlock *RangeMBB = nullptr;1823if (DebugLoc[0].getBeginSym() == Asm->getFunctionBegin())1824RangeMBB = &Asm->MF->front();1825else1826RangeMBB = Entries.begin()->getInstr()->getParent();1827auto *CurEntry = DebugLoc.begin();1828auto *NextEntry = std::next(CurEntry);1829while (NextEntry != DebugLoc.end()) {1830// Get the last machine basic block of this section.1831while (!RangeMBB->isEndSection())1832RangeMBB = RangeMBB->getNextNode();1833if (!RangeMBB->getNextNode())1834return false;1835// CurEntry should end the current section and NextEntry should start1836// the next section and the Values must match for these two ranges to be1837// merged.1838if (CurEntry->getEndSym() != RangeMBB->getEndSymbol() ||1839NextEntry->getBeginSym() != RangeMBB->getNextNode()->getSymbol() ||1840CurEntry->getValues() != NextEntry->getValues())1841return false;1842RangeMBB = RangeMBB->getNextNode();1843CurEntry = NextEntry;1844NextEntry = std::next(CurEntry);1845}1846return true;1847}18481849DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,1850LexicalScope &Scope,1851const DINode *Node,1852const DILocation *Location,1853const MCSymbol *Sym) {1854ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());1855if (isa<const DILocalVariable>(Node)) {1856ConcreteEntities.push_back(1857std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),1858Location));1859InfoHolder.addScopeVariable(&Scope,1860cast<DbgVariable>(ConcreteEntities.back().get()));1861} else if (isa<const DILabel>(Node)) {1862ConcreteEntities.push_back(1863std::make_unique<DbgLabel>(cast<const DILabel>(Node),1864Location, Sym));1865InfoHolder.addScopeLabel(&Scope,1866cast<DbgLabel>(ConcreteEntities.back().get()));1867}1868return ConcreteEntities.back().get();1869}18701871// Find variables for each lexical scope.1872void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,1873const DISubprogram *SP,1874DenseSet<InlinedEntity> &Processed) {1875// Grab the variable info that was squirreled away in the MMI side-table.1876collectVariableInfoFromMFTable(TheCU, Processed);18771878for (const auto &I : DbgValues) {1879InlinedEntity IV = I.first;1880if (Processed.count(IV))1881continue;18821883// Instruction ranges, specifying where IV is accessible.1884const auto &HistoryMapEntries = I.second;18851886// Try to find any non-empty variable location. Do not create a concrete1887// entity if there are no locations.1888if (!DbgValues.hasNonEmptyLocation(HistoryMapEntries))1889continue;18901891LexicalScope *Scope = nullptr;1892const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);1893if (const DILocation *IA = IV.second)1894Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);1895else1896Scope = LScopes.findLexicalScope(LocalVar->getScope());1897// If variable scope is not found then skip this variable.1898if (!Scope)1899continue;19001901Processed.insert(IV);1902DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,1903*Scope, LocalVar, IV.second));19041905const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();1906assert(MInsn->isDebugValue() && "History must begin with debug value");19071908// Check if there is a single DBG_VALUE, valid throughout the var's scope.1909// If the history map contains a single debug value, there may be an1910// additional entry which clobbers the debug value.1911size_t HistSize = HistoryMapEntries.size();1912bool SingleValueWithClobber =1913HistSize == 2 && HistoryMapEntries[1].isClobber();1914if (HistSize == 1 || SingleValueWithClobber) {1915const auto *End =1916SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;1917if (validThroughout(LScopes, MInsn, End, getInstOrdering())) {1918RegVar->emplace<Loc::Single>(MInsn);1919continue;1920}1921}19221923// Do not emit location lists if .debug_loc secton is disabled.1924if (!useLocSection())1925continue;19261927// Handle multiple DBG_VALUE instructions describing one variable.1928DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar);19291930// Build the location list for this variable.1931SmallVector<DebugLocEntry, 8> Entries;1932bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);19331934// Check whether buildLocationList managed to merge all locations to one1935// that is valid throughout the variable's scope. If so, produce single1936// value location.1937if (isValidSingleLocation) {1938RegVar->emplace<Loc::Single>(Entries[0].getValues()[0]);1939continue;1940}19411942// If the variable has a DIBasicType, extract it. Basic types cannot have1943// unique identifiers, so don't bother resolving the type with the1944// identifier map.1945const DIBasicType *BT = dyn_cast<DIBasicType>(1946static_cast<const Metadata *>(LocalVar->getType()));19471948// Finalize the entry by lowering it into a DWARF bytestream.1949for (auto &Entry : Entries)1950Entry.finalize(*Asm, List, BT, TheCU);1951}19521953// For each InlinedEntity collected from DBG_LABEL instructions, convert to1954// DWARF-related DbgLabel.1955for (const auto &I : DbgLabels) {1956InlinedEntity IL = I.first;1957const MachineInstr *MI = I.second;1958if (MI == nullptr)1959continue;19601961LexicalScope *Scope = nullptr;1962const DILabel *Label = cast<DILabel>(IL.first);1963// The scope could have an extra lexical block file.1964const DILocalScope *LocalScope =1965Label->getScope()->getNonLexicalBlockFileScope();1966// Get inlined DILocation if it is inlined label.1967if (const DILocation *IA = IL.second)1968Scope = LScopes.findInlinedScope(LocalScope, IA);1969else1970Scope = LScopes.findLexicalScope(LocalScope);1971// If label scope is not found then skip this label.1972if (!Scope)1973continue;19741975Processed.insert(IL);1976/// At this point, the temporary label is created.1977/// Save the temporary label to DbgLabel entity to get the1978/// actually address when generating Dwarf DIE.1979MCSymbol *Sym = getLabelBeforeInsn(MI);1980createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);1981}19821983// Collect info for retained nodes.1984for (const DINode *DN : SP->getRetainedNodes()) {1985const auto *LS = getRetainedNodeScope(DN);1986if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {1987if (!Processed.insert(InlinedEntity(DN, nullptr)).second)1988continue;1989LexicalScope *LexS = LScopes.findLexicalScope(LS);1990if (LexS)1991createConcreteEntity(TheCU, *LexS, DN, nullptr);1992} else {1993LocalDeclsPerLS[LS].insert(DN);1994}1995}1996}19971998// Process beginning of an instruction.1999void DwarfDebug::beginInstruction(const MachineInstr *MI) {2000const MachineFunction &MF = *MI->getMF();2001const auto *SP = MF.getFunction().getSubprogram();2002bool NoDebug =2003!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;20042005// Delay slot support check.2006auto delaySlotSupported = [](const MachineInstr &MI) {2007if (!MI.isBundledWithSucc())2008return false;2009auto Suc = std::next(MI.getIterator());2010(void)Suc;2011// Ensure that delay slot instruction is successor of the call instruction.2012// Ex. CALL_INSTRUCTION {2013// DELAY_SLOT_INSTRUCTION }2014assert(Suc->isBundledWithPred() &&2015"Call bundle instructions are out of order");2016return true;2017};20182019// When describing calls, we need a label for the call instruction.2020if (!NoDebug && SP->areAllCallsDescribed() &&2021MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) &&2022(!MI->hasDelaySlot() || delaySlotSupported(*MI))) {2023const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();2024bool IsTail = TII->isTailCall(*MI);2025// For tail calls, we need the address of the branch instruction for2026// DW_AT_call_pc.2027if (IsTail)2028requestLabelBeforeInsn(MI);2029// For non-tail calls, we need the return address for the call for2030// DW_AT_call_return_pc. Under GDB tuning, this information is needed for2031// tail calls as well.2032requestLabelAfterInsn(MI);2033}20342035DebugHandlerBase::beginInstruction(MI);2036if (!CurMI)2037return;20382039if (NoDebug)2040return;20412042// Check if source location changes, but ignore DBG_VALUE and CFI locations.2043// If the instruction is part of the function frame setup code, do not emit2044// any line record, as there is no correspondence with any user code.2045if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))2046return;2047const DebugLoc &DL = MI->getDebugLoc();2048unsigned Flags = 0;20492050if (MI->getFlag(MachineInstr::FrameDestroy) && DL) {2051const MachineBasicBlock *MBB = MI->getParent();2052if (MBB && (MBB != EpilogBeginBlock)) {2053// First time FrameDestroy has been seen in this basic block2054EpilogBeginBlock = MBB;2055Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;2056}2057}20582059// When we emit a line-0 record, we don't update PrevInstLoc; so look at2060// the last line number actually emitted, to see if it was line 0.2061unsigned LastAsmLine =2062Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();20632064bool PrevInstInSameSection =2065(!PrevInstBB ||2066PrevInstBB->getSectionID() == MI->getParent()->getSectionID());2067if (DL == PrevInstLoc && PrevInstInSameSection) {2068// If we have an ongoing unspecified location, nothing to do here.2069if (!DL)2070return;2071// We have an explicit location, same as the previous location.2072// But we might be coming back to it after a line 0 record.2073if ((LastAsmLine == 0 && DL.getLine() != 0) || Flags) {2074// Reinstate the source location but not marked as a statement.2075const MDNode *Scope = DL.getScope();2076recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);2077}2078return;2079}20802081if (!DL) {2082// We have an unspecified location, which might want to be line 0.2083// If we have already emitted a line-0 record, don't repeat it.2084if (LastAsmLine == 0)2085return;2086// If user said Don't Do That, don't do that.2087if (UnknownLocations == Disable)2088return;2089// See if we have a reason to emit a line-0 record now.2090// Reasons to emit a line-0 record include:2091// - User asked for it (UnknownLocations).2092// - Instruction has a label, so it's referenced from somewhere else,2093// possibly debug information; we want it to have a source location.2094// - Instruction is at the top of a block; we don't want to inherit the2095// location from the physically previous (maybe unrelated) block.2096if (UnknownLocations == Enable || PrevLabel ||2097(PrevInstBB && PrevInstBB != MI->getParent())) {2098// Preserve the file and column numbers, if we can, to save space in2099// the encoded line table.2100// Do not update PrevInstLoc, it remembers the last non-0 line.2101const MDNode *Scope = nullptr;2102unsigned Column = 0;2103if (PrevInstLoc) {2104Scope = PrevInstLoc.getScope();2105Column = PrevInstLoc.getCol();2106}2107recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);2108}2109return;2110}21112112// We have an explicit location, different from the previous location.2113// Don't repeat a line-0 record, but otherwise emit the new location.2114// (The new location might be an explicit line 0, which we do emit.)2115if (DL.getLine() == 0 && LastAsmLine == 0)2116return;2117if (DL == PrologEndLoc) {2118Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;2119PrologEndLoc = DebugLoc();2120}2121// If the line changed, we call that a new statement; unless we went to2122// line 0 and came back, in which case it is not a new statement.2123unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;2124if (DL.getLine() && DL.getLine() != OldLine)2125Flags |= DWARF2_FLAG_IS_STMT;21262127const MDNode *Scope = DL.getScope();2128recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);21292130// If we're not at line 0, remember this location.2131if (DL.getLine())2132PrevInstLoc = DL;2133}21342135static std::pair<DebugLoc, bool> findPrologueEndLoc(const MachineFunction *MF) {2136// First known non-DBG_VALUE and non-frame setup location marks2137// the beginning of the function body.2138DebugLoc LineZeroLoc;2139const Function &F = MF->getFunction();21402141// Some instructions may be inserted into prologue after this function. Must2142// keep prologue for these cases.2143bool IsEmptyPrologue =2144!(F.hasPrologueData() || F.getMetadata(LLVMContext::MD_func_sanitize));2145for (const auto &MBB : *MF) {2146for (const auto &MI : MBB) {2147if (!MI.isMetaInstruction()) {2148if (!MI.getFlag(MachineInstr::FrameSetup) && MI.getDebugLoc()) {2149// Scan forward to try to find a non-zero line number. The2150// prologue_end marks the first breakpoint in the function after the2151// frame setup, and a compiler-generated line 0 location is not a2152// meaningful breakpoint. If none is found, return the first2153// location after the frame setup.2154if (MI.getDebugLoc().getLine())2155return std::make_pair(MI.getDebugLoc(), IsEmptyPrologue);21562157LineZeroLoc = MI.getDebugLoc();2158}2159IsEmptyPrologue = false;2160}2161}2162}2163return std::make_pair(LineZeroLoc, IsEmptyPrologue);2164}21652166/// Register a source line with debug info. Returns the unique label that was2167/// emitted and which provides correspondence to the source line list.2168static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,2169const MDNode *S, unsigned Flags, unsigned CUID,2170uint16_t DwarfVersion,2171ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {2172StringRef Fn;2173unsigned FileNo = 1;2174unsigned Discriminator = 0;2175if (auto *Scope = cast_or_null<DIScope>(S)) {2176Fn = Scope->getFilename();2177if (Line != 0 && DwarfVersion >= 4)2178if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))2179Discriminator = LBF->getDiscriminator();21802181FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])2182.getOrCreateSourceID(Scope->getFile());2183}2184Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,2185Discriminator, Fn);2186}21872188DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,2189unsigned CUID) {2190std::pair<DebugLoc, bool> PrologEnd = findPrologueEndLoc(&MF);2191DebugLoc PrologEndLoc = PrologEnd.first;2192bool IsEmptyPrologue = PrologEnd.second;21932194// Get beginning of function.2195if (PrologEndLoc) {2196// If the prolog is empty, no need to generate scope line for the proc.2197if (IsEmptyPrologue)2198return PrologEndLoc;21992200// Ensure the compile unit is created if the function is called before2201// beginFunction().2202(void)getOrCreateDwarfCompileUnit(2203MF.getFunction().getSubprogram()->getUnit());2204// We'd like to list the prologue as "not statements" but GDB behaves2205// poorly if we do that. Revisit this with caution/GDB (7.5+) testing.2206const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();2207::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,2208CUID, getDwarfVersion(), getUnits());2209return PrologEndLoc;2210}2211return DebugLoc();2212}22132214// Gather pre-function debug information. Assumes being called immediately2215// after the function entry point has been emitted.2216void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {2217CurFn = MF;22182219auto *SP = MF->getFunction().getSubprogram();2220assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());2221if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)2222return;22232224DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());22252226Asm->OutStreamer->getContext().setDwarfCompileUnitID(2227getDwarfCompileUnitIDForLineTable(CU));22282229// Record beginning of function.2230PrologEndLoc = emitInitialLocDirective(2231*MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());2232}22332234unsigned2235DwarfDebug::getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU) {2236// Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function2237// belongs to so that we add to the correct per-cu line table in the2238// non-asm case.2239if (Asm->OutStreamer->hasRawTextSupport())2240// Use a single line table if we are generating assembly.2241return 0;2242else2243return CU.getUniqueID();2244}22452246void DwarfDebug::terminateLineTable(const DwarfCompileUnit *CU) {2247const auto &CURanges = CU->getRanges();2248auto &LineTable = Asm->OutStreamer->getContext().getMCDwarfLineTable(2249getDwarfCompileUnitIDForLineTable(*CU));2250// Add the last range label for the given CU.2251LineTable.getMCLineSections().addEndEntry(2252const_cast<MCSymbol *>(CURanges.back().End));2253}22542255void DwarfDebug::skippedNonDebugFunction() {2256// If we don't have a subprogram for this function then there will be a hole2257// in the range information. Keep note of this by setting the previously used2258// section to nullptr.2259// Terminate the pending line table.2260if (PrevCU)2261terminateLineTable(PrevCU);2262PrevCU = nullptr;2263CurFn = nullptr;2264}22652266// Gather and emit post-function debug information.2267void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {2268const DISubprogram *SP = MF->getFunction().getSubprogram();22692270assert(CurFn == MF &&2271"endFunction should be called with the same function as beginFunction");22722273// Set DwarfDwarfCompileUnitID in MCContext to default value.2274Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);22752276LexicalScope *FnScope = LScopes.getCurrentFunctionScope();2277assert(!FnScope || SP == FnScope->getScopeNode());2278DwarfCompileUnit &TheCU = getOrCreateDwarfCompileUnit(SP->getUnit());2279if (TheCU.getCUNode()->isDebugDirectivesOnly()) {2280PrevLabel = nullptr;2281CurFn = nullptr;2282return;2283}22842285DenseSet<InlinedEntity> Processed;2286collectEntityInfo(TheCU, SP, Processed);22872288// Add the range of this function to the list of ranges for the CU.2289// With basic block sections, add ranges for all basic block sections.2290for (const auto &R : Asm->MBBSectionRanges)2291TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});22922293// Under -gmlt, skip building the subprogram if there are no inlined2294// subroutines inside it. But with -fdebug-info-for-profiling, the subprogram2295// is still needed as we need its source location.2296if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&2297TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&2298LScopes.getAbstractScopesList().empty() && !IsDarwin) {2299for (const auto &R : Asm->MBBSectionRanges)2300addArangeLabel(SymbolCU(&TheCU, R.second.BeginLabel));23012302assert(InfoHolder.getScopeVariables().empty());2303PrevLabel = nullptr;2304CurFn = nullptr;2305return;2306}23072308#ifndef NDEBUG2309size_t NumAbstractSubprograms = LScopes.getAbstractScopesList().size();2310#endif2311for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {2312const auto *SP = cast<DISubprogram>(AScope->getScopeNode());2313for (const DINode *DN : SP->getRetainedNodes()) {2314const auto *LS = getRetainedNodeScope(DN);2315// Ensure LexicalScope is created for the scope of this node.2316auto *LexS = LScopes.getOrCreateAbstractScope(LS);2317assert(LexS && "Expected the LexicalScope to be created.");2318if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {2319// Collect info for variables/labels that were optimized out.2320if (!Processed.insert(InlinedEntity(DN, nullptr)).second ||2321TheCU.getExistingAbstractEntity(DN))2322continue;2323TheCU.createAbstractEntity(DN, LexS);2324} else {2325// Remember the node if this is a local declarations.2326LocalDeclsPerLS[LS].insert(DN);2327}2328assert(2329LScopes.getAbstractScopesList().size() == NumAbstractSubprograms &&2330"getOrCreateAbstractScope() inserted an abstract subprogram scope");2331}2332constructAbstractSubprogramScopeDIE(TheCU, AScope);2333}23342335ProcessedSPNodes.insert(SP);2336DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);2337if (auto *SkelCU = TheCU.getSkeleton())2338if (!LScopes.getAbstractScopesList().empty() &&2339TheCU.getCUNode()->getSplitDebugInlining())2340SkelCU->constructSubprogramScopeDIE(SP, FnScope);23412342// Construct call site entries.2343constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);23442345// Clear debug info2346// Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the2347// DbgVariables except those that are also in AbstractVariables (since they2348// can be used cross-function)2349InfoHolder.getScopeVariables().clear();2350InfoHolder.getScopeLabels().clear();2351LocalDeclsPerLS.clear();2352PrevLabel = nullptr;2353CurFn = nullptr;2354}23552356// Register a source line with debug info. Returns the unique label that was2357// emitted and which provides correspondence to the source line list.2358void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,2359unsigned Flags) {2360::recordSourceLine(*Asm, Line, Col, S, Flags,2361Asm->OutStreamer->getContext().getDwarfCompileUnitID(),2362getDwarfVersion(), getUnits());2363}23642365//===----------------------------------------------------------------------===//2366// Emit Methods2367//===----------------------------------------------------------------------===//23682369// Emit the debug info section.2370void DwarfDebug::emitDebugInfo() {2371DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;2372Holder.emitUnits(/* UseOffsets */ false);2373}23742375// Emit the abbreviation section.2376void DwarfDebug::emitAbbreviations() {2377DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;23782379Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());2380}23812382void DwarfDebug::emitStringOffsetsTableHeader() {2383DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;2384Holder.getStringPool().emitStringOffsetsTableHeader(2385*Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),2386Holder.getStringOffsetsStartSym());2387}23882389template <typename AccelTableT>2390void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,2391StringRef TableName) {2392Asm->OutStreamer->switchSection(Section);23932394// Emit the full data.2395emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());2396}23972398void DwarfDebug::emitAccelDebugNames() {2399// Don't emit anything if we have no compilation units to index.2400if (getUnits().empty())2401return;24022403emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());2404}24052406// Emit visible names into a hashed accelerator table section.2407void DwarfDebug::emitAccelNames() {2408emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),2409"Names");2410}24112412// Emit objective C classes and categories into a hashed accelerator table2413// section.2414void DwarfDebug::emitAccelObjC() {2415emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),2416"ObjC");2417}24182419// Emit namespace dies into a hashed accelerator table.2420void DwarfDebug::emitAccelNamespaces() {2421emitAccel(AccelNamespace,2422Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),2423"namespac");2424}24252426// Emit type dies into a hashed accelerator table.2427void DwarfDebug::emitAccelTypes() {2428emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),2429"types");2430}24312432// Public name handling.2433// The format for the various pubnames:2434//2435// dwarf pubnames - offset/name pairs where the offset is the offset into the CU2436// for the DIE that is named.2437//2438// gnu pubnames - offset/index value/name tuples where the offset is the offset2439// into the CU and the index value is computed according to the type of value2440// for the DIE that is named.2441//2442// For type units the offset is the offset of the skeleton DIE. For split dwarf2443// it's the offset within the debug_info/debug_types dwo section, however, the2444// reference in the pubname header doesn't change.24452446/// computeIndexValue - Compute the gdb index value for the DIE and CU.2447static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,2448const DIE *Die) {2449// Entities that ended up only in a Type Unit reference the CU instead (since2450// the pub entry has offsets within the CU there's no real offset that can be2451// provided anyway). As it happens all such entities (namespaces and types,2452// types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out2453// not to be true it would be necessary to persist this information from the2454// point at which the entry is added to the index data structure - since by2455// the time the index is built from that, the original type/namespace DIE in a2456// type unit has already been destroyed so it can't be queried for properties2457// like tag, etc.2458if (Die->getTag() == dwarf::DW_TAG_compile_unit)2459return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,2460dwarf::GIEL_EXTERNAL);2461dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;24622463// We could have a specification DIE that has our most of our knowledge,2464// look for that now.2465if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {2466DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();2467if (SpecDIE.findAttribute(dwarf::DW_AT_external))2468Linkage = dwarf::GIEL_EXTERNAL;2469} else if (Die->findAttribute(dwarf::DW_AT_external))2470Linkage = dwarf::GIEL_EXTERNAL;24712472switch (Die->getTag()) {2473case dwarf::DW_TAG_class_type:2474case dwarf::DW_TAG_structure_type:2475case dwarf::DW_TAG_union_type:2476case dwarf::DW_TAG_enumeration_type:2477return dwarf::PubIndexEntryDescriptor(2478dwarf::GIEK_TYPE,2479dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())2480? dwarf::GIEL_EXTERNAL2481: dwarf::GIEL_STATIC);2482case dwarf::DW_TAG_typedef:2483case dwarf::DW_TAG_base_type:2484case dwarf::DW_TAG_subrange_type:2485case dwarf::DW_TAG_template_alias:2486return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);2487case dwarf::DW_TAG_namespace:2488return dwarf::GIEK_TYPE;2489case dwarf::DW_TAG_subprogram:2490return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);2491case dwarf::DW_TAG_variable:2492return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);2493case dwarf::DW_TAG_enumerator:2494return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,2495dwarf::GIEL_STATIC);2496default:2497return dwarf::GIEK_NONE;2498}2499}25002501/// emitDebugPubSections - Emit visible names and types into debug pubnames and2502/// pubtypes sections.2503void DwarfDebug::emitDebugPubSections() {2504for (const auto &NU : CUMap) {2505DwarfCompileUnit *TheU = NU.second;2506if (!TheU->hasDwarfPubSections())2507continue;25082509bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==2510DICompileUnit::DebugNameTableKind::GNU;25112512Asm->OutStreamer->switchSection(2513GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()2514: Asm->getObjFileLowering().getDwarfPubNamesSection());2515emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());25162517Asm->OutStreamer->switchSection(2518GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()2519: Asm->getObjFileLowering().getDwarfPubTypesSection());2520emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());2521}2522}25232524void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {2525if (useSectionsAsReferences())2526Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),2527CU.getDebugSectionOffset());2528else2529Asm->emitDwarfSymbolReference(CU.getLabelBegin());2530}25312532void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,2533DwarfCompileUnit *TheU,2534const StringMap<const DIE *> &Globals) {2535if (auto *Skeleton = TheU->getSkeleton())2536TheU = Skeleton;25372538// Emit the header.2539MCSymbol *EndLabel = Asm->emitDwarfUnitLength(2540"pub" + Name, "Length of Public " + Name + " Info");25412542Asm->OutStreamer->AddComment("DWARF Version");2543Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);25442545Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");2546emitSectionReference(*TheU);25472548Asm->OutStreamer->AddComment("Compilation Unit Length");2549Asm->emitDwarfLengthOrOffset(TheU->getLength());25502551// Emit the pubnames for this compilation unit.2552SmallVector<std::pair<StringRef, const DIE *>, 0> Vec;2553for (const auto &GI : Globals)2554Vec.emplace_back(GI.first(), GI.second);2555llvm::sort(Vec, [](auto &A, auto &B) {2556return A.second->getOffset() < B.second->getOffset();2557});2558for (const auto &[Name, Entity] : Vec) {2559Asm->OutStreamer->AddComment("DIE offset");2560Asm->emitDwarfLengthOrOffset(Entity->getOffset());25612562if (GnuStyle) {2563dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);2564Asm->OutStreamer->AddComment(2565Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +2566", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));2567Asm->emitInt8(Desc.toBits());2568}25692570Asm->OutStreamer->AddComment("External Name");2571Asm->OutStreamer->emitBytes(StringRef(Name.data(), Name.size() + 1));2572}25732574Asm->OutStreamer->AddComment("End Mark");2575Asm->emitDwarfLengthOrOffset(0);2576Asm->OutStreamer->emitLabel(EndLabel);2577}25782579/// Emit null-terminated strings into a debug str section.2580void DwarfDebug::emitDebugStr() {2581MCSection *StringOffsetsSection = nullptr;2582if (useSegmentedStringOffsetsTable()) {2583emitStringOffsetsTableHeader();2584StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();2585}2586DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;2587Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),2588StringOffsetsSection, /* UseRelativeOffsets = */ true);2589}25902591void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,2592const DebugLocStream::Entry &Entry,2593const DwarfCompileUnit *CU) {2594auto &&Comments = DebugLocs.getComments(Entry);2595auto Comment = Comments.begin();2596auto End = Comments.end();25972598// The expressions are inserted into a byte stream rather early (see2599// DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that2600// need to reference a base_type DIE the offset of that DIE is not yet known.2601// To deal with this we instead insert a placeholder early and then extract2602// it here and replace it with the real reference.2603unsigned PtrSize = Asm->MAI->getCodePointerSize();2604DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),2605DebugLocs.getBytes(Entry).size()),2606Asm->getDataLayout().isLittleEndian(), PtrSize);2607DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());26082609using Encoding = DWARFExpression::Operation::Encoding;2610uint64_t Offset = 0;2611for (const auto &Op : Expr) {2612assert(Op.getCode() != dwarf::DW_OP_const_type &&2613"3 operand ops not yet supported");2614assert(!Op.getSubCode() && "SubOps not yet supported");2615Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");2616Offset++;2617for (unsigned I = 0; I < Op.getDescription().Op.size(); ++I) {2618if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {2619unsigned Length =2620Streamer.emitDIERef(*CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die);2621// Make sure comments stay aligned.2622for (unsigned J = 0; J < Length; ++J)2623if (Comment != End)2624Comment++;2625} else {2626for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)2627Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");2628}2629Offset = Op.getOperandEndOffset(I);2630}2631assert(Offset == Op.getEndOffset());2632}2633}26342635void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,2636const DbgValueLoc &Value,2637DwarfExpression &DwarfExpr) {2638auto *DIExpr = Value.getExpression();2639DIExpressionCursor ExprCursor(DIExpr);2640DwarfExpr.addFragmentOffset(DIExpr);26412642// If the DIExpr is an Entry Value, we want to follow the same code path2643// regardless of whether the DBG_VALUE is variadic or not.2644if (DIExpr && DIExpr->isEntryValue()) {2645// Entry values can only be a single register with no additional DIExpr,2646// so just add it directly.2647assert(Value.getLocEntries().size() == 1);2648assert(Value.getLocEntries()[0].isLocation());2649MachineLocation Location = Value.getLocEntries()[0].getLoc();2650DwarfExpr.setLocation(Location, DIExpr);26512652DwarfExpr.beginEntryValueExpression(ExprCursor);26532654const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();2655if (!DwarfExpr.addMachineRegExpression(TRI, ExprCursor, Location.getReg()))2656return;2657return DwarfExpr.addExpression(std::move(ExprCursor));2658}26592660// Regular entry.2661auto EmitValueLocEntry = [&DwarfExpr, &BT,2662&AP](const DbgValueLocEntry &Entry,2663DIExpressionCursor &Cursor) -> bool {2664if (Entry.isInt()) {2665if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||2666BT->getEncoding() == dwarf::DW_ATE_signed_char))2667DwarfExpr.addSignedConstant(Entry.getInt());2668else2669DwarfExpr.addUnsignedConstant(Entry.getInt());2670} else if (Entry.isLocation()) {2671MachineLocation Location = Entry.getLoc();2672if (Location.isIndirect())2673DwarfExpr.setMemoryLocationKind();26742675const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();2676if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))2677return false;2678} else if (Entry.isTargetIndexLocation()) {2679TargetIndexLocation Loc = Entry.getTargetIndexLocation();2680// TODO TargetIndexLocation is a target-independent. Currently only the2681// WebAssembly-specific encoding is supported.2682assert(AP.TM.getTargetTriple().isWasm());2683DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));2684} else if (Entry.isConstantFP()) {2685if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&2686!Cursor) {2687DwarfExpr.addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);2688} else if (Entry.getConstantFP()2689->getValueAPF()2690.bitcastToAPInt()2691.getBitWidth() <= 64 /*bits*/) {2692DwarfExpr.addUnsignedConstant(2693Entry.getConstantFP()->getValueAPF().bitcastToAPInt());2694} else {2695LLVM_DEBUG(2696dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"2697<< Entry.getConstantFP()2698->getValueAPF()2699.bitcastToAPInt()2700.getBitWidth()2701<< " bits\n");2702return false;2703}2704}2705return true;2706};27072708if (!Value.isVariadic()) {2709if (!EmitValueLocEntry(Value.getLocEntries()[0], ExprCursor))2710return;2711DwarfExpr.addExpression(std::move(ExprCursor));2712return;2713}27142715// If any of the location entries are registers with the value 0, then the2716// location is undefined.2717if (any_of(Value.getLocEntries(), [](const DbgValueLocEntry &Entry) {2718return Entry.isLocation() && !Entry.getLoc().getReg();2719}))2720return;27212722DwarfExpr.addExpression(2723std::move(ExprCursor),2724[EmitValueLocEntry, &Value](unsigned Idx,2725DIExpressionCursor &Cursor) -> bool {2726return EmitValueLocEntry(Value.getLocEntries()[Idx], Cursor);2727});2728}27292730void DebugLocEntry::finalize(const AsmPrinter &AP,2731DebugLocStream::ListBuilder &List,2732const DIBasicType *BT,2733DwarfCompileUnit &TheCU) {2734assert(!Values.empty() &&2735"location list entries without values are redundant");2736assert(Begin != End && "unexpected location list entry with empty range");2737DebugLocStream::EntryBuilder Entry(List, Begin, End);2738BufferByteStreamer Streamer = Entry.getStreamer();2739DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);2740const DbgValueLoc &Value = Values[0];2741if (Value.isFragment()) {2742// Emit all fragments that belong to the same variable and range.2743assert(llvm::all_of(Values, [](DbgValueLoc P) {2744return P.isFragment();2745}) && "all values are expected to be fragments");2746assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");27472748for (const auto &Fragment : Values)2749DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);27502751} else {2752assert(Values.size() == 1 && "only fragments may have >1 value");2753DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);2754}2755DwarfExpr.finalize();2756if (DwarfExpr.TagOffset)2757List.setTagOffset(*DwarfExpr.TagOffset);2758}27592760void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,2761const DwarfCompileUnit *CU) {2762// Emit the size.2763Asm->OutStreamer->AddComment("Loc expr size");2764if (getDwarfVersion() >= 5)2765Asm->emitULEB128(DebugLocs.getBytes(Entry).size());2766else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())2767Asm->emitInt16(DebugLocs.getBytes(Entry).size());2768else {2769// The entry is too big to fit into 16 bit, drop it as there is nothing we2770// can do.2771Asm->emitInt16(0);2772return;2773}2774// Emit the entry.2775APByteStreamer Streamer(*Asm);2776emitDebugLocEntry(Streamer, Entry, CU);2777}27782779// Emit the header of a DWARF 5 range list table list table. Returns the symbol2780// that designates the end of the table for the caller to emit when the table is2781// complete.2782static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,2783const DwarfFile &Holder) {2784MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);27852786Asm->OutStreamer->AddComment("Offset entry count");2787Asm->emitInt32(Holder.getRangeLists().size());2788Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());27892790for (const RangeSpanList &List : Holder.getRangeLists())2791Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),2792Asm->getDwarfOffsetByteSize());27932794return TableEnd;2795}27962797// Emit the header of a DWARF 5 locations list table. Returns the symbol that2798// designates the end of the table for the caller to emit when the table is2799// complete.2800static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,2801const DwarfDebug &DD) {2802MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);28032804const auto &DebugLocs = DD.getDebugLocs();28052806Asm->OutStreamer->AddComment("Offset entry count");2807Asm->emitInt32(DebugLocs.getLists().size());2808Asm->OutStreamer->emitLabel(DebugLocs.getSym());28092810for (const auto &List : DebugLocs.getLists())2811Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),2812Asm->getDwarfOffsetByteSize());28132814return TableEnd;2815}28162817template <typename Ranges, typename PayloadEmitter>2818static void emitRangeList(2819DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,2820const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,2821unsigned StartxLength, unsigned EndOfList,2822StringRef (*StringifyEnum)(unsigned),2823bool ShouldUseBaseAddress,2824PayloadEmitter EmitPayload) {28252826auto Size = Asm->MAI->getCodePointerSize();2827bool UseDwarf5 = DD.getDwarfVersion() >= 5;28282829// Emit our symbol so we can find the beginning of the range.2830Asm->OutStreamer->emitLabel(Sym);28312832// Gather all the ranges that apply to the same section so they can share2833// a base address entry.2834MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;28352836for (const auto &Range : R)2837SectionRanges[&Range.Begin->getSection()].push_back(&Range);28382839const MCSymbol *CUBase = CU.getBaseAddress();2840bool BaseIsSet = false;2841for (const auto &P : SectionRanges) {2842auto *Base = CUBase;2843if (!Base && ShouldUseBaseAddress) {2844const MCSymbol *Begin = P.second.front()->Begin;2845const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());2846if (!UseDwarf5) {2847Base = NewBase;2848BaseIsSet = true;2849Asm->OutStreamer->emitIntValue(-1, Size);2850Asm->OutStreamer->AddComment(" base address");2851Asm->OutStreamer->emitSymbolValue(Base, Size);2852} else if (NewBase != Begin || P.second.size() > 1) {2853// Only use a base address if2854// * the existing pool address doesn't match (NewBase != Begin)2855// * or, there's more than one entry to share the base address2856Base = NewBase;2857BaseIsSet = true;2858Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));2859Asm->emitInt8(BaseAddressx);2860Asm->OutStreamer->AddComment(" base address index");2861Asm->emitULEB128(DD.getAddressPool().getIndex(Base));2862}2863} else if (BaseIsSet && !UseDwarf5) {2864BaseIsSet = false;2865assert(!Base);2866Asm->OutStreamer->emitIntValue(-1, Size);2867Asm->OutStreamer->emitIntValue(0, Size);2868}28692870for (const auto *RS : P.second) {2871const MCSymbol *Begin = RS->Begin;2872const MCSymbol *End = RS->End;2873assert(Begin && "Range without a begin symbol?");2874assert(End && "Range without an end symbol?");2875if (Base) {2876if (UseDwarf5) {2877// Emit offset_pair when we have a base.2878Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));2879Asm->emitInt8(OffsetPair);2880Asm->OutStreamer->AddComment(" starting offset");2881Asm->emitLabelDifferenceAsULEB128(Begin, Base);2882Asm->OutStreamer->AddComment(" ending offset");2883Asm->emitLabelDifferenceAsULEB128(End, Base);2884} else {2885Asm->emitLabelDifference(Begin, Base, Size);2886Asm->emitLabelDifference(End, Base, Size);2887}2888} else if (UseDwarf5) {2889Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));2890Asm->emitInt8(StartxLength);2891Asm->OutStreamer->AddComment(" start index");2892Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));2893Asm->OutStreamer->AddComment(" length");2894Asm->emitLabelDifferenceAsULEB128(End, Begin);2895} else {2896Asm->OutStreamer->emitSymbolValue(Begin, Size);2897Asm->OutStreamer->emitSymbolValue(End, Size);2898}2899EmitPayload(*RS);2900}2901}29022903if (UseDwarf5) {2904Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));2905Asm->emitInt8(EndOfList);2906} else {2907// Terminate the list with two 0 values.2908Asm->OutStreamer->emitIntValue(0, Size);2909Asm->OutStreamer->emitIntValue(0, Size);2910}2911}29122913// Handles emission of both debug_loclist / debug_loclist.dwo2914static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {2915emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),2916*List.CU, dwarf::DW_LLE_base_addressx,2917dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,2918dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,2919/* ShouldUseBaseAddress */ true,2920[&](const DebugLocStream::Entry &E) {2921DD.emitDebugLocEntryLocation(E, List.CU);2922});2923}29242925void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {2926if (DebugLocs.getLists().empty())2927return;29282929Asm->OutStreamer->switchSection(Sec);29302931MCSymbol *TableEnd = nullptr;2932if (getDwarfVersion() >= 5)2933TableEnd = emitLoclistsTableHeader(Asm, *this);29342935for (const auto &List : DebugLocs.getLists())2936emitLocList(*this, Asm, List);29372938if (TableEnd)2939Asm->OutStreamer->emitLabel(TableEnd);2940}29412942// Emit locations into the .debug_loc/.debug_loclists section.2943void DwarfDebug::emitDebugLoc() {2944emitDebugLocImpl(2945getDwarfVersion() >= 52946? Asm->getObjFileLowering().getDwarfLoclistsSection()2947: Asm->getObjFileLowering().getDwarfLocSection());2948}29492950// Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.2951void DwarfDebug::emitDebugLocDWO() {2952if (getDwarfVersion() >= 5) {2953emitDebugLocImpl(2954Asm->getObjFileLowering().getDwarfLoclistsDWOSection());29552956return;2957}29582959for (const auto &List : DebugLocs.getLists()) {2960Asm->OutStreamer->switchSection(2961Asm->getObjFileLowering().getDwarfLocDWOSection());2962Asm->OutStreamer->emitLabel(List.Label);29632964for (const auto &Entry : DebugLocs.getEntries(List)) {2965// GDB only supports startx_length in pre-standard split-DWARF.2966// (in v5 standard loclists, it currently* /only/ supports base_address +2967// offset_pair, so the implementations can't really share much since they2968// need to use different representations)2969// * as of October 2018, at least2970//2971// In v5 (see emitLocList), this uses SectionLabels to reuse existing2972// addresses in the address pool to minimize object size/relocations.2973Asm->emitInt8(dwarf::DW_LLE_startx_length);2974unsigned idx = AddrPool.getIndex(Entry.Begin);2975Asm->emitULEB128(idx);2976// Also the pre-standard encoding is slightly different, emitting this as2977// an address-length entry here, but its a ULEB128 in DWARFv5 loclists.2978Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);2979emitDebugLocEntryLocation(Entry, List.CU);2980}2981Asm->emitInt8(dwarf::DW_LLE_end_of_list);2982}2983}29842985struct ArangeSpan {2986const MCSymbol *Start, *End;2987};29882989// Emit a debug aranges section, containing a CU lookup for any2990// address we can tie back to a CU.2991void DwarfDebug::emitDebugARanges() {2992if (ArangeLabels.empty())2993return;29942995// Provides a unique id per text section.2996MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;29972998// Filter labels by section.2999for (const SymbolCU &SCU : ArangeLabels) {3000if (SCU.Sym->isInSection()) {3001// Make a note of this symbol and it's section.3002MCSection *Section = &SCU.Sym->getSection();3003SectionMap[Section].push_back(SCU);3004} else {3005// Some symbols (e.g. common/bss on mach-o) can have no section but still3006// appear in the output. This sucks as we rely on sections to build3007// arange spans. We can do it without, but it's icky.3008SectionMap[nullptr].push_back(SCU);3009}3010}30113012DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;30133014for (auto &I : SectionMap) {3015MCSection *Section = I.first;3016SmallVector<SymbolCU, 8> &List = I.second;3017assert(!List.empty());30183019// If we have no section (e.g. common), just write out3020// individual spans for each symbol.3021if (!Section) {3022for (const SymbolCU &Cur : List) {3023ArangeSpan Span;3024Span.Start = Cur.Sym;3025Span.End = nullptr;3026assert(Cur.CU);3027Spans[Cur.CU].push_back(Span);3028}3029continue;3030}30313032// Insert a final terminator.3033List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));30343035// Build spans between each label.3036const MCSymbol *StartSym = List[0].Sym;3037for (size_t n = 1, e = List.size(); n < e; n++) {3038const SymbolCU &Prev = List[n - 1];3039const SymbolCU &Cur = List[n];30403041// Try and build the longest span we can within the same CU.3042if (Cur.CU != Prev.CU) {3043ArangeSpan Span;3044Span.Start = StartSym;3045Span.End = Cur.Sym;3046assert(Prev.CU);3047Spans[Prev.CU].push_back(Span);3048StartSym = Cur.Sym;3049}3050}3051}30523053// Start the dwarf aranges section.3054Asm->OutStreamer->switchSection(3055Asm->getObjFileLowering().getDwarfARangesSection());30563057unsigned PtrSize = Asm->MAI->getCodePointerSize();30583059// Build a list of CUs used.3060std::vector<DwarfCompileUnit *> CUs;3061for (const auto &it : Spans) {3062DwarfCompileUnit *CU = it.first;3063CUs.push_back(CU);3064}30653066// Sort the CU list (again, to ensure consistent output order).3067llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {3068return A->getUniqueID() < B->getUniqueID();3069});30703071// Emit an arange table for each CU we used.3072for (DwarfCompileUnit *CU : CUs) {3073std::vector<ArangeSpan> &List = Spans[CU];30743075// Describe the skeleton CU's offset and length, not the dwo file's.3076if (auto *Skel = CU->getSkeleton())3077CU = Skel;30783079// Emit size of content not including length itself.3080unsigned ContentSize =3081sizeof(int16_t) + // DWARF ARange version number3082Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info3083// section3084sizeof(int8_t) + // Pointer Size (in bytes)3085sizeof(int8_t); // Segment Size (in bytes)30863087unsigned TupleSize = PtrSize * 2;30883089// 7.20 in the Dwarf specs requires the table to be aligned to a tuple.3090unsigned Padding = offsetToAlignment(3091Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize));30923093ContentSize += Padding;3094ContentSize += (List.size() + 1) * TupleSize;30953096// For each compile unit, write the list of spans it covers.3097Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set");3098Asm->OutStreamer->AddComment("DWARF Arange version number");3099Asm->emitInt16(dwarf::DW_ARANGES_VERSION);3100Asm->OutStreamer->AddComment("Offset Into Debug Info Section");3101emitSectionReference(*CU);3102Asm->OutStreamer->AddComment("Address Size (in bytes)");3103Asm->emitInt8(PtrSize);3104Asm->OutStreamer->AddComment("Segment Size (in bytes)");3105Asm->emitInt8(0);31063107Asm->OutStreamer->emitFill(Padding, 0xff);31083109for (const ArangeSpan &Span : List) {3110Asm->emitLabelReference(Span.Start, PtrSize);31113112// Calculate the size as being from the span start to its end.3113//3114// If the size is zero, then round it up to one byte. The DWARF3115// specification requires that entries in this table have nonzero3116// lengths.3117auto SizeRef = SymSize.find(Span.Start);3118if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {3119Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);3120} else {3121// For symbols without an end marker (e.g. common), we3122// write a single arange entry containing just that one symbol.3123uint64_t Size;3124if (SizeRef == SymSize.end() || SizeRef->second == 0)3125Size = 1;3126else3127Size = SizeRef->second;31283129Asm->OutStreamer->emitIntValue(Size, PtrSize);3130}3131}31323133Asm->OutStreamer->AddComment("ARange terminator");3134Asm->OutStreamer->emitIntValue(0, PtrSize);3135Asm->OutStreamer->emitIntValue(0, PtrSize);3136}3137}31383139/// Emit a single range list. We handle both DWARF v5 and earlier.3140static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,3141const RangeSpanList &List) {3142emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,3143dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,3144dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,3145llvm::dwarf::RangeListEncodingString,3146List.CU->getCUNode()->getRangesBaseAddress() ||3147DD.getDwarfVersion() >= 5,3148[](auto) {});3149}31503151void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {3152if (Holder.getRangeLists().empty())3153return;31543155assert(useRangesSection());3156assert(!CUMap.empty());3157assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {3158return !Pair.second->getCUNode()->isDebugDirectivesOnly();3159}));31603161Asm->OutStreamer->switchSection(Section);31623163MCSymbol *TableEnd = nullptr;3164if (getDwarfVersion() >= 5)3165TableEnd = emitRnglistsTableHeader(Asm, Holder);31663167for (const RangeSpanList &List : Holder.getRangeLists())3168emitRangeList(*this, Asm, List);31693170if (TableEnd)3171Asm->OutStreamer->emitLabel(TableEnd);3172}31733174/// Emit address ranges into the .debug_ranges section or into the DWARF v53175/// .debug_rnglists section.3176void DwarfDebug::emitDebugRanges() {3177const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;31783179emitDebugRangesImpl(Holder,3180getDwarfVersion() >= 53181? Asm->getObjFileLowering().getDwarfRnglistsSection()3182: Asm->getObjFileLowering().getDwarfRangesSection());3183}31843185void DwarfDebug::emitDebugRangesDWO() {3186emitDebugRangesImpl(InfoHolder,3187Asm->getObjFileLowering().getDwarfRnglistsDWOSection());3188}31893190/// Emit the header of a DWARF 5 macro section, or the GNU extension for3191/// DWARF 4.3192static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,3193const DwarfCompileUnit &CU, uint16_t DwarfVersion) {3194enum HeaderFlagMask {3195#define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,3196#include "llvm/BinaryFormat/Dwarf.def"3197};3198Asm->OutStreamer->AddComment("Macro information version");3199Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);3200// We emit the line offset flag unconditionally here, since line offset should3201// be mostly present.3202if (Asm->isDwarf64()) {3203Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present");3204Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);3205} else {3206Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");3207Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);3208}3209Asm->OutStreamer->AddComment("debug_line_offset");3210if (DD.useSplitDwarf())3211Asm->emitDwarfLengthOrOffset(0);3212else3213Asm->emitDwarfSymbolReference(CU.getLineTableStartSym());3214}32153216void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {3217for (auto *MN : Nodes) {3218if (auto *M = dyn_cast<DIMacro>(MN))3219emitMacro(*M);3220else if (auto *F = dyn_cast<DIMacroFile>(MN))3221emitMacroFile(*F, U);3222else3223llvm_unreachable("Unexpected DI type!");3224}3225}32263227void DwarfDebug::emitMacro(DIMacro &M) {3228StringRef Name = M.getName();3229StringRef Value = M.getValue();32303231// There should be one space between the macro name and the macro value in3232// define entries. In undef entries, only the macro name is emitted.3233std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();32343235if (UseDebugMacroSection) {3236if (getDwarfVersion() >= 5) {3237unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define3238? dwarf::DW_MACRO_define_strx3239: dwarf::DW_MACRO_undef_strx;3240Asm->OutStreamer->AddComment(dwarf::MacroString(Type));3241Asm->emitULEB128(Type);3242Asm->OutStreamer->AddComment("Line Number");3243Asm->emitULEB128(M.getLine());3244Asm->OutStreamer->AddComment("Macro String");3245Asm->emitULEB128(3246InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());3247} else {3248unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define3249? dwarf::DW_MACRO_GNU_define_indirect3250: dwarf::DW_MACRO_GNU_undef_indirect;3251Asm->OutStreamer->AddComment(dwarf::GnuMacroString(Type));3252Asm->emitULEB128(Type);3253Asm->OutStreamer->AddComment("Line Number");3254Asm->emitULEB128(M.getLine());3255Asm->OutStreamer->AddComment("Macro String");3256Asm->emitDwarfSymbolReference(3257InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol());3258}3259} else {3260Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));3261Asm->emitULEB128(M.getMacinfoType());3262Asm->OutStreamer->AddComment("Line Number");3263Asm->emitULEB128(M.getLine());3264Asm->OutStreamer->AddComment("Macro String");3265Asm->OutStreamer->emitBytes(Str);3266Asm->emitInt8('\0');3267}3268}32693270void DwarfDebug::emitMacroFileImpl(3271DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,3272StringRef (*MacroFormToString)(unsigned Form)) {32733274Asm->OutStreamer->AddComment(MacroFormToString(StartFile));3275Asm->emitULEB128(StartFile);3276Asm->OutStreamer->AddComment("Line Number");3277Asm->emitULEB128(MF.getLine());3278Asm->OutStreamer->AddComment("File Number");3279DIFile &F = *MF.getFile();3280if (useSplitDwarf())3281Asm->emitULEB128(getDwoLineTable(U)->getFile(3282F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),3283Asm->OutContext.getDwarfVersion(), F.getSource()));3284else3285Asm->emitULEB128(U.getOrCreateSourceID(&F));3286handleMacroNodes(MF.getElements(), U);3287Asm->OutStreamer->AddComment(MacroFormToString(EndFile));3288Asm->emitULEB128(EndFile);3289}32903291void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {3292// DWARFv5 macro and DWARFv4 macinfo share some common encodings,3293// so for readibility/uniformity, We are explicitly emitting those.3294assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);3295if (UseDebugMacroSection)3296emitMacroFileImpl(3297F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,3298(getDwarfVersion() >= 5) ? dwarf::MacroString : dwarf::GnuMacroString);3299else3300emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,3301dwarf::DW_MACINFO_end_file, dwarf::MacinfoString);3302}33033304void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {3305for (const auto &P : CUMap) {3306auto &TheCU = *P.second;3307auto *SkCU = TheCU.getSkeleton();3308DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;3309auto *CUNode = cast<DICompileUnit>(P.first);3310DIMacroNodeArray Macros = CUNode->getMacros();3311if (Macros.empty())3312continue;3313Asm->OutStreamer->switchSection(Section);3314Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());3315if (UseDebugMacroSection)3316emitMacroHeader(Asm, *this, U, getDwarfVersion());3317handleMacroNodes(Macros, U);3318Asm->OutStreamer->AddComment("End Of Macro List Mark");3319Asm->emitInt8(0);3320}3321}33223323/// Emit macros into a debug macinfo/macro section.3324void DwarfDebug::emitDebugMacinfo() {3325auto &ObjLower = Asm->getObjFileLowering();3326emitDebugMacinfoImpl(UseDebugMacroSection3327? ObjLower.getDwarfMacroSection()3328: ObjLower.getDwarfMacinfoSection());3329}33303331void DwarfDebug::emitDebugMacinfoDWO() {3332auto &ObjLower = Asm->getObjFileLowering();3333emitDebugMacinfoImpl(UseDebugMacroSection3334? ObjLower.getDwarfMacroDWOSection()3335: ObjLower.getDwarfMacinfoDWOSection());3336}33373338// DWARF5 Experimental Separate Dwarf emitters.33393340void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,3341std::unique_ptr<DwarfCompileUnit> NewU) {33423343if (!CompilationDir.empty())3344NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);3345addGnuPubAttributes(*NewU, Die);33463347SkeletonHolder.addUnit(std::move(NewU));3348}33493350DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {33513352auto OwnedUnit = std::make_unique<DwarfCompileUnit>(3353CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,3354UnitKind::Skeleton);3355DwarfCompileUnit &NewCU = *OwnedUnit;3356NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());33573358NewCU.initStmtList();33593360if (useSegmentedStringOffsetsTable())3361NewCU.addStringOffsetsStart();33623363initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));33643365return NewCU;3366}33673368// Emit the .debug_info.dwo section for separated dwarf. This contains the3369// compile units that would normally be in debug_info.3370void DwarfDebug::emitDebugInfoDWO() {3371assert(useSplitDwarf() && "No split dwarf debug info?");3372// Don't emit relocations into the dwo file.3373InfoHolder.emitUnits(/* UseOffsets */ true);3374}33753376// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the3377// abbreviations for the .debug_info.dwo section.3378void DwarfDebug::emitDebugAbbrevDWO() {3379assert(useSplitDwarf() && "No split dwarf?");3380InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());3381}33823383void DwarfDebug::emitDebugLineDWO() {3384assert(useSplitDwarf() && "No split dwarf?");3385SplitTypeUnitFileTable.Emit(3386*Asm->OutStreamer, MCDwarfLineTableParams(),3387Asm->getObjFileLowering().getDwarfLineDWOSection());3388}33893390void DwarfDebug::emitStringOffsetsTableHeaderDWO() {3391assert(useSplitDwarf() && "No split dwarf?");3392InfoHolder.getStringPool().emitStringOffsetsTableHeader(3393*Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),3394InfoHolder.getStringOffsetsStartSym());3395}33963397// Emit the .debug_str.dwo section for separated dwarf. This contains the3398// string section and is identical in format to traditional .debug_str3399// sections.3400void DwarfDebug::emitDebugStrDWO() {3401if (useSegmentedStringOffsetsTable())3402emitStringOffsetsTableHeaderDWO();3403assert(useSplitDwarf() && "No split dwarf?");3404MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();3405InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),3406OffSec, /* UseRelativeOffsets = */ false);3407}34083409// Emit address pool.3410void DwarfDebug::emitDebugAddr() {3411AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());3412}34133414MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {3415if (!useSplitDwarf())3416return nullptr;3417const DICompileUnit *DIUnit = CU.getCUNode();3418SplitTypeUnitFileTable.maybeSetRootFile(3419DIUnit->getDirectory(), DIUnit->getFilename(),3420getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());3421return &SplitTypeUnitFileTable;3422}34233424uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {3425MD5 Hash;3426Hash.update(Identifier);3427// ... take the least significant 8 bytes and return those. Our MD53428// implementation always returns its results in little endian, so we actually3429// need the "high" word.3430MD5::MD5Result Result;3431Hash.final(Result);3432return Result.high();3433}34343435void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,3436StringRef Identifier, DIE &RefDie,3437const DICompositeType *CTy) {3438// Fast path if we're building some type units and one has already used the3439// address pool we know we're going to throw away all this work anyway, so3440// don't bother building dependent types.3441if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())3442return;34433444auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));3445if (!Ins.second) {3446CU.addDIETypeSignature(RefDie, Ins.first->second);3447return;3448}34493450setCurrentDWARF5AccelTable(DWARF5AccelTableKind::TU);3451bool TopLevelType = TypeUnitsUnderConstruction.empty();3452AddrPool.resetUsedFlag();34533454auto OwnedUnit = std::make_unique<DwarfTypeUnit>(3455CU, Asm, this, &InfoHolder, NumTypeUnitsCreated++, getDwoLineTable(CU));3456DwarfTypeUnit &NewTU = *OwnedUnit;3457DIE &UnitDie = NewTU.getUnitDie();3458TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);34593460NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,3461CU.getLanguage());34623463uint64_t Signature = makeTypeSignature(Identifier);3464NewTU.setTypeSignature(Signature);3465Ins.first->second = Signature;34663467if (useSplitDwarf()) {3468// Although multiple type units can have the same signature, they are not3469// guranteed to be bit identical. When LLDB uses .debug_names it needs to3470// know from which CU a type unit came from. These two attrbutes help it to3471// figure that out.3472if (getDwarfVersion() >= 5) {3473if (!CompilationDir.empty())3474NewTU.addString(UnitDie, dwarf::DW_AT_comp_dir, CompilationDir);3475NewTU.addString(UnitDie, dwarf::DW_AT_dwo_name,3476Asm->TM.Options.MCOptions.SplitDwarfFile);3477}3478MCSection *Section =3479getDwarfVersion() <= 43480? Asm->getObjFileLowering().getDwarfTypesDWOSection()3481: Asm->getObjFileLowering().getDwarfInfoDWOSection();3482NewTU.setSection(Section);3483} else {3484MCSection *Section =3485getDwarfVersion() <= 43486? Asm->getObjFileLowering().getDwarfTypesSection(Signature)3487: Asm->getObjFileLowering().getDwarfInfoSection(Signature);3488NewTU.setSection(Section);3489// Non-split type units reuse the compile unit's line table.3490CU.applyStmtList(UnitDie);3491}34923493// Add DW_AT_str_offsets_base to the type unit DIE, but not for split type3494// units.3495if (useSegmentedStringOffsetsTable() && !useSplitDwarf())3496NewTU.addStringOffsetsStart();34973498NewTU.setType(NewTU.createTypeDIE(CTy));34993500if (TopLevelType) {3501auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);3502TypeUnitsUnderConstruction.clear();35033504// Types referencing entries in the address table cannot be placed in type3505// units.3506if (AddrPool.hasBeenUsed()) {3507AccelTypeUnitsDebugNames.clear();3508// Remove all the types built while building this type.3509// This is pessimistic as some of these types might not be dependent on3510// the type that used an address.3511for (const auto &TU : TypeUnitsToAdd)3512TypeSignatures.erase(TU.second);35133514// Construct this type in the CU directly.3515// This is inefficient because all the dependent types will be rebuilt3516// from scratch, including building them in type units, discovering that3517// they depend on addresses, throwing them out and rebuilding them.3518setCurrentDWARF5AccelTable(DWARF5AccelTableKind::CU);3519CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));3520return;3521}35223523// If the type wasn't dependent on fission addresses, finish adding the type3524// and all its dependent types.3525for (auto &TU : TypeUnitsToAdd) {3526InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());3527InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());3528if (getDwarfVersion() >= 5 &&3529getAccelTableKind() == AccelTableKind::Dwarf) {3530if (useSplitDwarf())3531AccelDebugNames.addTypeUnitSignature(*TU.first);3532else3533AccelDebugNames.addTypeUnitSymbol(*TU.first);3534}3535}3536AccelTypeUnitsDebugNames.convertDieToOffset();3537AccelDebugNames.addTypeEntries(AccelTypeUnitsDebugNames);3538AccelTypeUnitsDebugNames.clear();3539setCurrentDWARF5AccelTable(DWARF5AccelTableKind::CU);3540}3541CU.addDIETypeSignature(RefDie, Signature);3542}35433544// Add the Name along with its companion DIE to the appropriate accelerator3545// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for3546// AccelTableKind::Apple, we use the table we got as an argument). If3547// accelerator tables are disabled, this function does nothing.3548template <typename DataT>3549void DwarfDebug::addAccelNameImpl(3550const DwarfUnit &Unit,3551const DICompileUnit::DebugNameTableKind NameTableKind,3552AccelTable<DataT> &AppleAccel, StringRef Name, const DIE &Die) {3553if (getAccelTableKind() == AccelTableKind::None ||3554Unit.getUnitDie().getTag() == dwarf::DW_TAG_skeleton_unit || Name.empty())3555return;35563557if (getAccelTableKind() != AccelTableKind::Apple &&3558NameTableKind != DICompileUnit::DebugNameTableKind::Apple &&3559NameTableKind != DICompileUnit::DebugNameTableKind::Default)3560return;35613562DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;3563DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);35643565switch (getAccelTableKind()) {3566case AccelTableKind::Apple:3567AppleAccel.addName(Ref, Die);3568break;3569case AccelTableKind::Dwarf: {3570DWARF5AccelTable &Current = getCurrentDWARF5AccelTable();3571assert(((&Current == &AccelTypeUnitsDebugNames) ||3572((&Current == &AccelDebugNames) &&3573(Unit.getUnitDie().getTag() != dwarf::DW_TAG_type_unit))) &&3574"Kind is CU but TU is being processed.");3575assert(((&Current == &AccelDebugNames) ||3576((&Current == &AccelTypeUnitsDebugNames) &&3577(Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit))) &&3578"Kind is TU but CU is being processed.");3579// The type unit can be discarded, so need to add references to final3580// acceleration table once we know it's complete and we emit it.3581Current.addName(Ref, Die, Unit.getUniqueID(),3582Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit);3583break;3584}3585case AccelTableKind::Default:3586llvm_unreachable("Default should have already been resolved.");3587case AccelTableKind::None:3588llvm_unreachable("None handled above");3589}3590}35913592void DwarfDebug::addAccelName(3593const DwarfUnit &Unit,3594const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,3595const DIE &Die) {3596addAccelNameImpl(Unit, NameTableKind, AccelNames, Name, Die);3597}35983599void DwarfDebug::addAccelObjC(3600const DwarfUnit &Unit,3601const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,3602const DIE &Die) {3603// ObjC names go only into the Apple accelerator tables.3604if (getAccelTableKind() == AccelTableKind::Apple)3605addAccelNameImpl(Unit, NameTableKind, AccelObjC, Name, Die);3606}36073608void DwarfDebug::addAccelNamespace(3609const DwarfUnit &Unit,3610const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,3611const DIE &Die) {3612addAccelNameImpl(Unit, NameTableKind, AccelNamespace, Name, Die);3613}36143615void DwarfDebug::addAccelType(3616const DwarfUnit &Unit,3617const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,3618const DIE &Die, char Flags) {3619addAccelNameImpl(Unit, NameTableKind, AccelTypes, Name, Die);3620}36213622uint16_t DwarfDebug::getDwarfVersion() const {3623return Asm->OutStreamer->getContext().getDwarfVersion();3624}36253626dwarf::Form DwarfDebug::getDwarfSectionOffsetForm() const {3627if (Asm->getDwarfVersion() >= 4)3628return dwarf::Form::DW_FORM_sec_offset;3629assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&3630"DWARF64 is not defined prior DWARFv3");3631return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data83632: dwarf::Form::DW_FORM_data4;3633}36343635const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {3636return SectionLabels.lookup(S);3637}36383639void DwarfDebug::insertSectionLabel(const MCSymbol *S) {3640if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)3641if (useSplitDwarf() || getDwarfVersion() >= 5)3642AddrPool.getIndex(S);3643}36443645std::optional<MD5::MD5Result>3646DwarfDebug::getMD5AsBytes(const DIFile *File) const {3647assert(File);3648if (getDwarfVersion() < 5)3649return std::nullopt;3650std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();3651if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)3652return std::nullopt;36533654// Convert the string checksum to an MD5Result for the streamer.3655// The verifier validates the checksum so we assume it's okay.3656// An MD5 checksum is 16 bytes.3657std::string ChecksumString = fromHex(Checksum->Value);3658MD5::MD5Result CKMem;3659std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.data());3660return CKMem;3661}36623663bool DwarfDebug::alwaysUseRanges(const DwarfCompileUnit &CU) const {3664if (MinimizeAddr == MinimizeAddrInV5::Ranges)3665return true;3666if (MinimizeAddr != MinimizeAddrInV5::Default)3667return false;3668if (useSplitDwarf())3669return true;3670return false;3671}367236733674