#include "LiveDebugValues.h"
#include "llvm/ADT/CoalescingBitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/CodeGen/LexicalScopes.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/PseudoSourceValue.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Function.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/TypeSize.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <functional>
#include <map>
#include <queue>
#include <tuple>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "livedebugvalues"
STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
static bool isRegOtherThanSPAndFP(const MachineOperand &Op,
const MachineInstr &MI,
const TargetRegisterInfo *TRI) {
if (!Op.isReg())
return false;
const MachineFunction *MF = MI.getParent()->getParent();
const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
Register SP = TLI->getStackPointerRegisterToSaveRestore();
Register FP = TRI->getFrameRegister(*MF);
Register Reg = Op.getReg();
return Reg && Reg != SP && Reg != FP;
}
namespace {
using DefinedRegsSet = SmallSet<Register, 32>;
using VarLocSet = CoalescingBitVector<uint64_t>;
struct LocIndex {
using u32_location_t = uint32_t;
using u32_index_t = uint32_t;
u32_location_t Location; u32_index_t Index;
static constexpr u32_location_t kUniversalLocation = 0;
static constexpr u32_location_t kFirstRegLocation = 1;
static constexpr u32_location_t kFirstInvalidRegLocation = 1 << 30;
static constexpr u32_location_t kSpillLocation = kFirstInvalidRegLocation;
static constexpr u32_location_t kEntryValueBackupLocation =
kFirstInvalidRegLocation + 1;
LocIndex(u32_location_t Location, u32_index_t Index)
: Location(Location), Index(Index) {}
uint64_t getAsRawInteger() const {
return (static_cast<uint64_t>(Location) << 32) | Index;
}
template<typename IntT> static LocIndex fromRawInteger(IntT ID) {
static_assert(std::is_unsigned<IntT>::value &&
sizeof(ID) == sizeof(uint64_t),
"Cannot convert raw integer to LocIndex");
return {static_cast<u32_location_t>(ID >> 32),
static_cast<u32_index_t>(ID)};
}
static uint64_t rawIndexForReg(Register Reg) {
return LocIndex(Reg, 0).getAsRawInteger();
}
static auto indexRangeForLocation(const VarLocSet &Set,
u32_location_t Location) {
uint64_t Start = LocIndex(Location, 0).getAsRawInteger();
uint64_t End = LocIndex(Location + 1, 0).getAsRawInteger();
return Set.half_open_range(Start, End);
}
};
using VarLocsInRange = SmallSet<LocIndex::u32_index_t, 32>;
using LocIndices = SmallVector<LocIndex, 2>;
class VarLocBasedLDV : public LDVImpl {
private:
const TargetRegisterInfo *TRI;
const TargetInstrInfo *TII;
const TargetFrameLowering *TFI;
TargetPassConfig *TPC;
BitVector CalleeSavedRegs;
LexicalScopes LS;
VarLocSet::Allocator Alloc;
const MachineInstr *LastNonDbgMI;
enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
using FragmentInfo = DIExpression::FragmentInfo;
using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
struct VarLoc {
struct SpillLoc {
unsigned SpillBase;
StackOffset SpillOffset;
bool operator==(const SpillLoc &Other) const {
return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
}
bool operator!=(const SpillLoc &Other) const {
return !(*this == Other);
}
};
const DebugVariable Var;
const DIExpression *Expr;
const MachineInstr &MI;
enum class MachineLocKind {
InvalidKind = 0,
RegisterKind,
SpillLocKind,
ImmediateKind
};
enum class EntryValueLocKind {
NonEntryValueKind = 0,
EntryValueKind,
EntryValueBackupKind,
EntryValueCopyBackupKind
} EVKind = EntryValueLocKind::NonEntryValueKind;
union MachineLocValue {
uint64_t RegNo;
SpillLoc SpillLocation;
uint64_t Hash;
int64_t Immediate;
const ConstantFP *FPImm;
const ConstantInt *CImm;
MachineLocValue() : Hash(0) {}
};
struct MachineLoc {
MachineLocKind Kind;
MachineLocValue Value;
bool operator==(const MachineLoc &Other) const {
if (Kind != Other.Kind)
return false;
switch (Kind) {
case MachineLocKind::SpillLocKind:
return Value.SpillLocation == Other.Value.SpillLocation;
case MachineLocKind::RegisterKind:
case MachineLocKind::ImmediateKind:
return Value.Hash == Other.Value.Hash;
default:
llvm_unreachable("Invalid kind");
}
}
bool operator<(const MachineLoc &Other) const {
switch (Kind) {
case MachineLocKind::SpillLocKind:
return std::make_tuple(
Kind, Value.SpillLocation.SpillBase,
Value.SpillLocation.SpillOffset.getFixed(),
Value.SpillLocation.SpillOffset.getScalable()) <
std::make_tuple(
Other.Kind, Other.Value.SpillLocation.SpillBase,
Other.Value.SpillLocation.SpillOffset.getFixed(),
Other.Value.SpillLocation.SpillOffset.getScalable());
case MachineLocKind::RegisterKind:
case MachineLocKind::ImmediateKind:
return std::tie(Kind, Value.Hash) <
std::tie(Other.Kind, Other.Value.Hash);
default:
llvm_unreachable("Invalid kind");
}
}
};
SmallVector<MachineLoc, 8> Locs;
SmallVector<unsigned, 8> OrigLocMap;
VarLoc(const MachineInstr &MI, LexicalScopes &LS)
: Var(MI.getDebugVariable(), MI.getDebugExpression(),
MI.getDebugLoc()->getInlinedAt()),
Expr(MI.getDebugExpression()), MI(MI) {
assert(MI.isDebugValue() && "not a DBG_VALUE");
assert((MI.isDebugValueList() || MI.getNumOperands() == 4) &&
"malformed DBG_VALUE");
for (const MachineOperand &Op : MI.debug_operands()) {
MachineLoc ML = GetLocForOp(Op);
auto It = find(Locs, ML);
if (It == Locs.end()) {
Locs.push_back(ML);
OrigLocMap.push_back(MI.getDebugOperandIndex(&Op));
} else {
unsigned OpIdx = Locs.size();
unsigned DuplicatingIdx = std::distance(Locs.begin(), It);
Expr = DIExpression::replaceArg(Expr, OpIdx, DuplicatingIdx);
}
}
assert(EVKind != EntryValueLocKind::EntryValueKind &&
!isEntryBackupLoc());
}
static MachineLoc GetLocForOp(const MachineOperand &Op) {
MachineLocKind Kind;
MachineLocValue Loc;
if (Op.isReg()) {
Kind = MachineLocKind::RegisterKind;
Loc.RegNo = Op.getReg();
} else if (Op.isImm()) {
Kind = MachineLocKind::ImmediateKind;
Loc.Immediate = Op.getImm();
} else if (Op.isFPImm()) {
Kind = MachineLocKind::ImmediateKind;
Loc.FPImm = Op.getFPImm();
} else if (Op.isCImm()) {
Kind = MachineLocKind::ImmediateKind;
Loc.CImm = Op.getCImm();
} else
llvm_unreachable("Invalid Op kind for MachineLoc.");
return {Kind, Loc};
}
static VarLoc CreateEntryLoc(const MachineInstr &MI, LexicalScopes &LS,
const DIExpression *EntryExpr, Register Reg) {
VarLoc VL(MI, LS);
assert(VL.Locs.size() == 1 &&
VL.Locs[0].Kind == MachineLocKind::RegisterKind);
VL.EVKind = EntryValueLocKind::EntryValueKind;
VL.Expr = EntryExpr;
VL.Locs[0].Value.RegNo = Reg;
return VL;
}
static VarLoc CreateEntryBackupLoc(const MachineInstr &MI,
LexicalScopes &LS,
const DIExpression *EntryExpr) {
VarLoc VL(MI, LS);
assert(VL.Locs.size() == 1 &&
VL.Locs[0].Kind == MachineLocKind::RegisterKind);
VL.EVKind = EntryValueLocKind::EntryValueBackupKind;
VL.Expr = EntryExpr;
return VL;
}
static VarLoc CreateEntryCopyBackupLoc(const MachineInstr &MI,
LexicalScopes &LS,
const DIExpression *EntryExpr,
Register NewReg) {
VarLoc VL(MI, LS);
assert(VL.Locs.size() == 1 &&
VL.Locs[0].Kind == MachineLocKind::RegisterKind);
VL.EVKind = EntryValueLocKind::EntryValueCopyBackupKind;
VL.Expr = EntryExpr;
VL.Locs[0].Value.RegNo = NewReg;
return VL;
}
static VarLoc CreateCopyLoc(const VarLoc &OldVL, const MachineLoc &OldML,
Register NewReg) {
VarLoc VL = OldVL;
for (MachineLoc &ML : VL.Locs)
if (ML == OldML) {
ML.Kind = MachineLocKind::RegisterKind;
ML.Value.RegNo = NewReg;
return VL;
}
llvm_unreachable("Should have found OldML in new VarLoc.");
}
static VarLoc CreateSpillLoc(const VarLoc &OldVL, const MachineLoc &OldML,
unsigned SpillBase, StackOffset SpillOffset) {
VarLoc VL = OldVL;
for (MachineLoc &ML : VL.Locs)
if (ML == OldML) {
ML.Kind = MachineLocKind::SpillLocKind;
ML.Value.SpillLocation = {SpillBase, SpillOffset};
return VL;
}
llvm_unreachable("Should have found OldML in new VarLoc.");
}
MachineInstr *BuildDbgValue(MachineFunction &MF) const {
assert(!isEntryBackupLoc() &&
"Tried to produce DBG_VALUE for backup VarLoc");
const DebugLoc &DbgLoc = MI.getDebugLoc();
bool Indirect = MI.isIndirectDebugValue();
const auto &IID = MI.getDesc();
const DILocalVariable *Var = MI.getDebugVariable();
NumInserted++;
const DIExpression *DIExpr = Expr;
SmallVector<MachineOperand, 8> MOs;
for (unsigned I = 0, E = Locs.size(); I < E; ++I) {
MachineLocKind LocKind = Locs[I].Kind;
MachineLocValue Loc = Locs[I].Value;
const MachineOperand &Orig = MI.getDebugOperand(OrigLocMap[I]);
switch (LocKind) {
case MachineLocKind::RegisterKind:
MOs.push_back(MachineOperand::CreateReg(
EVKind == EntryValueLocKind::EntryValueKind ? Orig.getReg()
: Register(Loc.RegNo),
false));
break;
case MachineLocKind::SpillLocKind: {
unsigned Base = Loc.SpillLocation.SpillBase;
auto *TRI = MF.getSubtarget().getRegisterInfo();
if (MI.isNonListDebugValue()) {
auto Deref = Indirect ? DIExpression::DerefAfter : 0;
DIExpr = TRI->prependOffsetExpression(
DIExpr, DIExpression::ApplyOffset | Deref,
Loc.SpillLocation.SpillOffset);
Indirect = true;
} else {
SmallVector<uint64_t, 4> Ops;
TRI->getOffsetOpcodes(Loc.SpillLocation.SpillOffset, Ops);
Ops.push_back(dwarf::DW_OP_deref);
DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, I);
}
MOs.push_back(MachineOperand::CreateReg(Base, false));
break;
}
case MachineLocKind::ImmediateKind: {
MOs.push_back(Orig);
break;
}
case MachineLocKind::InvalidKind:
llvm_unreachable("Tried to produce DBG_VALUE for invalid VarLoc");
}
}
return BuildMI(MF, DbgLoc, IID, Indirect, MOs, Var, DIExpr);
}
bool isConstant(MachineLocKind Kind) const {
return Kind == MachineLocKind::ImmediateKind;
}
bool isEntryBackupLoc() const {
return EVKind == EntryValueLocKind::EntryValueBackupKind ||
EVKind == EntryValueLocKind::EntryValueCopyBackupKind;
}
bool isEntryValueBackupReg(Register Reg) const {
return EVKind == EntryValueLocKind::EntryValueBackupKind && usesReg(Reg);
}
bool isEntryValueCopyBackupReg(Register Reg) const {
return EVKind == EntryValueLocKind::EntryValueCopyBackupKind &&
usesReg(Reg);
}
bool usesReg(Register Reg) const {
MachineLoc RegML;
RegML.Kind = MachineLocKind::RegisterKind;
RegML.Value.RegNo = Reg;
return is_contained(Locs, RegML);
}
unsigned getRegIdx(Register Reg) const {
for (unsigned Idx = 0; Idx < Locs.size(); ++Idx)
if (Locs[Idx].Kind == MachineLocKind::RegisterKind &&
Register{static_cast<unsigned>(Locs[Idx].Value.RegNo)} == Reg)
return Idx;
llvm_unreachable("Could not find given Reg in Locs");
}
bool getDescribingRegs(SmallVectorImpl<uint32_t> &Regs) const {
bool AnyRegs = false;
for (const auto &Loc : Locs)
if (Loc.Kind == MachineLocKind::RegisterKind) {
Regs.push_back(Loc.Value.RegNo);
AnyRegs = true;
}
return AnyRegs;
}
bool containsSpillLocs() const {
return any_of(Locs, [](VarLoc::MachineLoc ML) {
return ML.Kind == VarLoc::MachineLocKind::SpillLocKind;
});
}
bool usesSpillLoc(SpillLoc SpillLocation) const {
MachineLoc SpillML;
SpillML.Kind = MachineLocKind::SpillLocKind;
SpillML.Value.SpillLocation = SpillLocation;
return is_contained(Locs, SpillML);
}
unsigned getSpillLocIdx(SpillLoc SpillLocation) const {
for (unsigned Idx = 0; Idx < Locs.size(); ++Idx)
if (Locs[Idx].Kind == MachineLocKind::SpillLocKind &&
Locs[Idx].Value.SpillLocation == SpillLocation)
return Idx;
llvm_unreachable("Could not find given SpillLoc in Locs");
}
bool dominates(LexicalScopes &LS, MachineBasicBlock &MBB) const {
return LS.dominates(MI.getDebugLoc().get(), &MBB);
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void dump(const TargetRegisterInfo *TRI, raw_ostream &Out = dbgs()) const {
Out << "VarLoc(";
for (const MachineLoc &MLoc : Locs) {
if (Locs.begin() != &MLoc)
Out << ", ";
switch (MLoc.Kind) {
case MachineLocKind::RegisterKind:
Out << printReg(MLoc.Value.RegNo, TRI);
break;
case MachineLocKind::SpillLocKind:
Out << printReg(MLoc.Value.SpillLocation.SpillBase, TRI);
Out << "[" << MLoc.Value.SpillLocation.SpillOffset.getFixed() << " + "
<< MLoc.Value.SpillLocation.SpillOffset.getScalable()
<< "x vscale"
<< "]";
break;
case MachineLocKind::ImmediateKind:
Out << MLoc.Value.Immediate;
break;
case MachineLocKind::InvalidKind:
llvm_unreachable("Invalid VarLoc in dump method");
}
}
Out << ", \"" << Var.getVariable()->getName() << "\", " << *Expr << ", ";
if (Var.getInlinedAt())
Out << "!" << Var.getInlinedAt()->getMetadataID() << ")\n";
else
Out << "(null))";
if (isEntryBackupLoc())
Out << " (backup loc)\n";
else
Out << "\n";
}
#endif
bool operator==(const VarLoc &Other) const {
return std::tie(EVKind, Var, Expr, Locs) ==
std::tie(Other.EVKind, Other.Var, Other.Expr, Other.Locs);
}
bool operator<(const VarLoc &Other) const {
return std::tie(Var, EVKind, Locs, Expr) <
std::tie(Other.Var, Other.EVKind, Other.Locs, Other.Expr);
}
};
#ifndef NDEBUG
using VarVec = SmallVector<VarLoc, 32>;
#endif
class VarLocMap {
std::map<VarLoc, LocIndices> Var2Indices;
SmallDenseMap<LocIndex::u32_location_t, std::vector<VarLoc>> Loc2Vars;
public:
LocIndices insert(const VarLoc &VL) {
LocIndices &Indices = Var2Indices[VL];
if (!Indices.empty())
return Indices;
SmallVector<LocIndex::u32_location_t, 4> Locations;
if (VL.EVKind == VarLoc::EntryValueLocKind::NonEntryValueKind) {
VL.getDescribingRegs(Locations);
assert(all_of(Locations,
[](auto RegNo) {
return RegNo < LocIndex::kFirstInvalidRegLocation;
}) &&
"Physreg out of range?");
if (VL.containsSpillLocs()) {
LocIndex::u32_location_t Loc = LocIndex::kSpillLocation;
Locations.push_back(Loc);
}
} else if (VL.EVKind != VarLoc::EntryValueLocKind::EntryValueKind) {
LocIndex::u32_location_t Loc = LocIndex::kEntryValueBackupLocation;
Locations.push_back(Loc);
}
Locations.push_back(LocIndex::kUniversalLocation);
for (LocIndex::u32_location_t Location : Locations) {
auto &Vars = Loc2Vars[Location];
Indices.push_back(
{Location, static_cast<LocIndex::u32_index_t>(Vars.size())});
Vars.push_back(VL);
}
return Indices;
}
LocIndices getAllIndices(const VarLoc &VL) const {
auto IndIt = Var2Indices.find(VL);
assert(IndIt != Var2Indices.end() && "VarLoc not tracked");
return IndIt->second;
}
const VarLoc &operator[](LocIndex ID) const {
auto LocIt = Loc2Vars.find(ID.Location);
assert(LocIt != Loc2Vars.end() && "Location not tracked");
return LocIt->second[ID.Index];
}
};
using VarLocInMBB =
SmallDenseMap<const MachineBasicBlock *, std::unique_ptr<VarLocSet>>;
struct TransferDebugPair {
MachineInstr *TransferInst; LocIndex LocationID; };
using TransferMap = SmallVector<TransferDebugPair, 4>;
using InstToEntryLocMap = std::multimap<const MachineInstr *, LocIndex>;
using RegDefToInstMap = DenseMap<Register, MachineInstr *>;
using FragmentOfVar =
std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
using OverlapMap =
DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
using VarToFragments =
DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
static void collectAllVarLocs(SmallVectorImpl<VarLoc> &Collected,
const VarLocSet &CollectFrom,
const VarLocMap &VarLocIDs);
void getUsedRegs(const VarLocSet &CollectFrom,
SmallVectorImpl<Register> &UsedRegs) const;
class OpenRangesSet {
VarLocSet::Allocator &Alloc;
VarLocSet VarLocs;
SmallDenseMap<DebugVariable, LocIndices, 8> Vars;
SmallDenseMap<DebugVariable, LocIndices, 8> EntryValuesBackupVars;
OverlapMap &OverlappingFragments;
public:
OpenRangesSet(VarLocSet::Allocator &Alloc, OverlapMap &_OLapMap)
: Alloc(Alloc), VarLocs(Alloc), OverlappingFragments(_OLapMap) {}
const VarLocSet &getVarLocs() const { return VarLocs; }
void getUniqueVarLocs(SmallVectorImpl<VarLoc> &Collected,
const VarLocMap &VarLocIDs) const {
collectAllVarLocs(Collected, VarLocs, VarLocIDs);
}
void erase(const VarLoc &VL);
void erase(const VarLocsInRange &KillSet, const VarLocMap &VarLocIDs,
LocIndex::u32_location_t Location);
void insert(LocIndices VarLocIDs, const VarLoc &VL);
void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map);
llvm::Optional<LocIndices> getEntryValueBackup(DebugVariable Var);
void clear() {
VarLocs.clear();
Vars.clear();
EntryValuesBackupVars.clear();
}
bool empty() const {
assert(Vars.empty() == EntryValuesBackupVars.empty() &&
Vars.empty() == VarLocs.empty() &&
"open ranges are inconsistent");
return VarLocs.empty();
}
auto getEmptyVarLocRange() const {
return iterator_range<VarLocSet::const_iterator>(getVarLocs().end(),
getVarLocs().end());
}
auto getRegisterVarLocs(Register Reg) const {
return LocIndex::indexRangeForLocation(getVarLocs(), Reg);
}
auto getSpillVarLocs() const {
return LocIndex::indexRangeForLocation(getVarLocs(),
LocIndex::kSpillLocation);
}
auto getEntryValueBackupVarLocs() const {
return LocIndex::indexRangeForLocation(
getVarLocs(), LocIndex::kEntryValueBackupLocation);
}
};
static void collectIDsForRegs(VarLocsInRange &Collected,
const DefinedRegsSet &Regs,
const VarLocSet &CollectFrom,
const VarLocMap &VarLocIDs);
VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB, VarLocInMBB &Locs) {
std::unique_ptr<VarLocSet> &VLS = Locs[MBB];
if (!VLS)
VLS = std::make_unique<VarLocSet>(Alloc);
return *VLS;
}
const VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB,
const VarLocInMBB &Locs) const {
auto It = Locs.find(MBB);
assert(It != Locs.end() && "MBB not in map");
return *It->second;
}
bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
Register &Reg);
bool isEntryValueCandidate(const MachineInstr &MI,
const DefinedRegsSet &Regs) const;
Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
MachineFunction *MF,
Register &Reg);
VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
TransferMap &Transfers, VarLocMap &VarLocIDs,
LocIndex OldVarID, TransferKind Kind,
const VarLoc::MachineLoc &OldLoc,
Register NewReg = Register());
void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs,
InstToEntryLocMap &EntryValTransfers,
RegDefToInstMap &RegSetInstrs);
void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs, TransferMap &Transfers);
void cleanupEntryValueTransfers(const MachineInstr *MI,
OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs, const VarLoc &EntryVL,
InstToEntryLocMap &EntryValTransfers);
void removeEntryValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs, const VarLoc &EntryVL,
InstToEntryLocMap &EntryValTransfers,
RegDefToInstMap &RegSetInstrs);
void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs,
InstToEntryLocMap &EntryValTransfers,
VarLocsInRange &KillSet);
void recordEntryValue(const MachineInstr &MI,
const DefinedRegsSet &DefinedRegs,
OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs);
void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs, TransferMap &Transfers);
void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs,
InstToEntryLocMap &EntryValTransfers,
RegDefToInstMap &RegSetInstrs);
bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs, TransferMap &Transfers,
InstToEntryLocMap &EntryValTransfers,
RegDefToInstMap &RegSetInstrs);
void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
OverlapMap &OLapMap);
bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
const VarLocMap &VarLocIDs,
SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
TargetPassConfig *TPC, unsigned InputBBLimit,
unsigned InputDbgValLimit) override;
public:
VarLocBasedLDV();
~VarLocBasedLDV();
void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
const VarLocMap &VarLocIDs, const char *msg,
raw_ostream &Out) const;
};
}
VarLocBasedLDV::VarLocBasedLDV() = default;
VarLocBasedLDV::~VarLocBasedLDV() = default;
void VarLocBasedLDV::OpenRangesSet::erase(const VarLoc &VL) {
auto DoErase = [VL, this](DebugVariable VarToErase) {
auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
auto It = EraseFrom->find(VarToErase);
if (It != EraseFrom->end()) {
LocIndices IDs = It->second;
for (LocIndex ID : IDs)
VarLocs.reset(ID.getAsRawInteger());
EraseFrom->erase(It);
}
};
DebugVariable Var = VL.Var;
DoErase(Var);
FragmentInfo ThisFragment = Var.getFragmentOrDefault();
auto MapIt = OverlappingFragments.find({Var.getVariable(), ThisFragment});
if (MapIt != OverlappingFragments.end()) {
for (auto Fragment : MapIt->second) {
VarLocBasedLDV::OptFragmentInfo FragmentHolder;
if (!DebugVariable::isDefaultFragment(Fragment))
FragmentHolder = VarLocBasedLDV::OptFragmentInfo(Fragment);
DoErase({Var.getVariable(), FragmentHolder, Var.getInlinedAt()});
}
}
}
void VarLocBasedLDV::OpenRangesSet::erase(const VarLocsInRange &KillSet,
const VarLocMap &VarLocIDs,
LocIndex::u32_location_t Location) {
VarLocSet RemoveSet(Alloc);
for (LocIndex::u32_index_t ID : KillSet) {
const VarLoc &VL = VarLocIDs[LocIndex(Location, ID)];
auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
EraseFrom->erase(VL.Var);
LocIndices VLI = VarLocIDs.getAllIndices(VL);
for (LocIndex ID : VLI)
RemoveSet.set(ID.getAsRawInteger());
}
VarLocs.intersectWithComplement(RemoveSet);
}
void VarLocBasedLDV::OpenRangesSet::insertFromLocSet(const VarLocSet &ToLoad,
const VarLocMap &Map) {
VarLocsInRange UniqueVarLocIDs;
DefinedRegsSet Regs;
Regs.insert(LocIndex::kUniversalLocation);
collectIDsForRegs(UniqueVarLocIDs, Regs, ToLoad, Map);
for (uint64_t ID : UniqueVarLocIDs) {
LocIndex Idx = LocIndex::fromRawInteger(ID);
const VarLoc &VarL = Map[Idx];
const LocIndices Indices = Map.getAllIndices(VarL);
insert(Indices, VarL);
}
}
void VarLocBasedLDV::OpenRangesSet::insert(LocIndices VarLocIDs,
const VarLoc &VL) {
auto *InsertInto = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
for (LocIndex ID : VarLocIDs)
VarLocs.set(ID.getAsRawInteger());
InsertInto->insert({VL.Var, VarLocIDs});
}
llvm::Optional<LocIndices>
VarLocBasedLDV::OpenRangesSet::getEntryValueBackup(DebugVariable Var) {
auto It = EntryValuesBackupVars.find(Var);
if (It != EntryValuesBackupVars.end())
return It->second;
return llvm::None;
}
void VarLocBasedLDV::collectIDsForRegs(VarLocsInRange &Collected,
const DefinedRegsSet &Regs,
const VarLocSet &CollectFrom,
const VarLocMap &VarLocIDs) {
assert(!Regs.empty() && "Nothing to collect");
SmallVector<Register, 32> SortedRegs;
append_range(SortedRegs, Regs);
array_pod_sort(SortedRegs.begin(), SortedRegs.end());
auto It = CollectFrom.find(LocIndex::rawIndexForReg(SortedRegs.front()));
auto End = CollectFrom.end();
for (Register Reg : SortedRegs) {
uint64_t FirstIndexForReg = LocIndex::rawIndexForReg(Reg);
uint64_t FirstInvalidIndex = LocIndex::rawIndexForReg(Reg + 1);
It.advanceToLowerBound(FirstIndexForReg);
for (; It != End && *It < FirstInvalidIndex; ++It) {
LocIndex ItIdx = LocIndex::fromRawInteger(*It);
const VarLoc &VL = VarLocIDs[ItIdx];
LocIndices LI = VarLocIDs.getAllIndices(VL);
assert(LI.back().Location == LocIndex::kUniversalLocation &&
"Unexpected order of LocIndices for VarLoc; was it inserted into "
"the VarLocMap correctly?");
Collected.insert(LI.back().Index);
}
if (It == End)
return;
}
}
void VarLocBasedLDV::getUsedRegs(const VarLocSet &CollectFrom,
SmallVectorImpl<Register> &UsedRegs) const {
uint64_t FirstRegIndex =
LocIndex::rawIndexForReg(LocIndex::kFirstRegLocation);
uint64_t FirstInvalidIndex =
LocIndex::rawIndexForReg(LocIndex::kFirstInvalidRegLocation);
for (auto It = CollectFrom.find(FirstRegIndex),
End = CollectFrom.find(FirstInvalidIndex);
It != End;) {
uint32_t FoundReg = LocIndex::fromRawInteger(*It).Location;
assert((UsedRegs.empty() || FoundReg != UsedRegs.back()) &&
"Duplicate used reg");
UsedRegs.push_back(FoundReg);
uint64_t NextRegIndex = LocIndex::rawIndexForReg(FoundReg + 1);
It.advanceToLowerBound(NextRegIndex);
}
}
#ifndef NDEBUG
void VarLocBasedLDV::printVarLocInMBB(const MachineFunction &MF,
const VarLocInMBB &V,
const VarLocMap &VarLocIDs,
const char *msg,
raw_ostream &Out) const {
Out << '\n' << msg << '\n';
for (const MachineBasicBlock &BB : MF) {
if (!V.count(&BB))
continue;
const VarLocSet &L = getVarLocsInMBB(&BB, V);
if (L.empty())
continue;
SmallVector<VarLoc, 32> VarLocs;
collectAllVarLocs(VarLocs, L, VarLocIDs);
Out << "MBB: " << BB.getNumber() << ":\n";
for (const VarLoc &VL : VarLocs) {
Out << " Var: " << VL.Var.getVariable()->getName();
Out << " MI: ";
VL.dump(TRI, Out);
}
}
Out << "\n";
}
#endif
VarLocBasedLDV::VarLoc::SpillLoc
VarLocBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
assert(MI.hasOneMemOperand() &&
"Spill instruction does not have exactly one memory operand?");
auto MMOI = MI.memoperands_begin();
const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
assert(PVal->kind() == PseudoSourceValue::FixedStack &&
"Inconsistent memory operand in spill instruction");
int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
const MachineBasicBlock *MBB = MI.getParent();
Register Reg;
StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
return {Reg, Offset};
}
void VarLocBasedLDV::cleanupEntryValueTransfers(
const MachineInstr *TRInst, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
const VarLoc &EntryVL, InstToEntryLocMap &EntryValTransfers) {
if (EntryValTransfers.empty() || TRInst == nullptr)
return;
auto TransRange = EntryValTransfers.equal_range(TRInst);
for (auto TDPair : llvm::make_range(TransRange.first, TransRange.second)) {
const VarLoc &EmittedEV = VarLocIDs[TDPair.second];
if (std::tie(EntryVL.Var, EntryVL.Locs[0].Value.RegNo, EntryVL.Expr) ==
std::tie(EmittedEV.Var, EmittedEV.Locs[0].Value.RegNo,
EmittedEV.Expr)) {
OpenRanges.erase(EmittedEV);
EntryValTransfers.erase(TRInst);
break;
}
}
}
void VarLocBasedLDV::removeEntryValue(const MachineInstr &MI,
OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs,
const VarLoc &EntryVL,
InstToEntryLocMap &EntryValTransfers,
RegDefToInstMap &RegSetInstrs) {
if (&MI == &EntryVL.MI)
return;
if (!MI.getDebugOperand(0).isReg())
return;
const MachineInstr *TransferInst = nullptr;
Register Reg = MI.getDebugOperand(0).getReg();
if (Reg.isValid() && RegSetInstrs.find(Reg) != RegSetInstrs.end())
TransferInst = RegSetInstrs.find(Reg)->second;
if (!TransferInst && !LastNonDbgMI && MI.getParent()->isEntryBlock())
return;
if (MI.getDebugExpression()->getNumElements() == 0 && TransferInst) {
auto DestSrc = TII->isCopyInstr(*TransferInst);
if (DestSrc) {
const MachineOperand *SrcRegOp, *DestRegOp;
SrcRegOp = DestSrc->Source;
DestRegOp = DestSrc->Destination;
if (Reg == DestRegOp->getReg()) {
for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
const VarLoc &VL = VarLocIDs[LocIndex::fromRawInteger(ID)];
if (VL.isEntryValueCopyBackupReg(Reg) &&
VL.MI.getDebugOperand(0).getReg() == SrcRegOp->getReg())
return;
}
}
}
}
LLVM_DEBUG(dbgs() << "Deleting a DBG entry value because of: ";
MI.print(dbgs(), false,
false, false,
true, TII));
cleanupEntryValueTransfers(TransferInst, OpenRanges, VarLocIDs, EntryVL,
EntryValTransfers);
OpenRanges.erase(EntryVL);
}
void VarLocBasedLDV::transferDebugValue(const MachineInstr &MI,
OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs,
InstToEntryLocMap &EntryValTransfers,
RegDefToInstMap &RegSetInstrs) {
if (!MI.isDebugValue())
return;
const DILocalVariable *Var = MI.getDebugVariable();
const DIExpression *Expr = MI.getDebugExpression();
const DILocation *DebugLoc = MI.getDebugLoc();
const DILocation *InlinedAt = DebugLoc->getInlinedAt();
assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
"Expected inlined-at fields to agree");
DebugVariable V(Var, Expr, InlinedAt);
auto EntryValBackupID = OpenRanges.getEntryValueBackup(V);
if (Var->isParameter() && EntryValBackupID) {
const VarLoc &EntryVL = VarLocIDs[EntryValBackupID->back()];
removeEntryValue(MI, OpenRanges, VarLocIDs, EntryVL, EntryValTransfers,
RegSetInstrs);
}
if (all_of(MI.debug_operands(), [](const MachineOperand &MO) {
return (MO.isReg() && MO.getReg()) || MO.isImm() || MO.isFPImm() ||
MO.isCImm();
})) {
VarLoc VL(MI, LS);
OpenRanges.erase(VL);
LocIndices IDs = VarLocIDs.insert(VL);
OpenRanges.insert(IDs, VL);
} else if (MI.memoperands().size() > 0) {
llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
} else {
assert(MI.isUndefDebugValue() &&
"Unexpected non-undef DBG_VALUE encountered");
VarLoc VL(MI, LS);
OpenRanges.erase(VL);
}
}
void VarLocBasedLDV::collectAllVarLocs(SmallVectorImpl<VarLoc> &Collected,
const VarLocSet &CollectFrom,
const VarLocMap &VarLocIDs) {
uint64_t FirstIndex = LocIndex::rawIndexForReg(LocIndex::kUniversalLocation);
uint64_t FirstInvalidIndex =
LocIndex::rawIndexForReg(LocIndex::kUniversalLocation + 1);
for (auto It = CollectFrom.find(FirstIndex), End = CollectFrom.end();
It != End && *It < FirstInvalidIndex; ++It) {
LocIndex RegIdx = LocIndex::fromRawInteger(*It);
Collected.push_back(VarLocIDs[RegIdx]);
}
}
void VarLocBasedLDV::emitEntryValues(MachineInstr &MI,
OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs,
InstToEntryLocMap &EntryValTransfers,
VarLocsInRange &KillSet) {
if (MI.isTerminator())
return;
for (uint32_t ID : KillSet) {
LocIndex Idx = LocIndex(LocIndex::kUniversalLocation, ID);
const VarLoc &VL = VarLocIDs[Idx];
if (!VL.Var.getVariable()->isParameter())
continue;
auto DebugVar = VL.Var;
Optional<LocIndices> EntryValBackupIDs =
OpenRanges.getEntryValueBackup(DebugVar);
if (!EntryValBackupIDs)
continue;
const VarLoc &EntryVL = VarLocIDs[EntryValBackupIDs->back()];
VarLoc EntryLoc = VarLoc::CreateEntryLoc(EntryVL.MI, LS, EntryVL.Expr,
EntryVL.Locs[0].Value.RegNo);
LocIndices EntryValueIDs = VarLocIDs.insert(EntryLoc);
assert(EntryValueIDs.size() == 1 &&
"EntryValue loc should not be variadic");
EntryValTransfers.insert({&MI, EntryValueIDs.back()});
OpenRanges.insert(EntryValueIDs, EntryLoc);
}
}
void VarLocBasedLDV::insertTransferDebugPair(
MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
VarLocMap &VarLocIDs, LocIndex OldVarID, TransferKind Kind,
const VarLoc::MachineLoc &OldLoc, Register NewReg) {
const VarLoc &OldVarLoc = VarLocIDs[OldVarID];
auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &VarLocIDs](VarLoc &VL) {
LocIndices LocIds = VarLocIDs.insert(VL);
OpenRanges.erase(VL);
OpenRanges.insert(LocIds, VL);
assert(!MI.isTerminator() && "Cannot insert DBG_VALUE after terminator");
TransferDebugPair MIP = {&MI, LocIds.back()};
Transfers.push_back(MIP);
};
OpenRanges.erase(VarLocIDs[OldVarID]);
switch (Kind) {
case TransferKind::TransferCopy: {
assert(NewReg &&
"No register supplied when handling a copy of a debug value");
VarLoc VL = VarLoc::CreateCopyLoc(OldVarLoc, OldLoc, NewReg);
ProcessVarLoc(VL);
LLVM_DEBUG({
dbgs() << "Creating VarLoc for register copy:";
VL.dump(TRI);
});
return;
}
case TransferKind::TransferSpill: {
VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
VarLoc VL = VarLoc::CreateSpillLoc(
OldVarLoc, OldLoc, SpillLocation.SpillBase, SpillLocation.SpillOffset);
ProcessVarLoc(VL);
LLVM_DEBUG({
dbgs() << "Creating VarLoc for spill:";
VL.dump(TRI);
});
return;
}
case TransferKind::TransferRestore: {
assert(NewReg &&
"No register supplied when handling a restore of a debug value");
VarLoc VL = VarLoc::CreateCopyLoc(OldVarLoc, OldLoc, NewReg);
ProcessVarLoc(VL);
LLVM_DEBUG({
dbgs() << "Creating VarLoc for restore:";
VL.dump(TRI);
});
return;
}
}
llvm_unreachable("Invalid transfer kind");
}
void VarLocBasedLDV::transferRegisterDef(MachineInstr &MI,
OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs,
InstToEntryLocMap &EntryValTransfers,
RegDefToInstMap &RegSetInstrs) {
if (MI.isMetaInstruction())
return;
MachineFunction *MF = MI.getMF();
const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
Register SP = TLI->getStackPointerRegisterToSaveRestore();
DefinedRegsSet DeadRegs;
SmallVector<const uint32_t *, 4> RegMasks;
for (const MachineOperand &MO : MI.operands()) {
if (MO.isReg() && MO.isDef() && MO.getReg() &&
Register::isPhysicalRegister(MO.getReg()) &&
!(MI.isCall() && MO.getReg() == SP)) {
for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
DeadRegs.insert(*RAI);
RegSetInstrs.erase(MO.getReg());
RegSetInstrs.insert({MO.getReg(), &MI});
} else if (MO.isRegMask()) {
RegMasks.push_back(MO.getRegMask());
}
}
if (!RegMasks.empty()) {
SmallVector<Register, 32> UsedRegs;
getUsedRegs(OpenRanges.getVarLocs(), UsedRegs);
for (Register Reg : UsedRegs) {
if (Reg == SP)
continue;
bool AnyRegMaskKillsReg =
any_of(RegMasks, [Reg](const uint32_t *RegMask) {
return MachineOperand::clobbersPhysReg(RegMask, Reg);
});
if (AnyRegMaskKillsReg)
DeadRegs.insert(Reg);
if (AnyRegMaskKillsReg) {
RegSetInstrs.erase(Reg);
RegSetInstrs.insert({Reg, &MI});
}
}
}
if (DeadRegs.empty())
return;
VarLocsInRange KillSet;
collectIDsForRegs(KillSet, DeadRegs, OpenRanges.getVarLocs(), VarLocIDs);
OpenRanges.erase(KillSet, VarLocIDs, LocIndex::kUniversalLocation);
if (TPC) {
auto &TM = TPC->getTM<TargetMachine>();
if (TM.Options.ShouldEmitDebugEntryValues())
emitEntryValues(MI, OpenRanges, VarLocIDs, EntryValTransfers, KillSet);
}
}
bool VarLocBasedLDV::isSpillInstruction(const MachineInstr &MI,
MachineFunction *MF) {
if (!MI.hasOneMemOperand())
return false;
if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
return false;
return true;
}
bool VarLocBasedLDV::isLocationSpill(const MachineInstr &MI,
MachineFunction *MF, Register &Reg) {
if (!isSpillInstruction(MI, MF))
return false;
auto isKilledReg = [&](const MachineOperand MO, Register &Reg) {
if (!MO.isReg() || !MO.isUse()) {
Reg = 0;
return false;
}
Reg = MO.getReg();
return MO.isKill();
};
for (const MachineOperand &MO : MI.operands()) {
if (isKilledReg(MO, Reg))
return true;
if (Reg != 0) {
auto NextI = std::next(MI.getIterator());
if (MI.getParent()->end() == NextI)
continue;
Register RegNext;
for (const MachineOperand &MONext : NextI->operands()) {
if (isKilledReg(MONext, RegNext) && RegNext == Reg)
return true;
}
}
}
return false;
}
Optional<VarLocBasedLDV::VarLoc::SpillLoc>
VarLocBasedLDV::isRestoreInstruction(const MachineInstr &MI,
MachineFunction *MF, Register &Reg) {
if (!MI.hasOneMemOperand())
return None;
if (MI.getRestoreSize(TII)) {
Reg = MI.getOperand(0).getReg();
return extractSpillBaseRegAndOffset(MI);
}
return None;
}
void VarLocBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI,
OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs,
TransferMap &Transfers) {
MachineFunction *MF = MI.getMF();
TransferKind TKind;
Register Reg;
Optional<VarLoc::SpillLoc> Loc;
LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
VarLocsInRange KillSet;
if (isSpillInstruction(MI, MF)) {
Loc = extractSpillBaseRegAndOffset(MI);
for (uint64_t ID : OpenRanges.getSpillVarLocs()) {
LocIndex Idx = LocIndex::fromRawInteger(ID);
const VarLoc &VL = VarLocIDs[Idx];
assert(VL.containsSpillLocs() && "Broken VarLocSet?");
if (VL.usesSpillLoc(*Loc)) {
KillSet.insert(ID);
unsigned SpillLocIdx = VL.getSpillLocIdx(*Loc);
VarLoc::MachineLoc OldLoc = VL.Locs[SpillLocIdx];
VarLoc UndefVL = VarLoc::CreateCopyLoc(VL, OldLoc, 0);
LocIndices UndefLocIDs = VarLocIDs.insert(UndefVL);
Transfers.push_back({&MI, UndefLocIDs.back()});
}
}
OpenRanges.erase(KillSet, VarLocIDs, LocIndex::kSpillLocation);
}
if (isLocationSpill(MI, MF, Reg)) {
TKind = TransferKind::TransferSpill;
LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
<< "\n");
} else {
if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
return;
TKind = TransferKind::TransferRestore;
LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
<< "\n");
}
auto TransferCandidates = OpenRanges.getEmptyVarLocRange();
if (TKind == TransferKind::TransferSpill)
TransferCandidates = OpenRanges.getRegisterVarLocs(Reg);
else if (TKind == TransferKind::TransferRestore)
TransferCandidates = OpenRanges.getSpillVarLocs();
for (uint64_t ID : TransferCandidates) {
LocIndex Idx = LocIndex::fromRawInteger(ID);
const VarLoc &VL = VarLocIDs[Idx];
unsigned LocIdx;
if (TKind == TransferKind::TransferSpill) {
assert(VL.usesReg(Reg) && "Broken VarLocSet?");
LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
<< VL.Var.getVariable()->getName() << ")\n");
LocIdx = VL.getRegIdx(Reg);
} else {
assert(TKind == TransferKind::TransferRestore && VL.containsSpillLocs() &&
"Broken VarLocSet?");
if (!VL.usesSpillLoc(*Loc))
continue;
LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
<< VL.Var.getVariable()->getName() << ")\n");
LocIdx = VL.getSpillLocIdx(*Loc);
}
VarLoc::MachineLoc MLoc = VL.Locs[LocIdx];
insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx, TKind,
MLoc, Reg);
return;
}
}
void VarLocBasedLDV::transferRegisterCopy(MachineInstr &MI,
OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs,
TransferMap &Transfers) {
auto DestSrc = TII->isCopyInstr(MI);
if (!DestSrc)
return;
const MachineOperand *DestRegOp = DestSrc->Destination;
const MachineOperand *SrcRegOp = DestSrc->Source;
if (!DestRegOp->isDef())
return;
auto isCalleeSavedReg = [&](Register Reg) {
for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
if (CalleeSavedRegs.test(*RAI))
return true;
return false;
};
Register SrcReg = SrcRegOp->getReg();
Register DestReg = DestRegOp->getReg();
if (!isCalleeSavedReg(DestReg))
return;
if (isRegOtherThanSPAndFP(*DestRegOp, MI, TRI)) {
for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
LocIndex Idx = LocIndex::fromRawInteger(ID);
const VarLoc &VL = VarLocIDs[Idx];
if (VL.isEntryValueBackupReg(SrcReg)) {
LLVM_DEBUG(dbgs() << "Copy of the entry value: "; MI.dump(););
VarLoc EntryValLocCopyBackup =
VarLoc::CreateEntryCopyBackupLoc(VL.MI, LS, VL.Expr, DestReg);
OpenRanges.erase(VL);
LocIndices EntryValCopyLocIDs = VarLocIDs.insert(EntryValLocCopyBackup);
OpenRanges.insert(EntryValCopyLocIDs, EntryValLocCopyBackup);
break;
}
}
}
if (!SrcRegOp->isKill())
return;
for (uint64_t ID : OpenRanges.getRegisterVarLocs(SrcReg)) {
LocIndex Idx = LocIndex::fromRawInteger(ID);
assert(VarLocIDs[Idx].usesReg(SrcReg) && "Broken VarLocSet?");
VarLoc::MachineLocValue Loc;
Loc.RegNo = SrcReg;
VarLoc::MachineLoc MLoc{VarLoc::MachineLocKind::RegisterKind, Loc};
insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx,
TransferKind::TransferCopy, MLoc, DestReg);
return;
}
}
bool VarLocBasedLDV::transferTerminator(MachineBasicBlock *CurMBB,
OpenRangesSet &OpenRanges,
VarLocInMBB &OutLocs,
const VarLocMap &VarLocIDs) {
bool Changed = false;
LLVM_DEBUG({
VarVec VarLocs;
OpenRanges.getUniqueVarLocs(VarLocs, VarLocIDs);
for (VarLoc &VL : VarLocs) {
dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
VL.dump(TRI);
}
});
VarLocSet &VLS = getVarLocsInMBB(CurMBB, OutLocs);
Changed = VLS != OpenRanges.getVarLocs();
if (Changed)
VLS = OpenRanges.getVarLocs();
OpenRanges.clear();
return Changed;
}
void VarLocBasedLDV::accumulateFragmentMap(MachineInstr &MI,
VarToFragments &SeenFragments,
OverlapMap &OverlappingFragments) {
DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
MI.getDebugLoc()->getInlinedAt());
FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
auto SeenIt = SeenFragments.find(MIVar.getVariable());
if (SeenIt == SeenFragments.end()) {
SmallSet<FragmentInfo, 4> OneFragment;
OneFragment.insert(ThisFragment);
SeenFragments.insert({MIVar.getVariable(), OneFragment});
OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
return;
}
auto IsInOLapMap =
OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
if (!IsInOLapMap.second)
return;
auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
auto &AllSeenFragments = SeenIt->second;
for (const auto &ASeenFragment : AllSeenFragments) {
if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
ThisFragmentsOverlaps.push_back(ASeenFragment);
auto ASeenFragmentsOverlaps =
OverlappingFragments.find({MIVar.getVariable(), ASeenFragment});
assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
"Previously seen var fragment has no vector of overlaps");
ASeenFragmentsOverlaps->second.push_back(ThisFragment);
}
}
AllSeenFragments.insert(ThisFragment);
}
void VarLocBasedLDV::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs, TransferMap &Transfers,
InstToEntryLocMap &EntryValTransfers,
RegDefToInstMap &RegSetInstrs) {
if (!MI.isDebugInstr())
LastNonDbgMI = &MI;
transferDebugValue(MI, OpenRanges, VarLocIDs, EntryValTransfers,
RegSetInstrs);
transferRegisterDef(MI, OpenRanges, VarLocIDs, EntryValTransfers,
RegSetInstrs);
transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
}
bool VarLocBasedLDV::join(
MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
const VarLocMap &VarLocIDs,
SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
VarLocSet InLocsT(Alloc);
int NumVisited = 0;
for (auto *p : MBB.predecessors()) {
if (!Visited.count(p)) {
LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
<< "\n");
continue;
}
auto OL = OutLocs.find(p);
if (OL == OutLocs.end())
return false;
VarLocSet &OutLocVLS = *OL->second;
if (!NumVisited)
InLocsT = OutLocVLS;
else
InLocsT &= OutLocVLS;
LLVM_DEBUG({
if (!InLocsT.empty()) {
VarVec VarLocs;
collectAllVarLocs(VarLocs, InLocsT, VarLocIDs);
for (const VarLoc &VL : VarLocs)
dbgs() << " gathered candidate incoming var: "
<< VL.Var.getVariable()->getName() << "\n";
}
});
NumVisited++;
}
VarLocSet KillSet(Alloc);
bool IsArtificial = ArtificialBlocks.count(&MBB);
if (!IsArtificial) {
for (uint64_t ID : InLocsT) {
LocIndex Idx = LocIndex::fromRawInteger(ID);
if (!VarLocIDs[Idx].dominates(LS, MBB)) {
KillSet.set(ID);
LLVM_DEBUG({
auto Name = VarLocIDs[Idx].Var.getVariable()->getName();
dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
});
}
}
}
InLocsT.intersectWithComplement(KillSet);
assert((NumVisited || MBB.pred_empty()) &&
"Should have processed at least one predecessor");
VarLocSet &ILS = getVarLocsInMBB(&MBB, InLocs);
bool Changed = false;
if (ILS != InLocsT) {
ILS = InLocsT;
Changed = true;
}
return Changed;
}
void VarLocBasedLDV::flushPendingLocs(VarLocInMBB &PendingInLocs,
VarLocMap &VarLocIDs) {
for (auto &Iter : PendingInLocs) {
auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
VarLocSet &Pending = *Iter.second;
SmallVector<VarLoc, 32> VarLocs;
collectAllVarLocs(VarLocs, Pending, VarLocIDs);
for (VarLoc DiffIt : VarLocs) {
if (DiffIt.isEntryBackupLoc())
continue;
MachineInstr *MI = DiffIt.BuildDbgValue(*MBB.getParent());
MBB.insert(MBB.instr_begin(), MI);
(void)MI;
LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
}
}
}
bool VarLocBasedLDV::isEntryValueCandidate(
const MachineInstr &MI, const DefinedRegsSet &DefinedRegs) const {
assert(MI.isDebugValue() && "This must be DBG_VALUE.");
auto *DIVar = MI.getDebugVariable();
if (!DIVar->isParameter())
return false;
if (MI.getDebugLoc()->getInlinedAt())
return false;
if (!isRegOtherThanSPAndFP(MI.getDebugOperand(0), MI, TRI))
return false;
if (DefinedRegs.count(MI.getDebugOperand(0).getReg()))
return false;
if (MI.getDebugExpression()->getNumElements() > 0)
return false;
return true;
}
static void collectRegDefs(const MachineInstr &MI, DefinedRegsSet &Regs,
const TargetRegisterInfo *TRI) {
for (const MachineOperand &MO : MI.operands())
if (MO.isReg() && MO.isDef() && MO.getReg())
for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
Regs.insert(*AI);
}
void VarLocBasedLDV::recordEntryValue(const MachineInstr &MI,
const DefinedRegsSet &DefinedRegs,
OpenRangesSet &OpenRanges,
VarLocMap &VarLocIDs) {
if (TPC) {
auto &TM = TPC->getTM<TargetMachine>();
if (!TM.Options.ShouldEmitDebugEntryValues())
return;
}
DebugVariable V(MI.getDebugVariable(), MI.getDebugExpression(),
MI.getDebugLoc()->getInlinedAt());
if (!isEntryValueCandidate(MI, DefinedRegs) ||
OpenRanges.getEntryValueBackup(V))
return;
LLVM_DEBUG(dbgs() << "Creating the backup entry location: "; MI.dump(););
DIExpression *NewExpr =
DIExpression::prepend(MI.getDebugExpression(), DIExpression::EntryValue);
VarLoc EntryValLocAsBackup = VarLoc::CreateEntryBackupLoc(MI, LS, NewExpr);
LocIndices EntryValLocIDs = VarLocIDs.insert(EntryValLocAsBackup);
OpenRanges.insert(EntryValLocIDs, EntryValLocAsBackup);
}
bool VarLocBasedLDV::ExtendRanges(MachineFunction &MF,
MachineDominatorTree *DomTree,
TargetPassConfig *TPC, unsigned InputBBLimit,
unsigned InputDbgValLimit) {
(void)DomTree;
LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
if (!MF.getFunction().getSubprogram())
return false;
if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
DICompileUnit::NoDebug)
return false;
TRI = MF.getSubtarget().getRegisterInfo();
TII = MF.getSubtarget().getInstrInfo();
TFI = MF.getSubtarget().getFrameLowering();
TFI->getCalleeSaves(MF, CalleeSavedRegs);
this->TPC = TPC;
LS.initialize(MF);
bool Changed = false;
bool OLChanged = false;
bool MBBJoined = false;
VarLocMap VarLocIDs; OverlapMap OverlapFragments; OpenRangesSet OpenRanges(Alloc, OverlapFragments);
VarLocInMBB OutLocs; VarLocInMBB InLocs; TransferMap Transfers; InstToEntryLocMap EntryValTransfers;
RegDefToInstMap RegSetInstrs;
VarToFragments SeenFragments;
SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
std::priority_queue<unsigned int, std::vector<unsigned int>,
std::greater<unsigned int>>
Worklist;
std::priority_queue<unsigned int, std::vector<unsigned int>,
std::greater<unsigned int>>
Pending;
DefinedRegsSet DefinedRegs;
MachineBasicBlock &First_MBB = *(MF.begin());
for (auto &MI : First_MBB) {
collectRegDefs(MI, DefinedRegs, TRI);
if (MI.isDebugValue())
recordEntryValue(MI, DefinedRegs, OpenRanges, VarLocIDs);
}
for (auto &MBB : MF)
for (auto &MI : MBB)
if (MI.isDebugValue())
accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
if (const DebugLoc &DL = MI.getDebugLoc())
return DL.getLine() != 0;
return false;
};
for (auto &MBB : MF)
if (none_of(MBB.instrs(), hasNonArtificialLocation))
ArtificialBlocks.insert(&MBB);
LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
"OutLocs after initialization", dbgs()));
ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
unsigned int RPONumber = 0;
for (MachineBasicBlock *MBB : RPOT) {
OrderToBB[RPONumber] = MBB;
BBToOrder[MBB] = RPONumber;
Worklist.push(RPONumber);
++RPONumber;
}
if (RPONumber > InputBBLimit) {
unsigned NumInputDbgValues = 0;
for (auto &MBB : MF)
for (auto &MI : MBB)
if (MI.isDebugValue())
++NumInputDbgValues;
if (NumInputDbgValues > InputDbgValLimit) {
LLVM_DEBUG(dbgs() << "Disabling VarLocBasedLDV: " << MF.getName()
<< " has " << RPONumber << " basic blocks and "
<< NumInputDbgValues
<< " input DBG_VALUEs, exceeding limits.\n");
return false;
}
}
SmallPtrSet<const MachineBasicBlock *, 16> Visited;
while (!Worklist.empty() || !Pending.empty()) {
SmallPtrSet<MachineBasicBlock *, 16> OnPending;
LLVM_DEBUG(dbgs() << "Processing Worklist\n");
while (!Worklist.empty()) {
MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
Worklist.pop();
MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
ArtificialBlocks);
MBBJoined |= Visited.insert(MBB).second;
if (MBBJoined) {
MBBJoined = false;
Changed = true;
OpenRanges.insertFromLocSet(getVarLocsInMBB(MBB, InLocs), VarLocIDs);
LastNonDbgMI = nullptr;
RegSetInstrs.clear();
for (auto &MI : *MBB)
process(MI, OpenRanges, VarLocIDs, Transfers, EntryValTransfers,
RegSetInstrs);
OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
"OutLocs after propagating", dbgs()));
LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
"InLocs after propagating", dbgs()));
if (OLChanged) {
OLChanged = false;
for (auto *s : MBB->successors())
if (OnPending.insert(s).second) {
Pending.push(BBToOrder[s]);
}
}
}
}
Worklist.swap(Pending);
assert(Pending.empty() && "Pending should be empty");
}
for (auto &TR : Transfers) {
assert(!TR.TransferInst->isTerminator() &&
"Cannot insert DBG_VALUE after terminator");
MachineBasicBlock *MBB = TR.TransferInst->getParent();
const VarLoc &VL = VarLocIDs[TR.LocationID];
MachineInstr *MI = VL.BuildDbgValue(MF);
MBB->insertAfterBundle(TR.TransferInst->getIterator(), MI);
}
Transfers.clear();
for (auto &TR : EntryValTransfers) {
MachineInstr *TRInst = const_cast<MachineInstr *>(TR.first);
assert(!TRInst->isTerminator() &&
"Cannot insert DBG_VALUE after terminator");
MachineBasicBlock *MBB = TRInst->getParent();
const VarLoc &VL = VarLocIDs[TR.second];
MachineInstr *MI = VL.BuildDbgValue(MF);
MBB->insertAfterBundle(TRInst->getIterator(), MI);
}
EntryValTransfers.clear();
flushPendingLocs(InLocs, VarLocIDs);
LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
return Changed;
}
LDVImpl *
llvm::makeVarLocBasedLiveDebugValues()
{
return new VarLocBasedLDV();
}