#include "DwarfDebug.h"
#include "ByteStreamer.h"
#include "DIEHash.h"
#include "DwarfCompileUnit.h"
#include "DwarfExpression.h"
#include "DwarfUnit.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/DIE.h"
#include "llvm/CodeGen/LexicalScopes.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
#include "llvm/DebugInfo/DWARF/DWARFExpression.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Module.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/MC/MachineLocation.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MD5.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cstddef>
#include <iterator>
#include <string>
using namespace llvm;
#define DEBUG_TYPE "dwarfdebug"
STATISTIC(NumCSParams, "Number of dbg call site params created");
static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
"use-dwarf-ranges-base-address-specifier", cl::Hidden,
cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
static cl::opt<bool> GenerateARangeSection("generate-arange-section",
cl::Hidden,
cl::desc("Generate dwarf aranges"),
cl::init(false));
static cl::opt<bool>
GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
cl::desc("Generate DWARF4 type units."),
cl::init(false));
static cl::opt<bool> SplitDwarfCrossCuReferences(
"split-dwarf-cross-cu-references", cl::Hidden,
cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
enum DefaultOnOff { Default, Enable, Disable };
static cl::opt<DefaultOnOff> UnknownLocations(
"use-unknown-locations", cl::Hidden,
cl::desc("Make an absence of debug location information explicit."),
cl::values(clEnumVal(Default, "At top of block or after label"),
clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
cl::init(Default));
static cl::opt<AccelTableKind> AccelTables(
"accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
cl::values(clEnumValN(AccelTableKind::Default, "Default",
"Default for platform"),
clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
cl::init(AccelTableKind::Default));
static cl::opt<DefaultOnOff>
DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
cl::desc("Use inlined strings rather than string section."),
cl::values(clEnumVal(Default, "Default for platform"),
clEnumVal(Enable, "Enabled"),
clEnumVal(Disable, "Disabled")),
cl::init(Default));
static cl::opt<bool>
NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
cl::desc("Disable emission .debug_ranges section."),
cl::init(false));
static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
"dwarf-sections-as-references", cl::Hidden,
cl::desc("Use sections+offset as references rather than labels."),
cl::values(clEnumVal(Default, "Default for platform"),
clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
cl::init(Default));
static cl::opt<bool>
UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden,
cl::desc("Emit the GNU .debug_macro format with DWARF <5"),
cl::init(false));
static cl::opt<DefaultOnOff> DwarfOpConvert(
"dwarf-op-convert", cl::Hidden,
cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"),
cl::values(clEnumVal(Default, "Default for platform"),
clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
cl::init(Default));
enum LinkageNameOption {
DefaultLinkageNames,
AllLinkageNames,
AbstractLinkageNames
};
static cl::opt<LinkageNameOption>
DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
cl::desc("Which DWARF linkage-name attributes to emit."),
cl::values(clEnumValN(DefaultLinkageNames, "Default",
"Default for platform"),
clEnumValN(AllLinkageNames, "All", "All"),
clEnumValN(AbstractLinkageNames, "Abstract",
"Abstract subprograms")),
cl::init(DefaultLinkageNames));
static cl::opt<DwarfDebug::MinimizeAddrInV5> MinimizeAddrInV5Option(
"minimize-addr-in-v5", cl::Hidden,
cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more "
"address pool entry sharing to reduce relocations/object size"),
cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default",
"Default address minimization strategy"),
clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges",
"Use rnglists for contiguous ranges if that allows "
"using a pre-existing base address"),
clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions,
"Expressions",
"Use exprloc addrx+offset expressions for any "
"address with a prior base address"),
clEnumValN(DwarfDebug::MinimizeAddrInV5::Form, "Form",
"Use addrx+offset extension form for any address "
"with a prior base address"),
clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled",
"Stuff")),
cl::init(DwarfDebug::MinimizeAddrInV5::Default));
static constexpr unsigned ULEB128PadSize = 4;
void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
getActiveStreamer().emitInt8(
Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
: dwarf::OperationEncodingString(Op));
}
void DebugLocDwarfExpression::emitSigned(int64_t Value) {
getActiveStreamer().emitSLEB128(Value, Twine(Value));
}
void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
getActiveStreamer().emitULEB128(Value, Twine(Value));
}
void DebugLocDwarfExpression::emitData1(uint8_t Value) {
getActiveStreamer().emitInt8(Value, Twine(Value));
}
void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
}
bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
llvm::Register MachineReg) {
return false;
}
void DebugLocDwarfExpression::enableTemporaryBuffer() {
assert(!IsBuffering && "Already buffering?");
if (!TmpBuf)
TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
IsBuffering = true;
}
void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
return TmpBuf ? TmpBuf->Bytes.size() : 0;
}
void DebugLocDwarfExpression::commitTemporaryBuffer() {
if (!TmpBuf)
return;
for (auto Byte : enumerate(TmpBuf->Bytes)) {
const char *Comment = (Byte.index() < TmpBuf->Comments.size())
? TmpBuf->Comments[Byte.index()].c_str()
: "";
OutBS.emitInt8(Byte.value(), Comment);
}
TmpBuf->Bytes.clear();
TmpBuf->Comments.clear();
}
const DIType *DbgVariable::getType() const {
return getVariable()->getType();
}
static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
const DIExpression *Expr = MI->getDebugExpression();
const bool IsVariadic = MI->isDebugValueList();
assert(MI->getNumOperands() >= 3);
SmallVector<DbgValueLocEntry, 4> DbgValueLocEntries;
for (const MachineOperand &Op : MI->debug_operands()) {
if (Op.isReg()) {
MachineLocation MLoc(Op.getReg(),
MI->isNonListDebugValue() && MI->isDebugOffsetImm());
DbgValueLocEntries.push_back(DbgValueLocEntry(MLoc));
} else if (Op.isTargetIndex()) {
DbgValueLocEntries.push_back(
DbgValueLocEntry(TargetIndexLocation(Op.getIndex(), Op.getOffset())));
} else if (Op.isImm())
DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getImm()));
else if (Op.isFPImm())
DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getFPImm()));
else if (Op.isCImm())
DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getCImm()));
else
llvm_unreachable("Unexpected debug operand in DBG_VALUE* instruction!");
}
return DbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);
}
void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) {
assert(FrameIndexExprs.empty() && "Already initialized?");
assert(!ValueLoc.get() && "Already initialized?");
assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable");
assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() &&
"Wrong inlined-at");
ValueLoc = std::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue));
if (auto *E = DbgValue->getDebugExpression())
if (E->getNumElements())
FrameIndexExprs.push_back({0, E});
}
ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
if (FrameIndexExprs.size() == 1)
return FrameIndexExprs;
assert(llvm::all_of(FrameIndexExprs,
[](const FrameIndexExpr &A) {
return A.Expr->isFragment();
}) &&
"multiple FI expressions without DW_OP_LLVM_fragment");
llvm::sort(FrameIndexExprs,
[](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
return A.Expr->getFragmentInfo()->OffsetInBits <
B.Expr->getFragmentInfo()->OffsetInBits;
});
return FrameIndexExprs;
}
void DbgVariable::addMMIEntry(const DbgVariable &V) {
assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry");
assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry");
assert(V.getVariable() == getVariable() && "conflicting variable");
assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
if (FrameIndexExprs.size()) {
auto *Expr = FrameIndexExprs.back().Expr;
if (!Expr || !Expr->isFragment())
return;
}
for (const auto &FIE : V.FrameIndexExprs)
if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
}))
FrameIndexExprs.push_back(FIE);
assert((FrameIndexExprs.size() == 1 ||
llvm::all_of(FrameIndexExprs,
[](FrameIndexExpr &FIE) {
return FIE.Expr && FIE.Expr->isFragment();
})) &&
"conflicting locations for variable");
}
static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
bool GenerateTypeUnits,
DebuggerKind Tuning,
const Triple &TT) {
if (AccelTables != AccelTableKind::Default)
return AccelTables;
if (GenerateTypeUnits)
return AccelTableKind::None;
if (DwarfVersion >= 5)
return AccelTableKind::Dwarf;
if (Tuning == DebuggerKind::LLDB)
return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
: AccelTableKind::Dwarf;
return AccelTableKind::None;
}
DwarfDebug::DwarfDebug(AsmPrinter *A)
: DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
InfoHolder(A, "info_string", DIEValueAllocator),
SkeletonHolder(A, "skel_string", DIEValueAllocator),
IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
const Triple &TT = Asm->TM.getTargetTriple();
if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
DebuggerTuning = Asm->TM.Options.DebuggerTuning;
else if (IsDarwin)
DebuggerTuning = DebuggerKind::LLDB;
else if (TT.isPS())
DebuggerTuning = DebuggerKind::SCE;
else if (TT.isOSAIX())
DebuggerTuning = DebuggerKind::DBX;
else
DebuggerTuning = DebuggerKind::GDB;
if (DwarfInlinedStrings == Default)
UseInlineStrings = TT.isNVPTX() || tuneForDBX();
else
UseInlineStrings = DwarfInlinedStrings == Enable;
UseLocSection = !TT.isNVPTX();
HasAppleExtensionAttributes = tuneForLLDB();
HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
if (DwarfLinkageNames == DefaultLinkageNames)
UseAllLinkageNames = !tuneForSCE();
else
UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
: MMI->getModule()->getDwarfVersion();
DwarfVersion =
TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
bool Dwarf64 = DwarfVersion >= 3 && TT.isArch64Bit();
Dwarf64 &=
((Asm->TM.Options.MCOptions.Dwarf64 || MMI->getModule()->isDwarf64()) &&
TT.isOSBinFormatELF()) ||
TT.isOSBinFormatXCOFF();
if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())
report_fatal_error("XCOFF requires DWARF64 for 64-bit mode!");
UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
if (DwarfSectionsAsReferences == Default)
UseSectionsAsReferences = TT.isNVPTX();
else
UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() ||
A->TM.getTargetTriple().isOSBinFormatWasm()) &&
GenerateDwarfTypeUnits;
TheAccelTableKind = computeAccelTableKind(
DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();
UseDebugMacroSection =
DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());
if (DwarfOpConvert == Default)
EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO()));
else
EnableOpConvert = (DwarfOpConvert == Enable);
if (DwarfVersion >= 5) {
MinimizeAddr = MinimizeAddrInV5Option;
if (MinimizeAddr == MinimizeAddrInV5::Default)
MinimizeAddr = MinimizeAddrInV5::Disabled;
}
Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64
: dwarf::DWARF32);
}
DwarfDebug::~DwarfDebug() = default;
static bool isObjCClass(StringRef Name) {
return Name.startswith("+") || Name.startswith("-");
}
static bool hasObjCCategory(StringRef Name) {
if (!isObjCClass(Name))
return false;
return Name.contains(") ");
}
static void getObjCClassCategory(StringRef In, StringRef &Class,
StringRef &Category) {
if (!hasObjCCategory(In)) {
Class = In.slice(In.find('[') + 1, In.find(' '));
Category = "";
return;
}
Class = In.slice(In.find('[') + 1, In.find('('));
Category = In.slice(In.find('[') + 1, In.find(' '));
}
static StringRef getObjCMethodName(StringRef In) {
return In.slice(In.find(' ') + 1, In.find(']'));
}
void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
const DISubprogram *SP, DIE &Die) {
if (getAccelTableKind() != AccelTableKind::Apple &&
CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
return;
if (!SP->isDefinition())
return;
if (SP->getName() != "")
addAccelName(CU, SP->getName(), Die);
if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
(useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
addAccelName(CU, SP->getLinkageName(), Die);
if (isObjCClass(SP->getName())) {
StringRef Class, Category;
getObjCClassCategory(SP->getName(), Class, Category);
addAccelObjC(CU, Class, Die);
if (Category != "")
addAccelObjC(CU, Category, Die);
addAccelName(CU, getObjCMethodName(SP->getName()), Die);
}
}
bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
if (Scope->isAbstractScope())
return false;
const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
if (Ranges.empty())
return true;
if (Ranges.size() > 1)
return false;
return !getLabelAfterInsn(Ranges.front().second);
}
template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
F(CU);
if (auto *SkelCU = CU.getSkeleton())
if (CU.getCUNode()->getSplitDebugInlining())
F(*SkelCU);
}
bool DwarfDebug::shareAcrossDWOCUs() const {
return SplitDwarfCrossCuReferences;
}
void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
LexicalScope *Scope) {
assert(Scope && Scope->getScopeNode());
assert(Scope->isAbstractScope());
assert(!Scope->getInlinedAt());
auto *SP = cast<DISubprogram>(Scope->getScopeNode());
if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
SrcCU.constructAbstractSubprogramScopeDIE(Scope);
else {
auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
if (auto *SkelCU = CU.getSkeleton()) {
(shareAcrossDWOCUs() ? CU : SrcCU)
.constructAbstractSubprogramScopeDIE(Scope);
if (CU.getCUNode()->getSplitDebugInlining())
SkelCU->constructAbstractSubprogramScopeDIE(Scope);
} else
CU.constructAbstractSubprogramScopeDIE(Scope);
}
}
struct FwdRegParamInfo {
unsigned ParamReg;
const DIExpression *Expr;
};
using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>;
static const DIExpression *combineDIExpressions(const DIExpression *Original,
const DIExpression *Addition) {
std::vector<uint64_t> Elts = Addition->getElements().vec();
if (Original->isImplicit() && Addition->isImplicit())
erase_value(Elts, dwarf::DW_OP_stack_value);
const DIExpression *CombinedExpr =
(Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;
return CombinedExpr;
}
template <typename ValT>
static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
ArrayRef<FwdRegParamInfo> DescribedParams,
ParamSet &Params) {
for (auto Param : DescribedParams) {
bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
if (ShouldCombineExpressions && Expr->isEntryValue())
continue;
const DIExpression *CombinedExpr =
ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)
: Expr;
assert((!CombinedExpr || CombinedExpr->isValid()) &&
"Combined debug expression is invalid");
DbgValueLoc DbgLocVal(CombinedExpr, DbgValueLocEntry(Val));
DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
Params.push_back(CSParm);
++NumCSParams;
}
}
static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
const DIExpression *Expr,
ArrayRef<FwdRegParamInfo> ParamsToAdd) {
auto I = Worklist.insert({Reg, {}});
auto &ParamsForFwdReg = I.first->second;
for (auto Param : ParamsToAdd) {
assert(none_of(ParamsForFwdReg,
[Param](const FwdRegParamInfo &D) {
return D.ParamReg == Param.ParamReg;
}) &&
"Same parameter described twice by forwarding reg");
const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);
ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
}
}
static void interpretValues(const MachineInstr *CurMI,
FwdRegWorklist &ForwardedRegWorklist,
ParamSet &Params) {
const MachineFunction *MF = CurMI->getMF();
const DIExpression *EmptyExpr =
DIExpression::get(MF->getFunction().getContext(), {});
const auto &TRI = *MF->getSubtarget().getRegisterInfo();
const auto &TII = *MF->getSubtarget().getInstrInfo();
const auto &TLI = *MF->getSubtarget().getTargetLowering();
FwdRegWorklist TmpWorklistItems;
auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
SmallSetVector<unsigned, 4> &Defs) {
if (MI.isDebugInstr())
return;
for (const MachineOperand &MO : MI.operands()) {
if (MO.isReg() && MO.isDef() &&
Register::isPhysicalRegister(MO.getReg())) {
for (auto &FwdReg : ForwardedRegWorklist)
if (TRI.regsOverlap(FwdReg.first, MO.getReg()))
Defs.insert(FwdReg.first);
}
}
};
SmallSetVector<unsigned, 4> FwdRegDefs;
getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
if (FwdRegDefs.empty())
return;
for (auto ParamFwdReg : FwdRegDefs) {
if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
if (ParamValue->first.isImm()) {
int64_t Val = ParamValue->first.getImm();
finishCallSiteParams(Val, ParamValue->second,
ForwardedRegWorklist[ParamFwdReg], Params);
} else if (ParamValue->first.isReg()) {
Register RegLoc = ParamValue->first.getReg();
Register SP = TLI.getStackPointerRegisterToSaveRestore();
Register FP = TRI.getFrameRegister(*MF);
bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
if (TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP) {
MachineLocation MLoc(RegLoc, IsSPorFP);
finishCallSiteParams(MLoc, ParamValue->second,
ForwardedRegWorklist[ParamFwdReg], Params);
} else {
addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second,
ForwardedRegWorklist[ParamFwdReg]);
}
}
}
}
for (auto ParamFwdReg : FwdRegDefs)
ForwardedRegWorklist.erase(ParamFwdReg);
for (auto &New : TmpWorklistItems)
addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second);
TmpWorklistItems.clear();
}
static bool interpretNextInstr(const MachineInstr *CurMI,
FwdRegWorklist &ForwardedRegWorklist,
ParamSet &Params) {
if (CurMI->isBundle())
return true;
if (CurMI->isCall())
return false;
if (ForwardedRegWorklist.empty())
return false;
if (CurMI->getNumOperands() == 0)
return true;
interpretValues(CurMI, ForwardedRegWorklist, Params);
return true;
}
static void collectCallSiteParameters(const MachineInstr *CallMI,
ParamSet &Params) {
const MachineFunction *MF = CallMI->getMF();
const auto &CalleesMap = MF->getCallSitesInfo();
auto CallFwdRegsInfo = CalleesMap.find(CallMI);
if (CallFwdRegsInfo == CalleesMap.end())
return;
const MachineBasicBlock *MBB = CallMI->getParent();
auto I = std::next(CallMI->getReverseIterator());
FwdRegWorklist ForwardedRegWorklist;
const DIExpression *EmptyExpr =
DIExpression::get(MF->getFunction().getContext(), {});
for (const auto &ArgReg : CallFwdRegsInfo->second) {
bool InsertedReg =
ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
.second;
assert(InsertedReg && "Single register used to forward two arguments?");
(void)InsertedReg;
}
for (const auto &MO : CallMI->uses())
if (MO.isReg() && MO.isUndef())
ForwardedRegWorklist.erase(MO.getReg());
bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
if (CallMI->hasDelaySlot()) {
auto Suc = std::next(CallMI->getIterator());
auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator());
(void)BundleEnd;
assert(std::next(Suc) == BundleEnd &&
"More than one instruction in call delay slot");
if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params))
return;
}
for (; I != MBB->rend(); ++I) {
if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params))
return;
}
if (ShouldTryEmitEntryVals) {
DIExpression *EntryExpr = DIExpression::get(
MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
for (auto &RegEntry : ForwardedRegWorklist) {
MachineLocation MLoc(RegEntry.first);
finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
}
}
}
void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
DwarfCompileUnit &CU, DIE &ScopeDIE,
const MachineFunction &MF) {
if (!SP.areAllCallsDescribed() || !SP.isDefinition())
return;
CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
assert(TII && "TargetInstrInfo not found: cannot label tail calls");
auto delaySlotSupported = [&](const MachineInstr &MI) {
if (!MI.isBundledWithSucc())
return false;
auto Suc = std::next(MI.getIterator());
auto CallInstrBundle = getBundleStart(MI.getIterator());
(void)CallInstrBundle;
auto DelaySlotBundle = getBundleStart(Suc);
(void)DelaySlotBundle;
assert(getLabelAfterInsn(&*CallInstrBundle) ==
getLabelAfterInsn(&*DelaySlotBundle) &&
"Call and its successor instruction don't have same label after.");
return true;
};
for (const MachineBasicBlock &MBB : MF) {
for (const MachineInstr &MI : MBB.instrs()) {
if (MI.isBundle())
continue;
if (!MI.isCandidateForCallSiteEntry())
continue;
if (MI.getFlag(MachineInstr::FrameSetup))
continue;
if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))
return;
const MachineOperand &CalleeOp = TII->getCalleeOperand(MI);
if (!CalleeOp.isGlobal() &&
(!CalleeOp.isReg() ||
!Register::isPhysicalRegister(CalleeOp.getReg())))
continue;
unsigned CallReg = 0;
const DISubprogram *CalleeSP = nullptr;
const Function *CalleeDecl = nullptr;
if (CalleeOp.isReg()) {
CallReg = CalleeOp.getReg();
if (!CallReg)
continue;
} else {
CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
if (!CalleeDecl || !CalleeDecl->getSubprogram())
continue;
CalleeSP = CalleeDecl->getSubprogram();
}
bool IsTail = TII->isTailCall(MI);
const MachineInstr *TopLevelCallMI =
MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
const MCSymbol *PCAddr =
(!IsTail || CU.useGNUAnalogForDwarf5Feature())
? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
: nullptr;
const MCSymbol *CallAddr =
IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr;
assert((IsTail || PCAddr) && "Non-tail call without return PC");
LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
<< (CalleeDecl ? CalleeDecl->getName()
: StringRef(MF.getSubtarget()
.getRegisterInfo()
->getName(CallReg)))
<< (IsTail ? " [IsTail]" : "") << "\n");
DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(
ScopeDIE, CalleeSP, IsTail, PCAddr, CallAddr, CallReg);
if (emitDebugEntryValues()) {
ParamSet Params;
collectCallSiteParameters(&MI, Params);
CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
}
}
}
}
void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
if (!U.hasDwarfPubSections())
return;
U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
}
void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
DwarfCompileUnit &NewCU) {
DIE &Die = NewCU.getUnitDie();
StringRef FN = DIUnit->getFilename();
StringRef Producer = DIUnit->getProducer();
StringRef Flags = DIUnit->getFlags();
if (!Flags.empty() && !useAppleExtensionAttributes()) {
std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
} else
NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
DIUnit->getSourceLanguage());
NewCU.addString(Die, dwarf::DW_AT_name, FN);
StringRef SysRoot = DIUnit->getSysRoot();
if (!SysRoot.empty())
NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
StringRef SDK = DIUnit->getSDK();
if (!SDK.empty())
NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
NewCU.addStringOffsetsStart();
if (!useSplitDwarf()) {
NewCU.initStmtList();
if (!CompilationDir.empty())
NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
addGnuPubAttributes(NewCU, Die);
}
if (useAppleExtensionAttributes()) {
if (DIUnit->isOptimized())
NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
StringRef Flags = DIUnit->getFlags();
if (!Flags.empty())
NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
if (unsigned RVer = DIUnit->getRuntimeVersion())
NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
dwarf::DW_FORM_data1, RVer);
}
if (DIUnit->getDWOId()) {
NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
DIUnit->getDWOId());
if (!DIUnit->getSplitDebugFilename().empty()) {
dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
? dwarf::DW_AT_dwo_name
: dwarf::DW_AT_GNU_dwo_name;
NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
}
}
}
DwarfCompileUnit &
DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
if (auto *CU = CUMap.lookup(DIUnit))
return *CU;
CompilationDir = DIUnit->getDirectory();
auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
DwarfCompileUnit &NewCU = *OwnedUnit;
InfoHolder.addUnit(std::move(OwnedUnit));
for (auto *IE : DIUnit->getImportedEntities())
NewCU.addImportedEntity(IE);
if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
Asm->OutStreamer->emitDwarfFile0Directive(
CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()),
DIUnit->getSource(), NewCU.getUniqueID());
if (useSplitDwarf()) {
NewCU.setSkeleton(constructSkeletonCU(NewCU));
NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
} else {
finishUnitAttributes(DIUnit, NewCU);
NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
}
CUMap.insert({DIUnit, &NewCU});
CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
return NewCU;
}
void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
const DIImportedEntity *N) {
if (isa<DILocalScope>(N->getScope()))
return;
if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
D->addChild(TheCU.constructImportedEntityDIE(N));
}
static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
llvm::sort(
GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
if (!A.Expr || !B.Expr)
return !!B.Expr;
auto FragmentA = A.Expr->getFragmentInfo();
auto FragmentB = B.Expr->getFragmentInfo();
if (!FragmentA || !FragmentB)
return !!FragmentB;
return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
});
GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
[](DwarfCompileUnit::GlobalExpr A,
DwarfCompileUnit::GlobalExpr B) {
return A.Expr == B.Expr;
}),
GVEs.end());
return GVEs;
}
void DwarfDebug::beginModule(Module *M) {
DebugHandlerBase::beginModule(M);
if (!Asm || !MMI->hasDebugInfo())
return;
unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
M->debug_compile_units_end());
assert(NumDebugCUs > 0 && "Asm unexpectedly initialized");
assert(MMI->hasDebugInfo() &&
"DebugInfoAvailabilty unexpectedly not initialized");
SingleCU = NumDebugCUs == 1;
DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
GVMap;
for (const GlobalVariable &Global : M->globals()) {
SmallVector<DIGlobalVariableExpression *, 1> GVs;
Global.getDebugInfo(GVs);
for (auto *GVE : GVs)
GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
}
if (useSegmentedStringOffsetsTable())
(useSplitDwarf() ? SkeletonHolder : InfoHolder)
.setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
if (getDwarfVersion() >= 5) {
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Holder.setRnglistsTableBaseSym(
Asm->createTempSymbol("rnglists_table_base"));
if (useSplitDwarf())
InfoHolder.setRnglistsTableBaseSym(
Asm->createTempSymbol("rnglists_dwo_table_base"));
}
AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
for (DICompileUnit *CUNode : M->debug_compile_units()) {
bool HasNonLocalImportedEntities = llvm::any_of(
CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
return !isa<DILocalScope>(IE->getScope());
});
if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
CUNode->getRetainedTypes().empty() &&
CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
continue;
DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
for (auto *GVE : CUNode->getGlobalVariables()) {
auto &GVMapEntry = GVMap[GVE->getVariable()];
auto *Expr = GVE->getExpression();
if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
GVMapEntry.push_back({nullptr, Expr});
}
DenseSet<DIGlobalVariable *> Processed;
for (auto *GVE : CUNode->getGlobalVariables()) {
DIGlobalVariable *GV = GVE->getVariable();
if (Processed.insert(GV).second)
CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
}
for (auto *Ty : CUNode->getEnumTypes())
CU.getOrCreateTypeDIE(cast<DIType>(Ty));
for (auto *Ty : CUNode->getRetainedTypes()) {
if (DIType *RT = dyn_cast<DIType>(Ty))
CU.getOrCreateTypeDIE(RT);
}
for (auto *IE : CUNode->getImportedEntities())
constructAndAddImportedEntityDIE(CU, IE);
}
}
void DwarfDebug::finishEntityDefinitions() {
for (const auto &Entity : ConcreteEntities) {
DIE *Die = Entity->getDIE();
assert(Die);
DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
assert(Unit);
Unit->finishEntityDefinition(Entity.get());
}
}
void DwarfDebug::finishSubprogramDefinitions() {
for (const DISubprogram *SP : ProcessedSPNodes) {
assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
forBothCUs(
getOrCreateDwarfCompileUnit(SP->getUnit()),
[&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
}
}
void DwarfDebug::finalizeModuleInfo() {
const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
finishSubprogramDefinitions();
finishEntityDefinitions();
StringRef DWOName;
if (CUMap.size() > 1)
DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
for (const auto &P : CUMap) {
auto &TheCU = *P.second;
if (TheCU.getCUNode()->isDebugDirectivesOnly())
continue;
TheCU.constructContainingTypeDIEs();
auto *SkCU = TheCU.getSkeleton();
bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
if (HasSplitUnit) {
dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
? dwarf::DW_AT_dwo_name
: dwarf::DW_AT_GNU_dwo_name;
finishUnitAttributes(TheCU.getCUNode(), TheCU);
TheCU.addString(TheCU.getUnitDie(), attrDWOName,
Asm->TM.Options.MCOptions.SplitDwarfFile);
SkCU->addString(SkCU->getUnitDie(), attrDWOName,
Asm->TM.Options.MCOptions.SplitDwarfFile);
uint64_t ID =
DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());
if (getDwarfVersion() >= 5) {
TheCU.setDWOId(ID);
SkCU->setDWOId(ID);
} else {
TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
dwarf::DW_FORM_data8, ID);
SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
dwarf::DW_FORM_data8, ID);
}
if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
Sym, Sym);
}
} else if (SkCU) {
finishUnitAttributes(SkCU->getCUNode(), *SkCU);
}
DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
if (unsigned NumRanges = TheCU.getRanges().size()) {
if (NumRanges > 1 && useRangesSection())
U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
else
U.setBaseAddress(TheCU.getRanges().front().Begin);
U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
}
if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
U.addAddrTableBase();
if (getDwarfVersion() >= 5) {
if (U.hasRangeLists())
U.addRnglistsBase();
if (!DebugLocs.getLists().empty()) {
if (!useSplitDwarf())
U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
DebugLocs.getSym(),
TLOF.getDwarfLoclistsSection()->getBeginSymbol());
}
}
auto *CUNode = cast<DICompileUnit>(P.first);
if (CUNode->getMacros()) {
if (UseDebugMacroSection) {
if (useSplitDwarf())
TheCU.addSectionDelta(
TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
TLOF.getDwarfMacroDWOSection()->getBeginSymbol());
else {
dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5
? dwarf::DW_AT_macros
: dwarf::DW_AT_GNU_macros;
U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),
TLOF.getDwarfMacroSection()->getBeginSymbol());
}
} else {
if (useSplitDwarf())
TheCU.addSectionDelta(
TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
U.getMacroLabelBegin(),
TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
else
U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
U.getMacroLabelBegin(),
TLOF.getDwarfMacinfoSection()->getBeginSymbol());
}
}
}
for (auto *CUNode : MMI->getModule()->debug_compile_units())
if (CUNode->getDWOId())
getOrCreateDwarfCompileUnit(CUNode);
InfoHolder.computeSizeAndOffsets();
if (useSplitDwarf())
SkeletonHolder.computeSizeAndOffsets();
}
void DwarfDebug::endModule() {
if (PrevCU)
terminateLineTable(PrevCU);
PrevCU = nullptr;
assert(CurFn == nullptr);
assert(CurMI == nullptr);
for (const auto &P : CUMap) {
auto &CU = *P.second;
CU.createBaseTypeDIEs();
}
if (!Asm || !MMI->hasDebugInfo())
return;
finalizeModuleInfo();
if (useSplitDwarf())
emitDebugLocDWO();
else
emitDebugLoc();
emitAbbreviations();
emitDebugInfo();
if (GenerateARangeSection)
emitDebugARanges();
emitDebugRanges();
if (useSplitDwarf())
emitDebugMacinfoDWO();
else
emitDebugMacinfo();
emitDebugStr();
if (useSplitDwarf()) {
emitDebugStrDWO();
emitDebugInfoDWO();
emitDebugAbbrevDWO();
emitDebugLineDWO();
emitDebugRangesDWO();
}
emitDebugAddr();
switch (getAccelTableKind()) {
case AccelTableKind::Apple:
emitAccelNames();
emitAccelObjC();
emitAccelNamespaces();
emitAccelTypes();
break;
case AccelTableKind::Dwarf:
emitAccelDebugNames();
break;
case AccelTableKind::None:
break;
case AccelTableKind::Default:
llvm_unreachable("Default should have already been resolved.");
}
emitDebugPubSections();
}
void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
const DINode *Node,
const MDNode *ScopeNode) {
if (CU.getExistingAbstractEntity(Node))
return;
CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
cast<DILocalScope>(ScopeNode)));
}
void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
const DINode *Node, const MDNode *ScopeNode) {
if (CU.getExistingAbstractEntity(Node))
return;
if (LexicalScope *Scope =
LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
CU.createAbstractEntity(Node, Scope);
}
void DwarfDebug::collectVariableInfoFromMFTable(
DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
if (!VI.Var)
continue;
assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
"Expected inlined-at fields to agree");
InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
Processed.insert(Var);
LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
if (!Scope) {
LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
<< ", no variable scope found\n");
continue;
}
ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
auto RegVar = std::make_unique<DbgVariable>(
cast<DILocalVariable>(Var.first), Var.second);
RegVar->initializeMMI(VI.Expr, VI.Slot);
LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
<< "\n");
if (DbgVariable *DbgVar = MFVars.lookup(Var))
DbgVar->addMMIEntry(*RegVar);
else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
MFVars.insert({Var, RegVar.get()});
ConcreteEntities.push_back(std::move(RegVar));
}
}
}
static bool validThroughout(LexicalScopes &LScopes,
const MachineInstr *DbgValue,
const MachineInstr *RangeEnd,
const InstructionOrdering &Ordering) {
assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
auto MBB = DbgValue->getParent();
auto DL = DbgValue->getDebugLoc();
auto *LScope = LScopes.findLexicalScope(DL);
if (!LScope)
return false;
auto &LSRange = LScope->getRanges();
if (LSRange.size() == 0)
return false;
const MachineInstr *LScopeBegin = LSRange.front().first;
if (!Ordering.isBefore(DbgValue, LScopeBegin)) {
if (LScopeBegin->getParent() != MBB)
return false;
MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
for (++Pred; Pred != MBB->rend(); ++Pred) {
if (Pred->getFlag(MachineInstr::FrameSetup))
break;
auto PredDL = Pred->getDebugLoc();
if (!PredDL || Pred->isMetaInstruction())
continue;
if (DL->getScope() == PredDL->getScope())
return false;
auto *PredScope = LScopes.findLexicalScope(PredDL);
if (!PredScope || LScope->dominates(PredScope))
return false;
}
}
if (!RangeEnd)
return true;
if (MBB->pred_empty() &&
all_of(DbgValue->debug_operands(),
[](const MachineOperand &Op) { return Op.isImm(); }))
return true;
const MachineInstr *LScopeEnd = LSRange.back().second;
if (Ordering.isBefore(RangeEnd, LScopeEnd))
return false;
return true;
}
bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
const DbgValueHistoryMap::Entries &Entries) {
using OpenRange =
std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
SmallVector<OpenRange, 4> OpenRanges;
bool isSafeForSingleLocation = true;
const MachineInstr *StartDebugMI = nullptr;
const MachineInstr *EndMI = nullptr;
for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
const MachineInstr *Instr = EI->getInstr();
size_t Index = std::distance(EB, EI);
erase_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
const MCSymbol *StartLabel =
EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
assert(StartLabel &&
"Forgot label before/after instruction starting a range!");
const MCSymbol *EndLabel;
if (std::next(EI) == Entries.end()) {
const MachineBasicBlock &EndMBB = Asm->MF->back();
EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionIDNum()].EndLabel;
if (EI->isClobber())
EndMI = EI->getInstr();
}
else if (std::next(EI)->isClobber())
EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
else
EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
assert(EndLabel && "Forgot label after instruction ending a range!");
if (EI->isDbgValue())
LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
if (EI->isDbgValue()) {
if (!Instr->isUndefDebugValue()) {
auto Value = getDebugLocValue(Instr);
OpenRanges.emplace_back(EI->getEndIndex(), Value);
if (Instr->getDebugExpression()->isFragment())
isSafeForSingleLocation = false;
if (!StartDebugMI)
StartDebugMI = Instr;
} else {
isSafeForSingleLocation = false;
}
}
if (OpenRanges.empty())
continue;
if (StartLabel == EndLabel) {
LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
continue;
}
SmallVector<DbgValueLoc, 4> Values;
for (auto &R : OpenRanges)
Values.push_back(R.second);
if (Asm->MF->hasBBSections() && StartLabel == Asm->getFunctionBegin() &&
!Instr->getParent()->sameSection(&Asm->MF->front())) {
const MCSymbol *BeginSectionLabel = StartLabel;
for (const MachineBasicBlock &MBB : *Asm->MF) {
if (MBB.isBeginSection() && &MBB != &Asm->MF->front())
BeginSectionLabel = MBB.getSymbol();
if (MBB.sameSection(Instr->getParent())) {
DebugLoc.emplace_back(BeginSectionLabel, EndLabel, Values);
break;
}
if (MBB.isEndSection())
DebugLoc.emplace_back(BeginSectionLabel, MBB.getEndSymbol(), Values);
}
} else {
DebugLoc.emplace_back(StartLabel, EndLabel, Values);
}
auto CurEntry = DebugLoc.rbegin();
LLVM_DEBUG({
dbgs() << CurEntry->getValues().size() << " Values:\n";
for (auto &Value : CurEntry->getValues())
Value.dump();
dbgs() << "-----\n";
});
auto PrevEntry = std::next(CurEntry);
if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
DebugLoc.pop_back();
}
if (!isSafeForSingleLocation ||
!validThroughout(LScopes, StartDebugMI, EndMI, getInstOrdering()))
return false;
if (DebugLoc.size() == 1)
return true;
if (!Asm->MF->hasBBSections())
return false;
const MachineBasicBlock *RangeMBB = nullptr;
if (DebugLoc[0].getBeginSym() == Asm->getFunctionBegin())
RangeMBB = &Asm->MF->front();
else
RangeMBB = Entries.begin()->getInstr()->getParent();
auto *CurEntry = DebugLoc.begin();
auto *NextEntry = std::next(CurEntry);
while (NextEntry != DebugLoc.end()) {
while (!RangeMBB->isEndSection())
RangeMBB = RangeMBB->getNextNode();
if (!RangeMBB->getNextNode())
return false;
if (CurEntry->getEndSym() != RangeMBB->getEndSymbol() ||
NextEntry->getBeginSym() != RangeMBB->getNextNode()->getSymbol() ||
CurEntry->getValues() != NextEntry->getValues())
return false;
RangeMBB = RangeMBB->getNextNode();
CurEntry = NextEntry;
NextEntry = std::next(CurEntry);
}
return true;
}
DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
LexicalScope &Scope,
const DINode *Node,
const DILocation *Location,
const MCSymbol *Sym) {
ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
if (isa<const DILocalVariable>(Node)) {
ConcreteEntities.push_back(
std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
Location));
InfoHolder.addScopeVariable(&Scope,
cast<DbgVariable>(ConcreteEntities.back().get()));
} else if (isa<const DILabel>(Node)) {
ConcreteEntities.push_back(
std::make_unique<DbgLabel>(cast<const DILabel>(Node),
Location, Sym));
InfoHolder.addScopeLabel(&Scope,
cast<DbgLabel>(ConcreteEntities.back().get()));
}
return ConcreteEntities.back().get();
}
void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
const DISubprogram *SP,
DenseSet<InlinedEntity> &Processed) {
collectVariableInfoFromMFTable(TheCU, Processed);
for (const auto &I : DbgValues) {
InlinedEntity IV = I.first;
if (Processed.count(IV))
continue;
const auto &HistoryMapEntries = I.second;
if (!DbgValues.hasNonEmptyLocation(HistoryMapEntries))
continue;
LexicalScope *Scope = nullptr;
const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
if (const DILocation *IA = IV.second)
Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
else
Scope = LScopes.findLexicalScope(LocalVar->getScope());
if (!Scope)
continue;
Processed.insert(IV);
DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
*Scope, LocalVar, IV.second));
const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
assert(MInsn->isDebugValue() && "History must begin with debug value");
size_t HistSize = HistoryMapEntries.size();
bool SingleValueWithClobber =
HistSize == 2 && HistoryMapEntries[1].isClobber();
if (HistSize == 1 || SingleValueWithClobber) {
const auto *End =
SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
if (validThroughout(LScopes, MInsn, End, getInstOrdering())) {
RegVar->initializeDbgValue(MInsn);
continue;
}
}
if (!useLocSection())
continue;
DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
SmallVector<DebugLocEntry, 8> Entries;
bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
if (isValidSingleLocation) {
RegVar->initializeDbgValue(Entries[0].getValues()[0]);
continue;
}
const DIBasicType *BT = dyn_cast<DIBasicType>(
static_cast<const Metadata *>(LocalVar->getType()));
for (auto &Entry : Entries)
Entry.finalize(*Asm, List, BT, TheCU);
}
for (const auto &I : DbgLabels) {
InlinedEntity IL = I.first;
const MachineInstr *MI = I.second;
if (MI == nullptr)
continue;
LexicalScope *Scope = nullptr;
const DILabel *Label = cast<DILabel>(IL.first);
const DILocalScope *LocalScope =
Label->getScope()->getNonLexicalBlockFileScope();
if (const DILocation *IA = IL.second)
Scope = LScopes.findInlinedScope(LocalScope, IA);
else
Scope = LScopes.findLexicalScope(LocalScope);
if (!Scope)
continue;
Processed.insert(IL);
MCSymbol *Sym = getLabelBeforeInsn(MI);
createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
}
for (const DINode *DN : SP->getRetainedNodes()) {
if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
continue;
LexicalScope *Scope = nullptr;
if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
Scope = LScopes.findLexicalScope(DV->getScope());
} else if (auto *DL = dyn_cast<DILabel>(DN)) {
Scope = LScopes.findLexicalScope(DL->getScope());
}
if (Scope)
createConcreteEntity(TheCU, *Scope, DN, nullptr);
}
}
void DwarfDebug::beginInstruction(const MachineInstr *MI) {
const MachineFunction &MF = *MI->getMF();
const auto *SP = MF.getFunction().getSubprogram();
bool NoDebug =
!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
auto delaySlotSupported = [](const MachineInstr &MI) {
if (!MI.isBundledWithSucc())
return false;
auto Suc = std::next(MI.getIterator());
(void)Suc;
assert(Suc->isBundledWithPred() &&
"Call bundle instructions are out of order");
return true;
};
if (!NoDebug && SP->areAllCallsDescribed() &&
MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) &&
(!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
bool IsTail = TII->isTailCall(*MI);
if (IsTail)
requestLabelBeforeInsn(MI);
requestLabelAfterInsn(MI);
}
DebugHandlerBase::beginInstruction(MI);
if (!CurMI)
return;
if (NoDebug)
return;
if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
return;
const DebugLoc &DL = MI->getDebugLoc();
unsigned LastAsmLine =
Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
if (DL == PrevInstLoc) {
if (!DL)
return;
if (LastAsmLine == 0 && DL.getLine() != 0) {
const MDNode *Scope = DL.getScope();
recordSourceLine(DL.getLine(), DL.getCol(), Scope, 0);
}
return;
}
if (!DL) {
if (LastAsmLine == 0)
return;
if (UnknownLocations == Disable)
return;
if (UnknownLocations == Enable || PrevLabel ||
(PrevInstBB && PrevInstBB != MI->getParent())) {
const MDNode *Scope = nullptr;
unsigned Column = 0;
if (PrevInstLoc) {
Scope = PrevInstLoc.getScope();
Column = PrevInstLoc.getCol();
}
recordSourceLine(0, Column, Scope, 0);
}
return;
}
if (DL.getLine() == 0 && LastAsmLine == 0)
return;
unsigned Flags = 0;
if (DL == PrologEndLoc) {
Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
PrologEndLoc = DebugLoc();
}
unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
if (DL.getLine() && DL.getLine() != OldLine)
Flags |= DWARF2_FLAG_IS_STMT;
const MDNode *Scope = DL.getScope();
recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
if (DL.getLine())
PrevInstLoc = DL;
}
static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
DebugLoc LineZeroLoc;
for (const auto &MBB : *MF) {
for (const auto &MI : MBB) {
if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
MI.getDebugLoc()) {
if (MI.getDebugLoc().getLine())
return MI.getDebugLoc();
LineZeroLoc = MI.getDebugLoc();
}
}
}
return LineZeroLoc;
}
static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
const MDNode *S, unsigned Flags, unsigned CUID,
uint16_t DwarfVersion,
ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
StringRef Fn;
unsigned FileNo = 1;
unsigned Discriminator = 0;
if (auto *Scope = cast_or_null<DIScope>(S)) {
Fn = Scope->getFilename();
if (Line != 0 && DwarfVersion >= 4)
if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
Discriminator = LBF->getDiscriminator();
FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
.getOrCreateSourceID(Scope->getFile());
}
Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
Discriminator, Fn);
}
DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
unsigned CUID) {
if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
(void)getOrCreateDwarfCompileUnit(
MF.getFunction().getSubprogram()->getUnit());
const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
CUID, getDwarfVersion(), getUnits());
return PrologEndLoc;
}
return DebugLoc();
}
void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
CurFn = MF;
auto *SP = MF->getFunction().getSubprogram();
assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
return;
DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
Asm->OutStreamer->getContext().setDwarfCompileUnitID(
getDwarfCompileUnitIDForLineTable(CU));
PrologEndLoc = emitInitialLocDirective(
*MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
}
unsigned
DwarfDebug::getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU) {
if (Asm->OutStreamer->hasRawTextSupport())
return 0;
else
return CU.getUniqueID();
}
void DwarfDebug::terminateLineTable(const DwarfCompileUnit *CU) {
const auto &CURanges = CU->getRanges();
auto &LineTable = Asm->OutStreamer->getContext().getMCDwarfLineTable(
getDwarfCompileUnitIDForLineTable(*CU));
LineTable.getMCLineSections().addEndEntry(
const_cast<MCSymbol *>(CURanges.back().End));
}
void DwarfDebug::skippedNonDebugFunction() {
if (PrevCU)
terminateLineTable(PrevCU);
PrevCU = nullptr;
CurFn = nullptr;
}
void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
const DISubprogram *SP = MF->getFunction().getSubprogram();
assert(CurFn == MF &&
"endFunction should be called with the same function as beginFunction");
Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
assert(!FnScope || SP == FnScope->getScopeNode());
DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
PrevLabel = nullptr;
CurFn = nullptr;
return;
}
DenseSet<InlinedEntity> Processed;
collectEntityInfo(TheCU, SP, Processed);
for (const auto &R : Asm->MBBSectionRanges)
TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});
if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
LScopes.getAbstractScopesList().empty() && !IsDarwin) {
assert(InfoHolder.getScopeVariables().empty());
PrevLabel = nullptr;
CurFn = nullptr;
return;
}
#ifndef NDEBUG
size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
#endif
for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
const auto *SP = cast<DISubprogram>(AScope->getScopeNode());
for (const DINode *DN : SP->getRetainedNodes()) {
if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
continue;
const MDNode *Scope = nullptr;
if (auto *DV = dyn_cast<DILocalVariable>(DN))
Scope = DV->getScope();
else if (auto *DL = dyn_cast<DILabel>(DN))
Scope = DL->getScope();
else
llvm_unreachable("Unexpected DI type!");
ensureAbstractEntityIsCreated(TheCU, DN, Scope);
assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
&& "ensureAbstractEntityIsCreated inserted abstract scopes");
}
constructAbstractSubprogramScopeDIE(TheCU, AScope);
}
ProcessedSPNodes.insert(SP);
DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
if (auto *SkelCU = TheCU.getSkeleton())
if (!LScopes.getAbstractScopesList().empty() &&
TheCU.getCUNode()->getSplitDebugInlining())
SkelCU->constructSubprogramScopeDIE(SP, FnScope);
constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
InfoHolder.getScopeVariables().clear();
InfoHolder.getScopeLabels().clear();
PrevLabel = nullptr;
CurFn = nullptr;
}
void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
unsigned Flags) {
::recordSourceLine(*Asm, Line, Col, S, Flags,
Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
getDwarfVersion(), getUnits());
}
void DwarfDebug::emitDebugInfo() {
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Holder.emitUnits( false);
}
void DwarfDebug::emitAbbreviations() {
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
}
void DwarfDebug::emitStringOffsetsTableHeader() {
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Holder.getStringPool().emitStringOffsetsTableHeader(
*Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
Holder.getStringOffsetsStartSym());
}
template <typename AccelTableT>
void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
StringRef TableName) {
Asm->OutStreamer->switchSection(Section);
emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
}
void DwarfDebug::emitAccelDebugNames() {
if (getUnits().empty())
return;
emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
}
void DwarfDebug::emitAccelNames() {
emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
"Names");
}
void DwarfDebug::emitAccelObjC() {
emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
"ObjC");
}
void DwarfDebug::emitAccelNamespaces() {
emitAccel(AccelNamespace,
Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
"namespac");
}
void DwarfDebug::emitAccelTypes() {
emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
"types");
}
static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
const DIE *Die) {
if (Die->getTag() == dwarf::DW_TAG_compile_unit)
return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
dwarf::GIEL_EXTERNAL);
dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
if (SpecDIE.findAttribute(dwarf::DW_AT_external))
Linkage = dwarf::GIEL_EXTERNAL;
} else if (Die->findAttribute(dwarf::DW_AT_external))
Linkage = dwarf::GIEL_EXTERNAL;
switch (Die->getTag()) {
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_union_type:
case dwarf::DW_TAG_enumeration_type:
return dwarf::PubIndexEntryDescriptor(
dwarf::GIEK_TYPE,
dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
? dwarf::GIEL_EXTERNAL
: dwarf::GIEL_STATIC);
case dwarf::DW_TAG_typedef:
case dwarf::DW_TAG_base_type:
case dwarf::DW_TAG_subrange_type:
return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
case dwarf::DW_TAG_namespace:
return dwarf::GIEK_TYPE;
case dwarf::DW_TAG_subprogram:
return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
case dwarf::DW_TAG_variable:
return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
case dwarf::DW_TAG_enumerator:
return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
dwarf::GIEL_STATIC);
default:
return dwarf::GIEK_NONE;
}
}
void DwarfDebug::emitDebugPubSections() {
for (const auto &NU : CUMap) {
DwarfCompileUnit *TheU = NU.second;
if (!TheU->hasDwarfPubSections())
continue;
bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
DICompileUnit::DebugNameTableKind::GNU;
Asm->OutStreamer->switchSection(
GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
: Asm->getObjFileLowering().getDwarfPubNamesSection());
emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
Asm->OutStreamer->switchSection(
GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
: Asm->getObjFileLowering().getDwarfPubTypesSection());
emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
}
}
void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
if (useSectionsAsReferences())
Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
CU.getDebugSectionOffset());
else
Asm->emitDwarfSymbolReference(CU.getLabelBegin());
}
void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
DwarfCompileUnit *TheU,
const StringMap<const DIE *> &Globals) {
if (auto *Skeleton = TheU->getSkeleton())
TheU = Skeleton;
MCSymbol *EndLabel = Asm->emitDwarfUnitLength(
"pub" + Name, "Length of Public " + Name + " Info");
Asm->OutStreamer->AddComment("DWARF Version");
Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
emitSectionReference(*TheU);
Asm->OutStreamer->AddComment("Compilation Unit Length");
Asm->emitDwarfLengthOrOffset(TheU->getLength());
for (const auto &GI : Globals) {
const char *Name = GI.getKeyData();
const DIE *Entity = GI.second;
Asm->OutStreamer->AddComment("DIE offset");
Asm->emitDwarfLengthOrOffset(Entity->getOffset());
if (GnuStyle) {
dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
Asm->OutStreamer->AddComment(
Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
Asm->emitInt8(Desc.toBits());
}
Asm->OutStreamer->AddComment("External Name");
Asm->OutStreamer->emitBytes(StringRef(Name, GI.getKeyLength() + 1));
}
Asm->OutStreamer->AddComment("End Mark");
Asm->emitDwarfLengthOrOffset(0);
Asm->OutStreamer->emitLabel(EndLabel);
}
void DwarfDebug::emitDebugStr() {
MCSection *StringOffsetsSection = nullptr;
if (useSegmentedStringOffsetsTable()) {
emitStringOffsetsTableHeader();
StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
}
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
StringOffsetsSection, true);
}
void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
const DebugLocStream::Entry &Entry,
const DwarfCompileUnit *CU) {
auto &&Comments = DebugLocs.getComments(Entry);
auto Comment = Comments.begin();
auto End = Comments.end();
unsigned PtrSize = Asm->MAI->getCodePointerSize();
DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
DebugLocs.getBytes(Entry).size()),
Asm->getDataLayout().isLittleEndian(), PtrSize);
DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());
using Encoding = DWARFExpression::Operation::Encoding;
uint64_t Offset = 0;
for (const auto &Op : Expr) {
assert(Op.getCode() != dwarf::DW_OP_const_type &&
"3 operand ops not yet supported");
Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
Offset++;
for (unsigned I = 0; I < 2; ++I) {
if (Op.getDescription().Op[I] == Encoding::SizeNA)
continue;
if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
unsigned Length =
Streamer.emitDIERef(*CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die);
for (unsigned J = 0; J < Length; ++J)
if (Comment != End)
Comment++;
} else {
for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
}
Offset = Op.getOperandEndOffset(I);
}
assert(Offset == Op.getEndOffset());
}
}
void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
const DbgValueLoc &Value,
DwarfExpression &DwarfExpr) {
auto *DIExpr = Value.getExpression();
DIExpressionCursor ExprCursor(DIExpr);
DwarfExpr.addFragmentOffset(DIExpr);
if (DIExpr && DIExpr->isEntryValue()) {
assert(Value.getLocEntries().size() == 1);
assert(Value.getLocEntries()[0].isLocation());
MachineLocation Location = Value.getLocEntries()[0].getLoc();
DwarfExpr.setLocation(Location, DIExpr);
DwarfExpr.beginEntryValueExpression(ExprCursor);
const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
if (!DwarfExpr.addMachineRegExpression(TRI, ExprCursor, Location.getReg()))
return;
return DwarfExpr.addExpression(std::move(ExprCursor));
}
auto EmitValueLocEntry = [&DwarfExpr, &BT,
&AP](const DbgValueLocEntry &Entry,
DIExpressionCursor &Cursor) -> bool {
if (Entry.isInt()) {
if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
BT->getEncoding() == dwarf::DW_ATE_signed_char))
DwarfExpr.addSignedConstant(Entry.getInt());
else
DwarfExpr.addUnsignedConstant(Entry.getInt());
} else if (Entry.isLocation()) {
MachineLocation Location = Entry.getLoc();
if (Location.isIndirect())
DwarfExpr.setMemoryLocationKind();
const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
return false;
} else if (Entry.isTargetIndexLocation()) {
TargetIndexLocation Loc = Entry.getTargetIndexLocation();
assert(AP.TM.getTargetTriple().isWasm());
DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
} else if (Entry.isConstantFP()) {
if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&
!Cursor) {
DwarfExpr.addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);
} else if (Entry.getConstantFP()
->getValueAPF()
.bitcastToAPInt()
.getBitWidth() <= 64 ) {
DwarfExpr.addUnsignedConstant(
Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
} else {
LLVM_DEBUG(
dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
<< Entry.getConstantFP()
->getValueAPF()
.bitcastToAPInt()
.getBitWidth()
<< " bits\n");
return false;
}
}
return true;
};
if (!Value.isVariadic()) {
if (!EmitValueLocEntry(Value.getLocEntries()[0], ExprCursor))
return;
DwarfExpr.addExpression(std::move(ExprCursor));
return;
}
if (any_of(Value.getLocEntries(), [](const DbgValueLocEntry &Entry) {
return Entry.isLocation() && !Entry.getLoc().getReg();
}))
return;
DwarfExpr.addExpression(
std::move(ExprCursor),
[EmitValueLocEntry, &Value](unsigned Idx,
DIExpressionCursor &Cursor) -> bool {
return EmitValueLocEntry(Value.getLocEntries()[Idx], Cursor);
});
}
void DebugLocEntry::finalize(const AsmPrinter &AP,
DebugLocStream::ListBuilder &List,
const DIBasicType *BT,
DwarfCompileUnit &TheCU) {
assert(!Values.empty() &&
"location list entries without values are redundant");
assert(Begin != End && "unexpected location list entry with empty range");
DebugLocStream::EntryBuilder Entry(List, Begin, End);
BufferByteStreamer Streamer = Entry.getStreamer();
DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
const DbgValueLoc &Value = Values[0];
if (Value.isFragment()) {
assert(llvm::all_of(Values, [](DbgValueLoc P) {
return P.isFragment();
}) && "all values are expected to be fragments");
assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
for (const auto &Fragment : Values)
DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
} else {
assert(Values.size() == 1 && "only fragments may have >1 value");
DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
}
DwarfExpr.finalize();
if (DwarfExpr.TagOffset)
List.setTagOffset(*DwarfExpr.TagOffset);
}
void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
const DwarfCompileUnit *CU) {
Asm->OutStreamer->AddComment("Loc expr size");
if (getDwarfVersion() >= 5)
Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
Asm->emitInt16(DebugLocs.getBytes(Entry).size());
else {
Asm->emitInt16(0);
return;
}
APByteStreamer Streamer(*Asm);
emitDebugLocEntry(Streamer, Entry, CU);
}
static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
const DwarfFile &Holder) {
MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
Asm->OutStreamer->AddComment("Offset entry count");
Asm->emitInt32(Holder.getRangeLists().size());
Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
for (const RangeSpanList &List : Holder.getRangeLists())
Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
Asm->getDwarfOffsetByteSize());
return TableEnd;
}
static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
const DwarfDebug &DD) {
MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
const auto &DebugLocs = DD.getDebugLocs();
Asm->OutStreamer->AddComment("Offset entry count");
Asm->emitInt32(DebugLocs.getLists().size());
Asm->OutStreamer->emitLabel(DebugLocs.getSym());
for (const auto &List : DebugLocs.getLists())
Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),
Asm->getDwarfOffsetByteSize());
return TableEnd;
}
template <typename Ranges, typename PayloadEmitter>
static void emitRangeList(
DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
unsigned StartxLength, unsigned EndOfList,
StringRef (*StringifyEnum)(unsigned),
bool ShouldUseBaseAddress,
PayloadEmitter EmitPayload) {
auto Size = Asm->MAI->getCodePointerSize();
bool UseDwarf5 = DD.getDwarfVersion() >= 5;
Asm->OutStreamer->emitLabel(Sym);
MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
for (const auto &Range : R)
SectionRanges[&Range.Begin->getSection()].push_back(&Range);
const MCSymbol *CUBase = CU.getBaseAddress();
bool BaseIsSet = false;
for (const auto &P : SectionRanges) {
auto *Base = CUBase;
if (!Base && ShouldUseBaseAddress) {
const MCSymbol *Begin = P.second.front()->Begin;
const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
if (!UseDwarf5) {
Base = NewBase;
BaseIsSet = true;
Asm->OutStreamer->emitIntValue(-1, Size);
Asm->OutStreamer->AddComment(" base address");
Asm->OutStreamer->emitSymbolValue(Base, Size);
} else if (NewBase != Begin || P.second.size() > 1) {
Base = NewBase;
BaseIsSet = true;
Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
Asm->emitInt8(BaseAddressx);
Asm->OutStreamer->AddComment(" base address index");
Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
}
} else if (BaseIsSet && !UseDwarf5) {
BaseIsSet = false;
assert(!Base);
Asm->OutStreamer->emitIntValue(-1, Size);
Asm->OutStreamer->emitIntValue(0, Size);
}
for (const auto *RS : P.second) {
const MCSymbol *Begin = RS->Begin;
const MCSymbol *End = RS->End;
assert(Begin && "Range without a begin symbol?");
assert(End && "Range without an end symbol?");
if (Base) {
if (UseDwarf5) {
Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
Asm->emitInt8(OffsetPair);
Asm->OutStreamer->AddComment(" starting offset");
Asm->emitLabelDifferenceAsULEB128(Begin, Base);
Asm->OutStreamer->AddComment(" ending offset");
Asm->emitLabelDifferenceAsULEB128(End, Base);
} else {
Asm->emitLabelDifference(Begin, Base, Size);
Asm->emitLabelDifference(End, Base, Size);
}
} else if (UseDwarf5) {
Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
Asm->emitInt8(StartxLength);
Asm->OutStreamer->AddComment(" start index");
Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
Asm->OutStreamer->AddComment(" length");
Asm->emitLabelDifferenceAsULEB128(End, Begin);
} else {
Asm->OutStreamer->emitSymbolValue(Begin, Size);
Asm->OutStreamer->emitSymbolValue(End, Size);
}
EmitPayload(*RS);
}
}
if (UseDwarf5) {
Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
Asm->emitInt8(EndOfList);
} else {
Asm->OutStreamer->emitIntValue(0, Size);
Asm->OutStreamer->emitIntValue(0, Size);
}
}
static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
*List.CU, dwarf::DW_LLE_base_addressx,
dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
true,
[&](const DebugLocStream::Entry &E) {
DD.emitDebugLocEntryLocation(E, List.CU);
});
}
void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
if (DebugLocs.getLists().empty())
return;
Asm->OutStreamer->switchSection(Sec);
MCSymbol *TableEnd = nullptr;
if (getDwarfVersion() >= 5)
TableEnd = emitLoclistsTableHeader(Asm, *this);
for (const auto &List : DebugLocs.getLists())
emitLocList(*this, Asm, List);
if (TableEnd)
Asm->OutStreamer->emitLabel(TableEnd);
}
void DwarfDebug::emitDebugLoc() {
emitDebugLocImpl(
getDwarfVersion() >= 5
? Asm->getObjFileLowering().getDwarfLoclistsSection()
: Asm->getObjFileLowering().getDwarfLocSection());
}
void DwarfDebug::emitDebugLocDWO() {
if (getDwarfVersion() >= 5) {
emitDebugLocImpl(
Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
return;
}
for (const auto &List : DebugLocs.getLists()) {
Asm->OutStreamer->switchSection(
Asm->getObjFileLowering().getDwarfLocDWOSection());
Asm->OutStreamer->emitLabel(List.Label);
for (const auto &Entry : DebugLocs.getEntries(List)) {
Asm->emitInt8(dwarf::DW_LLE_startx_length);
unsigned idx = AddrPool.getIndex(Entry.Begin);
Asm->emitULEB128(idx);
Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
emitDebugLocEntryLocation(Entry, List.CU);
}
Asm->emitInt8(dwarf::DW_LLE_end_of_list);
}
}
struct ArangeSpan {
const MCSymbol *Start, *End;
};
void DwarfDebug::emitDebugARanges() {
MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
for (const SymbolCU &SCU : ArangeLabels) {
if (SCU.Sym->isInSection()) {
MCSection *Section = &SCU.Sym->getSection();
if (!Section->getKind().isMetadata())
SectionMap[Section].push_back(SCU);
} else {
SectionMap[nullptr].push_back(SCU);
}
}
DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
for (auto &I : SectionMap) {
MCSection *Section = I.first;
SmallVector<SymbolCU, 8> &List = I.second;
if (List.size() < 1)
continue;
if (!Section) {
for (const SymbolCU &Cur : List) {
ArangeSpan Span;
Span.Start = Cur.Sym;
Span.End = nullptr;
assert(Cur.CU);
Spans[Cur.CU].push_back(Span);
}
continue;
}
llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
unsigned IA = A.Sym ? Asm->OutStreamer->getSymbolOrder(A.Sym) : 0;
unsigned IB = B.Sym ? Asm->OutStreamer->getSymbolOrder(B.Sym) : 0;
if (IA == 0)
return false;
if (IB == 0)
return true;
return IA < IB;
});
List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
const MCSymbol *StartSym = List[0].Sym;
for (size_t n = 1, e = List.size(); n < e; n++) {
const SymbolCU &Prev = List[n - 1];
const SymbolCU &Cur = List[n];
if (Cur.CU != Prev.CU) {
ArangeSpan Span;
Span.Start = StartSym;
Span.End = Cur.Sym;
assert(Prev.CU);
Spans[Prev.CU].push_back(Span);
StartSym = Cur.Sym;
}
}
}
Asm->OutStreamer->switchSection(
Asm->getObjFileLowering().getDwarfARangesSection());
unsigned PtrSize = Asm->MAI->getCodePointerSize();
std::vector<DwarfCompileUnit *> CUs;
for (const auto &it : Spans) {
DwarfCompileUnit *CU = it.first;
CUs.push_back(CU);
}
llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
return A->getUniqueID() < B->getUniqueID();
});
for (DwarfCompileUnit *CU : CUs) {
std::vector<ArangeSpan> &List = Spans[CU];
if (auto *Skel = CU->getSkeleton())
CU = Skel;
unsigned ContentSize =
sizeof(int16_t) + Asm->getDwarfOffsetByteSize() + sizeof(int8_t) + sizeof(int8_t);
unsigned TupleSize = PtrSize * 2;
unsigned Padding = offsetToAlignment(
Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize));
ContentSize += Padding;
ContentSize += (List.size() + 1) * TupleSize;
Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set");
Asm->OutStreamer->AddComment("DWARF Arange version number");
Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
emitSectionReference(*CU);
Asm->OutStreamer->AddComment("Address Size (in bytes)");
Asm->emitInt8(PtrSize);
Asm->OutStreamer->AddComment("Segment Size (in bytes)");
Asm->emitInt8(0);
Asm->OutStreamer->emitFill(Padding, 0xff);
for (const ArangeSpan &Span : List) {
Asm->emitLabelReference(Span.Start, PtrSize);
auto SizeRef = SymSize.find(Span.Start);
if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
} else {
uint64_t Size;
if (SizeRef == SymSize.end() || SizeRef->second == 0)
Size = 1;
else
Size = SizeRef->second;
Asm->OutStreamer->emitIntValue(Size, PtrSize);
}
}
Asm->OutStreamer->AddComment("ARange terminator");
Asm->OutStreamer->emitIntValue(0, PtrSize);
Asm->OutStreamer->emitIntValue(0, PtrSize);
}
}
static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
const RangeSpanList &List) {
emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
llvm::dwarf::RangeListEncodingString,
List.CU->getCUNode()->getRangesBaseAddress() ||
DD.getDwarfVersion() >= 5,
[](auto) {});
}
void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
if (Holder.getRangeLists().empty())
return;
assert(useRangesSection());
assert(!CUMap.empty());
assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
return !Pair.second->getCUNode()->isDebugDirectivesOnly();
}));
Asm->OutStreamer->switchSection(Section);
MCSymbol *TableEnd = nullptr;
if (getDwarfVersion() >= 5)
TableEnd = emitRnglistsTableHeader(Asm, Holder);
for (const RangeSpanList &List : Holder.getRangeLists())
emitRangeList(*this, Asm, List);
if (TableEnd)
Asm->OutStreamer->emitLabel(TableEnd);
}
void DwarfDebug::emitDebugRanges() {
const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
emitDebugRangesImpl(Holder,
getDwarfVersion() >= 5
? Asm->getObjFileLowering().getDwarfRnglistsSection()
: Asm->getObjFileLowering().getDwarfRangesSection());
}
void DwarfDebug::emitDebugRangesDWO() {
emitDebugRangesImpl(InfoHolder,
Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
}
static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
enum HeaderFlagMask {
#define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
#include "llvm/BinaryFormat/Dwarf.def"
};
Asm->OutStreamer->AddComment("Macro information version");
Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
if (Asm->isDwarf64()) {
Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present");
Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
} else {
Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
}
Asm->OutStreamer->AddComment("debug_line_offset");
if (DD.useSplitDwarf())
Asm->emitDwarfLengthOrOffset(0);
else
Asm->emitDwarfSymbolReference(CU.getLineTableStartSym());
}
void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
for (auto *MN : Nodes) {
if (auto *M = dyn_cast<DIMacro>(MN))
emitMacro(*M);
else if (auto *F = dyn_cast<DIMacroFile>(MN))
emitMacroFile(*F, U);
else
llvm_unreachable("Unexpected DI type!");
}
}
void DwarfDebug::emitMacro(DIMacro &M) {
StringRef Name = M.getName();
StringRef Value = M.getValue();
std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
if (UseDebugMacroSection) {
if (getDwarfVersion() >= 5) {
unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
? dwarf::DW_MACRO_define_strx
: dwarf::DW_MACRO_undef_strx;
Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
Asm->emitULEB128(Type);
Asm->OutStreamer->AddComment("Line Number");
Asm->emitULEB128(M.getLine());
Asm->OutStreamer->AddComment("Macro String");
Asm->emitULEB128(
InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());
} else {
unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
? dwarf::DW_MACRO_GNU_define_indirect
: dwarf::DW_MACRO_GNU_undef_indirect;
Asm->OutStreamer->AddComment(dwarf::GnuMacroString(Type));
Asm->emitULEB128(Type);
Asm->OutStreamer->AddComment("Line Number");
Asm->emitULEB128(M.getLine());
Asm->OutStreamer->AddComment("Macro String");
Asm->emitDwarfSymbolReference(
InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol());
}
} else {
Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
Asm->emitULEB128(M.getMacinfoType());
Asm->OutStreamer->AddComment("Line Number");
Asm->emitULEB128(M.getLine());
Asm->OutStreamer->AddComment("Macro String");
Asm->OutStreamer->emitBytes(Str);
Asm->emitInt8('\0');
}
}
void DwarfDebug::emitMacroFileImpl(
DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
StringRef (*MacroFormToString)(unsigned Form)) {
Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
Asm->emitULEB128(StartFile);
Asm->OutStreamer->AddComment("Line Number");
Asm->emitULEB128(MF.getLine());
Asm->OutStreamer->AddComment("File Number");
DIFile &F = *MF.getFile();
if (useSplitDwarf())
Asm->emitULEB128(getDwoLineTable(U)->getFile(
F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),
Asm->OutContext.getDwarfVersion(), F.getSource()));
else
Asm->emitULEB128(U.getOrCreateSourceID(&F));
handleMacroNodes(MF.getElements(), U);
Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
Asm->emitULEB128(EndFile);
}
void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
if (UseDebugMacroSection)
emitMacroFileImpl(
F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
(getDwarfVersion() >= 5) ? dwarf::MacroString : dwarf::GnuMacroString);
else
emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
dwarf::DW_MACINFO_end_file, dwarf::MacinfoString);
}
void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
for (const auto &P : CUMap) {
auto &TheCU = *P.second;
auto *SkCU = TheCU.getSkeleton();
DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
auto *CUNode = cast<DICompileUnit>(P.first);
DIMacroNodeArray Macros = CUNode->getMacros();
if (Macros.empty())
continue;
Asm->OutStreamer->switchSection(Section);
Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
if (UseDebugMacroSection)
emitMacroHeader(Asm, *this, U, getDwarfVersion());
handleMacroNodes(Macros, U);
Asm->OutStreamer->AddComment("End Of Macro List Mark");
Asm->emitInt8(0);
}
}
void DwarfDebug::emitDebugMacinfo() {
auto &ObjLower = Asm->getObjFileLowering();
emitDebugMacinfoImpl(UseDebugMacroSection
? ObjLower.getDwarfMacroSection()
: ObjLower.getDwarfMacinfoSection());
}
void DwarfDebug::emitDebugMacinfoDWO() {
auto &ObjLower = Asm->getObjFileLowering();
emitDebugMacinfoImpl(UseDebugMacroSection
? ObjLower.getDwarfMacroDWOSection()
: ObjLower.getDwarfMacinfoDWOSection());
}
void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
std::unique_ptr<DwarfCompileUnit> NewU) {
if (!CompilationDir.empty())
NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
addGnuPubAttributes(*NewU, Die);
SkeletonHolder.addUnit(std::move(NewU));
}
DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
UnitKind::Skeleton);
DwarfCompileUnit &NewCU = *OwnedUnit;
NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
NewCU.initStmtList();
if (useSegmentedStringOffsetsTable())
NewCU.addStringOffsetsStart();
initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
return NewCU;
}
void DwarfDebug::emitDebugInfoDWO() {
assert(useSplitDwarf() && "No split dwarf debug info?");
InfoHolder.emitUnits( true);
}
void DwarfDebug::emitDebugAbbrevDWO() {
assert(useSplitDwarf() && "No split dwarf?");
InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
}
void DwarfDebug::emitDebugLineDWO() {
assert(useSplitDwarf() && "No split dwarf?");
SplitTypeUnitFileTable.Emit(
*Asm->OutStreamer, MCDwarfLineTableParams(),
Asm->getObjFileLowering().getDwarfLineDWOSection());
}
void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
assert(useSplitDwarf() && "No split dwarf?");
InfoHolder.getStringPool().emitStringOffsetsTableHeader(
*Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
InfoHolder.getStringOffsetsStartSym());
}
void DwarfDebug::emitDebugStrDWO() {
if (useSegmentedStringOffsetsTable())
emitStringOffsetsTableHeaderDWO();
assert(useSplitDwarf() && "No split dwarf?");
MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
OffSec, false);
}
void DwarfDebug::emitDebugAddr() {
AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
}
MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
if (!useSplitDwarf())
return nullptr;
const DICompileUnit *DIUnit = CU.getCUNode();
SplitTypeUnitFileTable.maybeSetRootFile(
DIUnit->getDirectory(), DIUnit->getFilename(),
getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
return &SplitTypeUnitFileTable;
}
uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
MD5 Hash;
Hash.update(Identifier);
MD5::MD5Result Result;
Hash.final(Result);
return Result.high();
}
void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
StringRef Identifier, DIE &RefDie,
const DICompositeType *CTy) {
if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
return;
auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
if (!Ins.second) {
CU.addDIETypeSignature(RefDie, Ins.first->second);
return;
}
bool TopLevelType = TypeUnitsUnderConstruction.empty();
AddrPool.resetUsedFlag();
auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
getDwoLineTable(CU));
DwarfTypeUnit &NewTU = *OwnedUnit;
DIE &UnitDie = NewTU.getUnitDie();
TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
CU.getLanguage());
uint64_t Signature = makeTypeSignature(Identifier);
NewTU.setTypeSignature(Signature);
Ins.first->second = Signature;
if (useSplitDwarf()) {
MCSection *Section =
getDwarfVersion() <= 4
? Asm->getObjFileLowering().getDwarfTypesDWOSection()
: Asm->getObjFileLowering().getDwarfInfoDWOSection();
NewTU.setSection(Section);
} else {
MCSection *Section =
getDwarfVersion() <= 4
? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
: Asm->getObjFileLowering().getDwarfInfoSection(Signature);
NewTU.setSection(Section);
CU.applyStmtList(UnitDie);
}
if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
NewTU.addStringOffsetsStart();
NewTU.setType(NewTU.createTypeDIE(CTy));
if (TopLevelType) {
auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
TypeUnitsUnderConstruction.clear();
if (AddrPool.hasBeenUsed()) {
for (const auto &TU : TypeUnitsToAdd)
TypeSignatures.erase(TU.second);
CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
return;
}
for (auto &TU : TypeUnitsToAdd) {
InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
}
}
CU.addDIETypeSignature(RefDie, Signature);
}
template <typename DataT>
void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
AccelTable<DataT> &AppleAccel, StringRef Name,
const DIE &Die) {
if (getAccelTableKind() == AccelTableKind::None)
return;
if (getAccelTableKind() != AccelTableKind::Apple &&
CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
return;
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
switch (getAccelTableKind()) {
case AccelTableKind::Apple:
AppleAccel.addName(Ref, Die);
break;
case AccelTableKind::Dwarf:
AccelDebugNames.addName(Ref, Die);
break;
case AccelTableKind::Default:
llvm_unreachable("Default should have already been resolved.");
case AccelTableKind::None:
llvm_unreachable("None handled above");
}
}
void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
const DIE &Die) {
addAccelNameImpl(CU, AccelNames, Name, Die);
}
void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
const DIE &Die) {
if (getAccelTableKind() == AccelTableKind::Apple)
addAccelNameImpl(CU, AccelObjC, Name, Die);
}
void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
const DIE &Die) {
addAccelNameImpl(CU, AccelNamespace, Name, Die);
}
void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
const DIE &Die, char Flags) {
addAccelNameImpl(CU, AccelTypes, Name, Die);
}
uint16_t DwarfDebug::getDwarfVersion() const {
return Asm->OutStreamer->getContext().getDwarfVersion();
}
dwarf::Form DwarfDebug::getDwarfSectionOffsetForm() const {
if (Asm->getDwarfVersion() >= 4)
return dwarf::Form::DW_FORM_sec_offset;
assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&
"DWARF64 is not defined prior DWARFv3");
return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
: dwarf::Form::DW_FORM_data4;
}
const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
auto I = SectionLabels.find(S);
if (I == SectionLabels.end())
return nullptr;
return I->second;
}
void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
if (useSplitDwarf() || getDwarfVersion() >= 5)
AddrPool.getIndex(S);
}
Optional<MD5::MD5Result> DwarfDebug::getMD5AsBytes(const DIFile *File) const {
assert(File);
if (getDwarfVersion() < 5)
return None;
Optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
return None;
std::string ChecksumString = fromHex(Checksum->Value);
MD5::MD5Result CKMem;
std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.data());
return CKMem;
}