#include "DwarfCompileUnit.h"
#include "AddressPool.h"
#include "DwarfExpression.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/DIE.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCSymbolWasm.h"
#include "llvm/MC/MachineLocation.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include <iterator>
#include <string>
#include <utility>
using namespace llvm;
static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW) {
if (DW->getDwarfVersion() >= 5 && Kind == UnitKind::Skeleton)
return dwarf::DW_TAG_skeleton_unit;
return dwarf::DW_TAG_compile_unit;
}
DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
AsmPrinter *A, DwarfDebug *DW,
DwarfFile *DWU, UnitKind Kind)
: DwarfUnit(GetCompileUnitType(Kind, DW), Node, A, DW, DWU), UniqueID(UID) {
insertDIE(Node, &getUnitDie());
MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
}
void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
const MCSymbol *Label) {
if ((Skeleton || !DD->useSplitDwarf()) && Label)
DD->addArangeLabel(SymbolCU(this, Label));
if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
return addLocalLabelAddress(Die, Attribute, Label);
bool UseAddrOffsetFormOrExpressions =
DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
const MCSymbol *Base = nullptr;
if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
Base = DD->getSectionLabel(&Label->getSection());
if (!Base || Base == Label) {
unsigned idx = DD->getAddressPool().getIndex(Label);
addAttribute(Die, Attribute,
DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
: dwarf::DW_FORM_GNU_addr_index,
DIEInteger(idx));
return;
}
assert(DD->getDwarfVersion() >= 5 &&
"Addr+offset expressions are only valuable when using debug_addr (to "
"reduce relocations) available in DWARFv5 or higher");
if (DD->useAddrOffsetExpressions()) {
auto *Loc = new (DIEValueAllocator) DIEBlock();
addPoolOpAddress(*Loc, Label);
addBlock(Die, Attribute, dwarf::DW_FORM_exprloc, Loc);
} else
addAttribute(Die, Attribute, dwarf::DW_FORM_LLVM_addrx_offset,
new (DIEValueAllocator) DIEAddrOffset(
DD->getAddressPool().getIndex(Base), Label, Base));
}
void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
dwarf::Attribute Attribute,
const MCSymbol *Label) {
if (Label)
addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIELabel(Label));
else
addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIEInteger(0));
}
unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
if (!File)
return Asm->OutStreamer->emitDwarfFileDirective(0, "", "", None, None,
CUID);
if (LastFile != File) {
LastFile = File;
LastFileID = Asm->OutStreamer->emitDwarfFileDirective(
0, File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
File->getSource(), CUID);
}
return LastFileID;
}
DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
if (DIE *Die = getDIE(GV))
return Die;
assert(GV);
auto *GVContext = GV->getScope();
const DIType *GTy = GV->getType();
auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
: getOrCreateContextDIE(GVContext);
DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
DIScope *DeclContext;
if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
DeclContext = SDMDecl->getScope();
assert(SDMDecl->isStaticMember() && "Expected static member decl");
assert(GV->isDefinition());
DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
if (GTy != SDMDecl->getBaseType())
addType(*VariableDIE, GTy);
} else {
DeclContext = GV->getScope();
StringRef DisplayName = GV->getDisplayName();
if (!DisplayName.empty())
addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
if (GTy)
addType(*VariableDIE, GTy);
if (!GV->isLocalToUnit())
addFlag(*VariableDIE, dwarf::DW_AT_external);
addSourceLine(*VariableDIE, GV);
}
if (!GV->isDefinition())
addFlag(*VariableDIE, dwarf::DW_AT_declaration);
else
addGlobalName(GV->getName(), *VariableDIE, DeclContext);
addAnnotation(*VariableDIE, GV->getAnnotations());
if (uint32_t AlignInBytes = GV->getAlignInBytes())
addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
AlignInBytes);
if (MDTuple *TP = GV->getTemplateParams())
addTemplateParams(*VariableDIE, DINodeArray(TP));
addLocationAttribute(VariableDIE, GV, GlobalExprs);
return VariableDIE;
}
void DwarfCompileUnit::addLocationAttribute(
DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
bool addToAccelTable = false;
DIELoc *Loc = nullptr;
Optional<unsigned> NVPTXAddressSpace;
std::unique_ptr<DIEDwarfExpression> DwarfExpr;
for (const auto &GE : GlobalExprs) {
const GlobalVariable *Global = GE.Var;
const DIExpression *Expr = GE.Expr;
if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
addToAccelTable = true;
addConstantValue(
*VariableDIE,
DIExpression::SignedOrUnsignedConstant::UnsignedConstant ==
*Expr->isConstant(),
Expr->getElement(1));
break;
}
if (Global && Global->hasDLLImportStorageClass())
continue;
if (!Global && (!Expr || !Expr->isConstant()))
continue;
if (Global && Global->isThreadLocal() &&
!Asm->getObjFileLowering().supportDebugThreadLocalLocation())
continue;
if (!Loc) {
addToAccelTable = true;
Loc = new (DIEValueAllocator) DIELoc;
DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
}
if (Expr) {
unsigned LocalNVPTXAddressSpace;
if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
const DIExpression *NewExpr =
DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
if (NewExpr != Expr) {
Expr = NewExpr;
NVPTXAddressSpace = LocalNVPTXAddressSpace;
}
}
DwarfExpr->addFragmentOffset(Expr);
}
if (Global) {
const MCSymbol *Sym = Asm->getSymbol(Global);
auto GetPointerSizedFormAndOp = [this]() {
unsigned PointerSize = Asm->getDataLayout().getPointerSize();
assert((PointerSize == 4 || PointerSize == 8) &&
"Add support for other sizes if necessary");
struct FormAndOp {
dwarf::Form Form;
dwarf::LocationAtom Op;
};
return PointerSize == 4
? FormAndOp{dwarf::DW_FORM_data4, dwarf::DW_OP_const4u}
: FormAndOp{dwarf::DW_FORM_data8, dwarf::DW_OP_const8u};
};
if (Global->isThreadLocal()) {
if (Asm->TM.useEmulatedTLS()) {
} else {
if (!DD->useSplitDwarf()) {
auto FormAndOp = GetPointerSizedFormAndOp();
addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
addExpr(*Loc, FormAndOp.Form,
Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
} else {
addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
addUInt(*Loc, dwarf::DW_FORM_udata,
DD->getAddressPool().getIndex(Sym, true));
}
addUInt(*Loc, dwarf::DW_FORM_data1,
DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
: dwarf::DW_OP_form_tls_address);
}
} else if ((Asm->TM.getRelocationModel() == Reloc::RWPI ||
Asm->TM.getRelocationModel() == Reloc::ROPI_RWPI) &&
!Asm->getObjFileLowering()
.getKindForGlobal(Global, Asm->TM)
.isReadOnly()) {
auto FormAndOp = GetPointerSizedFormAndOp();
addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
addExpr(*Loc, FormAndOp.Form,
Asm->getObjFileLowering().getIndirectSymViaRWPI(Sym));
Register BaseReg = Asm->getObjFileLowering().getStaticBase();
BaseReg = Asm->TM.getMCRegisterInfo()->getDwarfRegNum(BaseReg, false);
addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + BaseReg);
addSInt(*Loc, dwarf::DW_FORM_sdata, 0);
addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
} else {
DD->addArangeLabel(SymbolCU(this, Sym));
addOpAddress(*Loc, Sym);
}
}
if (DwarfExpr->isUnknownLocation())
DwarfExpr->setMemoryLocationKind();
DwarfExpr->addExpression(Expr);
}
if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
const unsigned NVPTX_ADDR_global_space = 5;
addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
}
if (Loc)
addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
if (DD->useAllLinkageNames())
addLinkageName(*VariableDIE, GV->getLinkageName());
if (addToAccelTable) {
DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
DD->useAllLinkageNames())
DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
}
}
DIE *DwarfCompileUnit::getOrCreateCommonBlock(
const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
if (DIE *NDie = getDIE(CB))
return NDie;
DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
addString(NDie, dwarf::DW_AT_name, Name);
addGlobalName(Name, NDie, CB->getScope());
if (CB->getFile())
addSourceLine(NDie, CB->getLineNo(), CB->getFile());
if (DIGlobalVariable *V = CB->getDecl())
getCU().addLocationAttribute(&NDie, V, GlobalExprs);
return &NDie;
}
void DwarfCompileUnit::addRange(RangeSpan Range) {
DD->insertSectionLabel(Range.Begin);
auto *PrevCU = DD->getPrevCU();
bool SameAsPrevCU = this == PrevCU;
DD->setPrevCU(this);
if (CURanges.empty() || !SameAsPrevCU ||
(&CURanges.back().End->getSection() !=
&Range.End->getSection())) {
if (PrevCU)
DD->terminateLineTable(PrevCU);
CURanges.push_back(Range);
return;
}
CURanges.back().End = Range.End;
}
void DwarfCompileUnit::initStmtList() {
if (CUNode->isDebugDirectivesOnly())
return;
const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
if (DD->useSectionsAsReferences()) {
LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
} else {
LineTableStartSym =
Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
}
addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
TLOF.getDwarfLineSection()->getBeginSymbol());
}
void DwarfCompileUnit::applyStmtList(DIE &D) {
const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
addSectionLabel(D, dwarf::DW_AT_stmt_list, LineTableStartSym,
TLOF.getDwarfLineSection()->getBeginSymbol());
}
void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
const MCSymbol *End) {
assert(Begin && "Begin label should not be null!");
assert(End && "End label should not be null!");
assert(Begin->isDefined() && "Invalid starting label");
assert(End->isDefined() && "Invalid end label");
addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
if (DD->getDwarfVersion() < 4)
addLabelAddress(D, dwarf::DW_AT_high_pc, End);
else
addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
}
DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
SmallVector<RangeSpan, 2> BB_List;
for (const auto &R : Asm->MBBSectionRanges)
BB_List.push_back({R.second.BeginLabel, R.second.EndLabel});
attachRangesOrLowHighPC(*SPDie, BB_List);
if (DD->useAppleExtensionAttributes() &&
!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
*DD->getCurrentFunction()))
addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
if (!includeMinimalInlineScopes()) {
const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
TargetFrameLowering::DwarfFrameBase FrameBase =
TFI->getDwarfFrameBase(*Asm->MF);
switch (FrameBase.Kind) {
case TargetFrameLowering::DwarfFrameBase::Register: {
if (Register::isPhysicalRegister(FrameBase.Location.Reg)) {
MachineLocation Location(FrameBase.Location.Reg);
addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
}
break;
}
case TargetFrameLowering::DwarfFrameBase::CFA: {
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
break;
}
case TargetFrameLowering::DwarfFrameBase::WasmFrameBase: {
const unsigned TI_GLOBAL_RELOC = 3;
if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC) {
assert(FrameBase.Location.WasmLoc.Index == 0); auto SPSym = cast<MCSymbolWasm>(
Asm->GetExternalSymbolSymbol("__stack_pointer"));
SPSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
SPSym->setGlobalType(wasm::WasmGlobalType{
uint8_t(Asm->getSubtargetInfo().getTargetTriple().getArch() ==
Triple::wasm64
? wasm::WASM_TYPE_I64
: wasm::WASM_TYPE_I32),
true});
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location);
addSInt(*Loc, dwarf::DW_FORM_sdata, TI_GLOBAL_RELOC);
if (!isDwoUnit()) {
addLabel(*Loc, dwarf::DW_FORM_data4, SPSym);
} else {
addUInt(*Loc, dwarf::DW_FORM_data4, FrameBase.Location.WasmLoc.Index);
}
addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
} else {
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
DIExpressionCursor Cursor({});
DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind,
FrameBase.Location.WasmLoc.Index);
DwarfExpr.addExpression(std::move(Cursor));
addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize());
}
break;
}
}
}
DD->addSubprogramNames(*CUNode, SP, *SPDie);
return *SPDie;
}
void DwarfCompileUnit::constructScopeDIE(LexicalScope *Scope,
DIE &ParentScopeDIE) {
if (!Scope || !Scope->getScopeNode())
return;
auto *DS = Scope->getScopeNode();
assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
"Only handle inlined subprograms here, use "
"constructSubprogramScopeDIE for non-inlined "
"subprograms");
if (Scope->getParent() && isa<DISubprogram>(DS)) {
DIE *ScopeDIE = constructInlinedScopeDIE(Scope);
if (!ScopeDIE)
return;
ParentScopeDIE.addChild(ScopeDIE);
createAndAddScopeChildren(Scope, *ScopeDIE);
return;
}
if (DD->isLexicalScopeDIENull(Scope))
return;
DIE *ScopeDIE = constructLexicalScopeDIE(Scope);
assert(ScopeDIE && "Scope DIE should not be null.");
ParentScopeDIE.addChild(ScopeDIE);
createAndAddScopeChildren(Scope, *ScopeDIE);
}
void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
SmallVector<RangeSpan, 2> Range) {
HasRangeLists = true;
auto IndexAndList =
(DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
uint32_t Index = IndexAndList.first;
auto &List = *IndexAndList.second;
if (DD->getDwarfVersion() >= 5)
addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
else {
const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
const MCSymbol *RangeSectionSym =
TLOF.getDwarfRangesSection()->getBeginSymbol();
if (isDwoUnit())
addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
RangeSectionSym);
else
addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
RangeSectionSym);
}
}
void DwarfCompileUnit::attachRangesOrLowHighPC(
DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
assert(!Ranges.empty());
if (!DD->useRangesSection() ||
(Ranges.size() == 1 &&
(!DD->alwaysUseRanges() ||
DD->getSectionLabel(&Ranges.front().Begin->getSection()) ==
Ranges.front().Begin))) {
const RangeSpan &Front = Ranges.front();
const RangeSpan &Back = Ranges.back();
attachLowHighPC(Die, Front.Begin, Back.End);
} else
addScopeRangeList(Die, std::move(Ranges));
}
void DwarfCompileUnit::attachRangesOrLowHighPC(
DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
SmallVector<RangeSpan, 2> List;
List.reserve(Ranges.size());
for (const InsnRange &R : Ranges) {
auto *BeginLabel = DD->getLabelBeforeInsn(R.first);
auto *EndLabel = DD->getLabelAfterInsn(R.second);
const auto *BeginMBB = R.first->getParent();
const auto *EndMBB = R.second->getParent();
const auto *MBB = BeginMBB;
do {
if (MBB->sameSection(EndMBB) || MBB->isEndSection()) {
auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()];
List.push_back(
{MBB->sameSection(BeginMBB) ? BeginLabel
: MBBSectionRange.BeginLabel,
MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
}
if (MBB->sameSection(EndMBB))
break;
MBB = MBB->getNextNode();
} while (true);
}
attachRangesOrLowHighPC(Die, std::move(List));
}
DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
assert(Scope->getScopeNode());
auto *DS = Scope->getScopeNode();
auto *InlinedSP = getDISubprogram(DS);
DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
const DILocation *IA = Scope->getInlinedAt();
addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
getOrCreateSourceID(IA->getFile()));
addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
if (IA->getColumn())
addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
IA->getDiscriminator());
DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
return ScopeDIE;
}
DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
if (DD->isLexicalScopeDIENull(Scope))
return nullptr;
auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
if (Scope->isAbstractScope())
return ScopeDIE;
attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
return ScopeDIE;
}
DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
auto D = constructVariableDIEImpl(DV, Abstract);
DV.setDIE(*D);
return D;
}
DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
const LexicalScope &Scope) {
auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
insertDIE(DL.getLabel(), LabelDie);
DL.setDIE(*LabelDie);
if (Scope.isAbstractScope())
applyLabelAttributes(DL, *LabelDie);
return LabelDie;
}
DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
bool Abstract) {
auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
insertDIE(DV.getVariable(), VariableDie);
if (Abstract) {
applyVariableAttributes(DV, *VariableDie);
return VariableDie;
}
unsigned Index = DV.getDebugLocListIndex();
if (Index != ~0U) {
addLocationList(*VariableDie, dwarf::DW_AT_location, Index);
auto TagOffset = DV.getDebugLocListTagOffset();
if (TagOffset)
addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
*TagOffset);
return VariableDie;
}
if (auto *DVal = DV.getValueLoc()) {
if (!DVal->isVariadic()) {
const DbgValueLocEntry *Entry = DVal->getLocEntries().begin();
if (Entry->isLocation()) {
addVariableAddress(DV, *VariableDie, Entry->getLoc());
} else if (Entry->isInt()) {
auto *Expr = DV.getSingleExpression();
if (Expr && Expr->getNumElements()) {
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
DwarfExpr.addFragmentOffset(Expr);
DwarfExpr.addUnsignedConstant(Entry->getInt());
DwarfExpr.addExpression(Expr);
addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
if (DwarfExpr.TagOffset)
addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset,
dwarf::DW_FORM_data1, *DwarfExpr.TagOffset);
} else
addConstantValue(*VariableDie, Entry->getInt(), DV.getType());
} else if (Entry->isConstantFP()) {
addConstantFPValue(*VariableDie, Entry->getConstantFP());
} else if (Entry->isConstantInt()) {
addConstantValue(*VariableDie, Entry->getConstantInt(), DV.getType());
} else if (Entry->isTargetIndexLocation()) {
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
const DIBasicType *BT = dyn_cast<DIBasicType>(
static_cast<const Metadata *>(DV.getVariable()->getType()));
DwarfDebug::emitDebugLocValue(*Asm, BT, *DVal, DwarfExpr);
addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
}
return VariableDie;
}
if (any_of(DVal->getLocEntries(), [](const DbgValueLocEntry &Entry) {
return Entry.isLocation() && !Entry.getLoc().getReg();
}))
return VariableDie;
const DIExpression *Expr = DV.getSingleExpression();
assert(Expr && "Variadic Debug Value must have an Expression.");
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
DwarfExpr.addFragmentOffset(Expr);
DIExpressionCursor Cursor(Expr);
const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
auto AddEntry = [&](const DbgValueLocEntry &Entry,
DIExpressionCursor &Cursor) {
if (Entry.isLocation()) {
if (!DwarfExpr.addMachineRegExpression(TRI, Cursor,
Entry.getLoc().getReg()))
return false;
} else if (Entry.isInt()) {
DwarfExpr.addUnsignedConstant(Entry.getInt());
} else if (Entry.isConstantFP()) {
APInt RawBytes = Entry.getConstantFP()->getValueAPF().bitcastToAPInt();
if (RawBytes.getBitWidth() > 64)
return false;
DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
} else if (Entry.isConstantInt()) {
APInt RawBytes = Entry.getConstantInt()->getValue();
if (RawBytes.getBitWidth() > 64)
return false;
DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
} else if (Entry.isTargetIndexLocation()) {
TargetIndexLocation Loc = Entry.getTargetIndexLocation();
assert(Asm->TM.getTargetTriple().isWasm());
DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
} else {
llvm_unreachable("Unsupported Entry type.");
}
return true;
};
if (!DwarfExpr.addExpression(
std::move(Cursor),
[&](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
return AddEntry(DVal->getLocEntries()[Idx], Cursor);
}))
return VariableDie;
addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
if (DwarfExpr.TagOffset)
addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
*DwarfExpr.TagOffset);
return VariableDie;
}
if (!DV.hasFrameIndexExprs())
return VariableDie;
Optional<unsigned> NVPTXAddressSpace;
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
for (const auto &Fragment : DV.getFrameIndexExprs()) {
Register FrameReg;
const DIExpression *Expr = Fragment.Expr;
const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
StackOffset Offset =
TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
DwarfExpr.addFragmentOffset(Expr);
auto *TRI = Asm->MF->getSubtarget().getRegisterInfo();
SmallVector<uint64_t, 8> Ops;
TRI->getOffsetOpcodes(Offset, Ops);
unsigned LocalNVPTXAddressSpace;
if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
const DIExpression *NewExpr =
DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
if (NewExpr != Expr) {
Expr = NewExpr;
NVPTXAddressSpace = LocalNVPTXAddressSpace;
}
}
if (Expr)
Ops.append(Expr->elements_begin(), Expr->elements_end());
DIExpressionCursor Cursor(Ops);
DwarfExpr.setMemoryLocationKind();
if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
addOpAddress(*Loc, FrameSymbol);
else
DwarfExpr.addMachineRegExpression(
*Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
DwarfExpr.addExpression(std::move(Cursor));
}
if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
const unsigned NVPTX_ADDR_local_space = 6;
addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
}
addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
if (DwarfExpr.TagOffset)
addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
*DwarfExpr.TagOffset);
return VariableDie;
}
DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
const LexicalScope &Scope,
DIE *&ObjectPointer) {
auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
if (DV.isObjectPointer())
ObjectPointer = Var;
return Var;
}
static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
SmallVector<const DIVariable *, 2> Result;
auto *Array = dyn_cast<DICompositeType>(Var->getType());
if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
return Result;
if (auto *DLVar = Array->getDataLocation())
Result.push_back(DLVar);
if (auto *AsVar = Array->getAssociated())
Result.push_back(AsVar);
if (auto *AlVar = Array->getAllocated())
Result.push_back(AlVar);
for (auto *El : Array->getElements()) {
if (auto *Subrange = dyn_cast<DISubrange>(El)) {
if (auto Count = Subrange->getCount())
if (auto *Dependency = Count.dyn_cast<DIVariable *>())
Result.push_back(Dependency);
if (auto LB = Subrange->getLowerBound())
if (auto *Dependency = LB.dyn_cast<DIVariable *>())
Result.push_back(Dependency);
if (auto UB = Subrange->getUpperBound())
if (auto *Dependency = UB.dyn_cast<DIVariable *>())
Result.push_back(Dependency);
if (auto ST = Subrange->getStride())
if (auto *Dependency = ST.dyn_cast<DIVariable *>())
Result.push_back(Dependency);
} else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) {
if (auto Count = GenericSubrange->getCount())
if (auto *Dependency = Count.dyn_cast<DIVariable *>())
Result.push_back(Dependency);
if (auto LB = GenericSubrange->getLowerBound())
if (auto *Dependency = LB.dyn_cast<DIVariable *>())
Result.push_back(Dependency);
if (auto UB = GenericSubrange->getUpperBound())
if (auto *Dependency = UB.dyn_cast<DIVariable *>())
Result.push_back(Dependency);
if (auto ST = GenericSubrange->getStride())
if (auto *Dependency = ST.dyn_cast<DIVariable *>())
Result.push_back(Dependency);
}
}
return Result;
}
static SmallVector<DbgVariable *, 8>
sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
SmallVector<DbgVariable *, 8> Result;
SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
SmallDenseSet<DbgVariable *, 8> Visited;
SmallDenseSet<DbgVariable *, 8> Visiting;
for (auto *Var : reverse(Input)) {
DbgVar.insert({Var->getVariable(), Var});
WorkList.push_back({Var, 0});
}
while (!WorkList.empty()) {
auto Item = WorkList.back();
DbgVariable *Var = Item.getPointer();
bool visitedAllDependencies = Item.getInt();
WorkList.pop_back();
assert(Var);
if (Visited.count(Var))
continue;
if (visitedAllDependencies) {
Visited.insert(Var);
Result.push_back(Var);
continue;
}
auto Res = Visiting.insert(Var);
if (!Res.second) {
assert(false && "dependency cycle in local variables");
return Result;
}
WorkList.push_back({Var, 1});
for (const auto *Dependency : dependencies(Var)) {
if (const auto *Dep = dyn_cast<const DILocalVariable>(Dependency))
if (DbgVariable *Var = DbgVar.lookup(Dep))
WorkList.push_back({Var, 0});
}
}
return Result;
}
DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
LexicalScope *Scope) {
DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
if (Scope) {
assert(!Scope->getInlinedAt());
assert(!Scope->isAbstractScope());
if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
}
DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
!includeMinimalInlineScopes())
ScopeDIE.addChild(
DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
return ScopeDIE;
}
DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
DIE &ScopeDIE) {
DIE *ObjectPointer = nullptr;
auto Vars = DU->getScopeVariables().lookup(Scope);
for (auto &DV : Vars.Args)
ScopeDIE.addChild(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
auto Locals = sortLocalVars(Vars.Locals);
for (DbgVariable *DV : Locals)
ScopeDIE.addChild(constructVariableDIE(*DV, *Scope, ObjectPointer));
if (!includeMinimalInlineScopes()) {
for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
ScopeDIE.addChild(constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
}
for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
ScopeDIE.addChild(constructLabelDIE(*DL, *Scope));
auto needToEmitLexicalScope = [this](LexicalScope *LS) {
if (isa<DISubprogram>(LS->getScopeNode()))
return true;
auto Vars = DU->getScopeVariables().lookup(LS);
if (!Vars.Args.empty() || !Vars.Locals.empty())
return true;
if (!includeMinimalInlineScopes() &&
!ImportedEntities[LS->getScopeNode()].empty())
return true;
return false;
};
for (LexicalScope *LS : Scope->getChildren()) {
if (needToEmitLexicalScope(LS))
constructScopeDIE(LS, ScopeDIE);
else
createAndAddScopeChildren(LS, ScopeDIE);
}
return ObjectPointer;
}
void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
LexicalScope *Scope) {
DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
if (AbsDef)
return;
auto *SP = cast<DISubprogram>(Scope->getScopeNode());
DIE *ContextDIE;
DwarfCompileUnit *ContextCU = this;
if (includeMinimalInlineScopes())
ContextDIE = &getUnitDie();
else if (auto *SPDecl = SP->getDeclaration()) {
ContextDIE = &getUnitDie();
getOrCreateSubprogramDIE(SPDecl);
} else {
ContextDIE = getOrCreateContextDIE(SP->getScope());
ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
}
AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
ContextCU->addSInt(*AbsDef, dwarf::DW_AT_inline,
DD->getDwarfVersion() <= 4 ? Optional<dwarf::Form>()
: dwarf::DW_FORM_implicit_const,
dwarf::DW_INL_inlined);
if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
}
bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const {
return DD->getDwarfVersion() == 4 && !DD->tuneForLLDB();
}
dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
if (!useGNUAnalogForDwarf5Feature())
return Tag;
switch (Tag) {
case dwarf::DW_TAG_call_site:
return dwarf::DW_TAG_GNU_call_site;
case dwarf::DW_TAG_call_site_parameter:
return dwarf::DW_TAG_GNU_call_site_parameter;
default:
llvm_unreachable("DWARF5 tag with no GNU analog");
}
}
dwarf::Attribute
DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
if (!useGNUAnalogForDwarf5Feature())
return Attr;
switch (Attr) {
case dwarf::DW_AT_call_all_calls:
return dwarf::DW_AT_GNU_all_call_sites;
case dwarf::DW_AT_call_target:
return dwarf::DW_AT_GNU_call_site_target;
case dwarf::DW_AT_call_origin:
return dwarf::DW_AT_abstract_origin;
case dwarf::DW_AT_call_return_pc:
return dwarf::DW_AT_low_pc;
case dwarf::DW_AT_call_value:
return dwarf::DW_AT_GNU_call_site_value;
case dwarf::DW_AT_call_tail_call:
return dwarf::DW_AT_GNU_tail_call;
default:
llvm_unreachable("DWARF5 attribute with no GNU analog");
}
}
dwarf::LocationAtom
DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
if (!useGNUAnalogForDwarf5Feature())
return Loc;
switch (Loc) {
case dwarf::DW_OP_entry_value:
return dwarf::DW_OP_GNU_entry_value;
default:
llvm_unreachable("DWARF5 location atom with no GNU analog");
}
}
DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE,
const DISubprogram *CalleeSP,
bool IsTail,
const MCSymbol *PCAddr,
const MCSymbol *CallAddr,
unsigned CallReg) {
DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
ScopeDIE, nullptr);
if (CallReg) {
addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target),
MachineLocation(CallReg));
} else {
DIE *CalleeDIE = getOrCreateSubprogramDIE(CalleeSP);
assert(CalleeDIE && "Could not create DIE for call site entry origin");
addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
*CalleeDIE);
}
if (IsTail) {
addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
if (!useGNUAnalogForDwarf5Feature())
addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr);
}
if (!IsTail || useGNUAnalogForDwarf5Feature()) {
assert(PCAddr && "Missing return PC information for a call");
addLabelAddress(CallSiteDIE,
getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr);
}
return CallSiteDIE;
}
void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
for (const auto &Param : Params) {
unsigned Register = Param.getRegister();
auto CallSiteDieParam =
DIE::get(DIEValueAllocator,
getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
insertDIE(CallSiteDieParam);
addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
MachineLocation(Register));
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
DwarfExpr.setCallSiteParamValueFlag();
DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
DwarfExpr.finalize());
CallSiteDIE.addChild(CallSiteDieParam);
}
}
DIE *DwarfCompileUnit::constructImportedEntityDIE(
const DIImportedEntity *Module) {
DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
insertDIE(Module, IMDie);
DIE *EntityDie;
auto *Entity = Module->getEntity();
if (auto *NS = dyn_cast<DINamespace>(Entity))
EntityDie = getOrCreateNameSpace(NS);
else if (auto *M = dyn_cast<DIModule>(Entity))
EntityDie = getOrCreateModule(M);
else if (auto *SP = dyn_cast<DISubprogram>(Entity))
EntityDie = getOrCreateSubprogramDIE(SP);
else if (auto *T = dyn_cast<DIType>(Entity))
EntityDie = getOrCreateTypeDIE(T);
else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
EntityDie = getOrCreateGlobalVariableDIE(GV, {});
else
EntityDie = getDIE(Entity);
assert(EntityDie);
addSourceLine(*IMDie, Module->getLine(), Module->getFile());
addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
StringRef Name = Module->getName();
if (!Name.empty())
addString(*IMDie, dwarf::DW_AT_name, Name);
DINodeArray Elements = Module->getElements();
for (const auto *Element : Elements) {
if (!Element)
continue;
IMDie->addChild(
constructImportedEntityDIE(cast<DIImportedEntity>(Element)));
}
return IMDie;
}
void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
DIE *D = getDIE(SP);
if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
if (D)
addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
} else {
assert(D || includeMinimalInlineScopes());
if (D)
applySubprogramAttributesToDefinition(SP, *D);
}
}
void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
auto *Die = Entity->getDIE();
const DbgLabel *Label = nullptr;
if (AbsEntity && AbsEntity->getDIE()) {
addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
Label = dyn_cast<const DbgLabel>(Entity);
} else {
if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
applyVariableAttributes(*Var, *Die);
else if ((Label = dyn_cast<const DbgLabel>(Entity)))
applyLabelAttributes(*Label, *Die);
else
llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
}
if (Label)
if (const auto *Sym = Label->getSymbol())
addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
}
DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
auto &AbstractEntities = getAbstractEntities();
auto I = AbstractEntities.find(Node);
if (I != AbstractEntities.end())
return I->second.get();
return nullptr;
}
void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
LexicalScope *Scope) {
assert(Scope && Scope->isAbstractScope());
auto &Entity = getAbstractEntities()[Node];
if (isa<const DILocalVariable>(Node)) {
Entity = std::make_unique<DbgVariable>(
cast<const DILocalVariable>(Node), nullptr );;
DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
} else if (isa<const DILabel>(Node)) {
Entity = std::make_unique<DbgLabel>(
cast<const DILabel>(Node), nullptr );
DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
}
}
void DwarfCompileUnit::emitHeader(bool UseOffsets) {
if (!Skeleton && !DD->useSectionsAsReferences()) {
LabelBegin = Asm->createTempSymbol("cu_begin");
Asm->OutStreamer->emitLabel(LabelBegin);
}
dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
: DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
: dwarf::DW_UT_compile;
DwarfUnit::emitCommonHeader(UseOffsets, UT);
if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
Asm->emitInt64(getDWOId());
}
bool DwarfCompileUnit::hasDwarfPubSections() const {
switch (CUNode->getNameTableKind()) {
case DICompileUnit::DebugNameTableKind::None:
return false;
case DICompileUnit::DebugNameTableKind::GNU:
return true;
case DICompileUnit::DebugNameTableKind::Default:
return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
!CUNode->isDebugDirectivesOnly() &&
DD->getAccelTableKind() != AccelTableKind::Apple &&
DD->getDwarfVersion() < 5;
}
llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
}
void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
const DIScope *Context) {
if (!hasDwarfPubSections())
return;
std::string FullName = getParentContextString(Context) + Name.str();
GlobalNames[FullName] = &Die;
}
void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
const DIScope *Context) {
if (!hasDwarfPubSections())
return;
std::string FullName = getParentContextString(Context) + Name.str();
GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
}
void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
const DIScope *Context) {
if (!hasDwarfPubSections())
return;
std::string FullName = getParentContextString(Context) + Ty->getName().str();
GlobalTypes[FullName] = &Die;
}
void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
const DIScope *Context) {
if (!hasDwarfPubSections())
return;
std::string FullName = getParentContextString(Context) + Ty->getName().str();
GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
}
void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
MachineLocation Location) {
if (DV.hasComplexAddress())
addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
else
addAddress(Die, dwarf::DW_AT_location, Location);
}
void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
const MachineLocation &Location) {
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
if (Location.isIndirect())
DwarfExpr.setMemoryLocationKind();
DIExpressionCursor Cursor({});
const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
return;
DwarfExpr.addExpression(std::move(Cursor));
addBlock(Die, Attribute, DwarfExpr.finalize());
if (DwarfExpr.TagOffset)
addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
*DwarfExpr.TagOffset);
}
void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
dwarf::Attribute Attribute,
const MachineLocation &Location) {
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
const DIExpression *DIExpr = DV.getSingleExpression();
DwarfExpr.addFragmentOffset(DIExpr);
DwarfExpr.setLocation(Location, DIExpr);
DIExpressionCursor Cursor(DIExpr);
if (DIExpr->isEntryValue())
DwarfExpr.beginEntryValueExpression(Cursor);
const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
return;
DwarfExpr.addExpression(std::move(Cursor));
addBlock(Die, Attribute, DwarfExpr.finalize());
if (DwarfExpr.TagOffset)
addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
*DwarfExpr.TagOffset);
}
void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
unsigned Index) {
dwarf::Form Form = (DD->getDwarfVersion() >= 5)
? dwarf::DW_FORM_loclistx
: DD->getDwarfSectionOffsetForm();
addAttribute(Die, Attribute, Form, DIELocList(Index));
}
void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
DIE &VariableDie) {
StringRef Name = Var.getName();
if (!Name.empty())
addString(VariableDie, dwarf::DW_AT_name, Name);
const auto *DIVar = Var.getVariable();
if (DIVar) {
if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
AlignInBytes);
addAnnotation(VariableDie, DIVar->getAnnotations());
}
addSourceLine(VariableDie, DIVar);
addType(VariableDie, Var.getType());
if (Var.isArtificial())
addFlag(VariableDie, dwarf::DW_AT_artificial);
}
void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
DIE &LabelDie) {
StringRef Name = Label.getName();
if (!Name.empty())
addString(LabelDie, dwarf::DW_AT_name, Name);
const auto *DILabel = Label.getLabel();
addSourceLine(LabelDie, DILabel);
}
void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
const MCExpr *Expr) {
addAttribute(Die, (dwarf::Attribute)0, Form, DIEExpr(Expr));
}
void DwarfCompileUnit::applySubprogramAttributesToDefinition(
const DISubprogram *SP, DIE &SPDie) {
auto *SPDecl = SP->getDeclaration();
auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
addGlobalName(SP->getName(), SPDie, Context);
}
bool DwarfCompileUnit::isDwoUnit() const {
return DD->useSplitDwarf() && Skeleton;
}
void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
constructTypeDIE(D, CTy);
}
bool DwarfCompileUnit::includeMinimalInlineScopes() const {
return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
(DD->useSplitDwarf() && !Skeleton);
}
void DwarfCompileUnit::addAddrTableBase() {
const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
MCSymbol *Label = DD->getAddressPool().getLabel();
addSectionLabel(getUnitDie(),
DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
: dwarf::DW_AT_GNU_addr_base,
Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
}
void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
addAttribute(Die, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
}
void DwarfCompileUnit::createBaseTypeDIEs() {
for (auto &Btr : reverse(ExprRefedBaseTypes)) {
DIE &Die = getUnitDie().addChildFront(
DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
SmallString<32> Str;
addString(Die, dwarf::DW_AT_name,
Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
"_" + Twine(Btr.BitSize)).toStringRef(Str));
addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
addUInt(Die, dwarf::DW_AT_byte_size, None, divideCeil(Btr.BitSize, 8));
Btr.Die = &Die;
}
}