ExecutionDepsFix.cpp [plain text]
#include "llvm/CodeGen/Passes.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/CodeGen/LivePhysRegs.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;
#define DEBUG_TYPE "execution-fix"
namespace {
struct DomainValue {
unsigned Refs;
unsigned AvailableDomains;
DomainValue *Next;
SmallVector<MachineInstr*, 8> Instrs;
bool isCollapsed() const { return Instrs.empty(); }
bool hasDomain(unsigned domain) const {
assert(domain <
static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
"undefined behavior");
return AvailableDomains & (1u << domain);
}
void addDomain(unsigned domain) {
AvailableDomains |= 1u << domain;
}
void setSingleDomain(unsigned domain) {
AvailableDomains = 1u << domain;
}
unsigned getCommonDomains(unsigned mask) const {
return AvailableDomains & mask;
}
unsigned getFirstDomain() const {
return countTrailingZeros(AvailableDomains);
}
DomainValue() : Refs(0) { clear(); }
void clear() {
AvailableDomains = 0;
Next = nullptr;
Instrs.clear();
}
};
}
namespace {
struct LiveReg {
DomainValue *Value;
int Def;
};
}
namespace {
class ExeDepsFix : public MachineFunctionPass {
static char ID;
SpecificBumpPtrAllocator<DomainValue> Allocator;
SmallVector<DomainValue*,16> Avail;
const TargetRegisterClass *const RC;
MachineFunction *MF;
const TargetInstrInfo *TII;
const TargetRegisterInfo *TRI;
std::vector<SmallVector<int, 1>> AliasMap;
const unsigned NumRegs;
LiveReg *LiveRegs;
typedef DenseMap<MachineBasicBlock*, LiveReg*> LiveOutMap;
LiveOutMap LiveOuts;
std::vector<std::pair<MachineInstr*, unsigned> > UndefReads;
LivePhysRegs LiveRegSet;
int CurInstr;
bool SeenUnknownBackEdge;
public:
ExeDepsFix(const TargetRegisterClass *rc)
: MachineFunctionPass(ID), RC(rc), NumRegs(RC->getNumRegs()) {}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &MF) override;
const char *getPassName() const override {
return "Execution dependency fix";
}
private:
iterator_range<SmallVectorImpl<int>::const_iterator>
regIndices(unsigned Reg) const;
DomainValue *alloc(int domain = -1);
DomainValue *retain(DomainValue *DV) {
if (DV) ++DV->Refs;
return DV;
}
void release(DomainValue*);
DomainValue *resolve(DomainValue*&);
void setLiveReg(int rx, DomainValue *DV);
void kill(int rx);
void force(int rx, unsigned domain);
void collapse(DomainValue *dv, unsigned domain);
bool merge(DomainValue *A, DomainValue *B);
void enterBasicBlock(MachineBasicBlock*);
void leaveBasicBlock(MachineBasicBlock*);
void visitInstr(MachineInstr*);
void processDefs(MachineInstr*, bool Kill);
void visitSoftInstr(MachineInstr*, unsigned mask);
void visitHardInstr(MachineInstr*, unsigned domain);
bool shouldBreakDependence(MachineInstr*, unsigned OpIdx, unsigned Pref);
void processUndefReads(MachineBasicBlock*);
};
}
char ExeDepsFix::ID = 0;
iterator_range<SmallVectorImpl<int>::const_iterator>
ExeDepsFix::regIndices(unsigned Reg) const {
assert(Reg < AliasMap.size() && "Invalid register");
const auto &Entry = AliasMap[Reg];
return make_range(Entry.begin(), Entry.end());
}
DomainValue *ExeDepsFix::alloc(int domain) {
DomainValue *dv = Avail.empty() ?
new(Allocator.Allocate()) DomainValue :
Avail.pop_back_val();
if (domain >= 0)
dv->addDomain(domain);
assert(dv->Refs == 0 && "Reference count wasn't cleared");
assert(!dv->Next && "Chained DomainValue shouldn't have been recycled");
return dv;
}
void ExeDepsFix::release(DomainValue *DV) {
while (DV) {
assert(DV->Refs && "Bad DomainValue");
if (--DV->Refs)
return;
if (DV->AvailableDomains && !DV->isCollapsed())
collapse(DV, DV->getFirstDomain());
DomainValue *Next = DV->Next;
DV->clear();
Avail.push_back(DV);
DV = Next;
}
}
DomainValue *ExeDepsFix::resolve(DomainValue *&DVRef) {
DomainValue *DV = DVRef;
if (!DV || !DV->Next)
return DV;
do DV = DV->Next;
while (DV->Next);
retain(DV);
release(DVRef);
DVRef = DV;
return DV;
}
void ExeDepsFix::setLiveReg(int rx, DomainValue *dv) {
assert(unsigned(rx) < NumRegs && "Invalid index");
assert(LiveRegs && "Must enter basic block first.");
if (LiveRegs[rx].Value == dv)
return;
if (LiveRegs[rx].Value)
release(LiveRegs[rx].Value);
LiveRegs[rx].Value = retain(dv);
}
void ExeDepsFix::kill(int rx) {
assert(unsigned(rx) < NumRegs && "Invalid index");
assert(LiveRegs && "Must enter basic block first.");
if (!LiveRegs[rx].Value)
return;
release(LiveRegs[rx].Value);
LiveRegs[rx].Value = nullptr;
}
void ExeDepsFix::force(int rx, unsigned domain) {
assert(unsigned(rx) < NumRegs && "Invalid index");
assert(LiveRegs && "Must enter basic block first.");
if (DomainValue *dv = LiveRegs[rx].Value) {
if (dv->isCollapsed())
dv->addDomain(domain);
else if (dv->hasDomain(domain))
collapse(dv, domain);
else {
collapse(dv, dv->getFirstDomain());
assert(LiveRegs[rx].Value && "Not live after collapse?");
LiveRegs[rx].Value->addDomain(domain);
}
} else {
setLiveReg(rx, alloc(domain));
}
}
void ExeDepsFix::collapse(DomainValue *dv, unsigned domain) {
assert(dv->hasDomain(domain) && "Cannot collapse");
while (!dv->Instrs.empty())
TII->setExecutionDomain(dv->Instrs.pop_back_val(), domain);
dv->setSingleDomain(domain);
if (LiveRegs && dv->Refs > 1)
for (unsigned rx = 0; rx != NumRegs; ++rx)
if (LiveRegs[rx].Value == dv)
setLiveReg(rx, alloc(domain));
}
bool ExeDepsFix::merge(DomainValue *A, DomainValue *B) {
assert(!A->isCollapsed() && "Cannot merge into collapsed");
assert(!B->isCollapsed() && "Cannot merge from collapsed");
if (A == B)
return true;
unsigned common = A->getCommonDomains(B->AvailableDomains);
if (!common)
return false;
A->AvailableDomains = common;
A->Instrs.append(B->Instrs.begin(), B->Instrs.end());
B->clear();
B->Next = retain(A);
for (unsigned rx = 0; rx != NumRegs; ++rx) {
assert(LiveRegs && "no space allocated for live registers");
if (LiveRegs[rx].Value == B)
setLiveReg(rx, A);
}
return true;
}
void ExeDepsFix::enterBasicBlock(MachineBasicBlock *MBB) {
SeenUnknownBackEdge = false;
CurInstr = 0;
UndefReads.clear();
LiveRegSet.clear();
if (!LiveRegs)
LiveRegs = new LiveReg[NumRegs];
for (unsigned rx = 0; rx != NumRegs; ++rx) {
LiveRegs[rx].Value = nullptr;
LiveRegs[rx].Def = -(1 << 20);
}
if (MBB->pred_empty()) {
for (const auto &LI : MBB->liveins()) {
for (int rx : regIndices(LI.PhysReg)) {
LiveRegs[rx].Def = -1;
}
}
DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": entry\n");
return;
}
for (MachineBasicBlock::const_pred_iterator pi = MBB->pred_begin(),
pe = MBB->pred_end(); pi != pe; ++pi) {
LiveOutMap::const_iterator fi = LiveOuts.find(*pi);
if (fi == LiveOuts.end()) {
SeenUnknownBackEdge = true;
continue;
}
assert(fi->second && "Can't have NULL entries");
for (unsigned rx = 0; rx != NumRegs; ++rx) {
LiveRegs[rx].Def = std::max(LiveRegs[rx].Def, fi->second[rx].Def);
DomainValue *pdv = resolve(fi->second[rx].Value);
if (!pdv)
continue;
if (!LiveRegs[rx].Value) {
setLiveReg(rx, pdv);
continue;
}
if (LiveRegs[rx].Value->isCollapsed()) {
unsigned Domain = LiveRegs[rx].Value->getFirstDomain();
if (!pdv->isCollapsed() && pdv->hasDomain(Domain))
collapse(pdv, Domain);
continue;
}
if (!pdv->isCollapsed())
merge(LiveRegs[rx].Value, pdv);
else
force(rx, pdv->getFirstDomain());
}
}
DEBUG(dbgs() << "BB#" << MBB->getNumber()
<< (SeenUnknownBackEdge ? ": incomplete\n" : ": all preds known\n"));
}
void ExeDepsFix::leaveBasicBlock(MachineBasicBlock *MBB) {
assert(LiveRegs && "Must enter basic block first.");
bool First = LiveOuts.insert(std::make_pair(MBB, LiveRegs)).second;
if (First) {
for (unsigned i = 0, e = NumRegs; i != e; ++i)
LiveRegs[i].Def -= CurInstr;
} else {
for (unsigned i = 0, e = NumRegs; i != e; ++i)
release(LiveRegs[i].Value);
delete[] LiveRegs;
}
LiveRegs = nullptr;
}
void ExeDepsFix::visitInstr(MachineInstr *MI) {
if (MI->isDebugValue())
return;
std::pair<uint16_t, uint16_t> DomP = TII->getExecutionDomain(MI);
if (DomP.first) {
if (DomP.second)
visitSoftInstr(MI, DomP.second);
else
visitHardInstr(MI, DomP.first);
}
processDefs(MI, !DomP.first);
}
bool ExeDepsFix::shouldBreakDependence(MachineInstr *MI, unsigned OpIdx,
unsigned Pref) {
unsigned reg = MI->getOperand(OpIdx).getReg();
for (int rx : regIndices(reg)) {
unsigned Clearance = CurInstr - LiveRegs[rx].Def;
DEBUG(dbgs() << "Clearance: " << Clearance << ", want " << Pref);
if (Pref > Clearance) {
DEBUG(dbgs() << ": Break dependency.\n");
continue;
}
if (!SeenUnknownBackEdge || Pref <= unsigned(CurInstr)) {
DEBUG(dbgs() << ": OK .\n");
return false;
}
DEBUG(dbgs() << ": Wait for back-edge to resolve.\n");
return false;
}
return true;
}
void ExeDepsFix::processDefs(MachineInstr *MI, bool Kill) {
assert(!MI->isDebugValue() && "Won't process debug values");
unsigned OpNum;
unsigned Pref = TII->getUndefRegClearance(MI, OpNum, TRI);
if (Pref) {
if (shouldBreakDependence(MI, OpNum, Pref))
UndefReads.push_back(std::make_pair(MI, OpNum));
}
const MCInstrDesc &MCID = MI->getDesc();
for (unsigned i = 0,
e = MI->isVariadic() ? MI->getNumOperands() : MCID.getNumDefs();
i != e; ++i) {
MachineOperand &MO = MI->getOperand(i);
if (!MO.isReg())
continue;
if (MO.isImplicit())
break;
if (MO.isUse())
continue;
for (int rx : regIndices(MO.getReg())) {
DEBUG(dbgs() << TRI->getName(RC->getRegister(rx)) << ":\t" << CurInstr
<< '\t' << *MI);
unsigned Pref = TII->getPartialRegUpdateClearance(MI, i, TRI);
if (Pref && shouldBreakDependence(MI, i, Pref))
TII->breakPartialRegDependency(MI, i, TRI);
LiveRegs[rx].Def = CurInstr;
if (Kill)
kill(rx);
}
}
++CurInstr;
}
void ExeDepsFix::processUndefReads(MachineBasicBlock *MBB) {
if (UndefReads.empty())
return;
LiveRegSet.init(TRI);
LiveRegSet.addLiveOuts(MBB);
MachineInstr *UndefMI = UndefReads.back().first;
unsigned OpIdx = UndefReads.back().second;
for (MachineInstr &I : make_range(MBB->rbegin(), MBB->rend())) {
LiveRegSet.stepBackward(I);
if (UndefMI == &I) {
if (!LiveRegSet.contains(UndefMI->getOperand(OpIdx).getReg()))
TII->breakPartialRegDependency(UndefMI, OpIdx, TRI);
UndefReads.pop_back();
if (UndefReads.empty())
return;
UndefMI = UndefReads.back().first;
OpIdx = UndefReads.back().second;
}
}
}
void ExeDepsFix::visitHardInstr(MachineInstr *mi, unsigned domain) {
for (unsigned i = mi->getDesc().getNumDefs(),
e = mi->getDesc().getNumOperands(); i != e; ++i) {
MachineOperand &mo = mi->getOperand(i);
if (!mo.isReg()) continue;
for (int rx : regIndices(mo.getReg())) {
force(rx, domain);
}
}
for (unsigned i = 0, e = mi->getDesc().getNumDefs(); i != e; ++i) {
MachineOperand &mo = mi->getOperand(i);
if (!mo.isReg()) continue;
for (int rx : regIndices(mo.getReg())) {
kill(rx);
force(rx, domain);
}
}
}
void ExeDepsFix::visitSoftInstr(MachineInstr *mi, unsigned mask) {
unsigned available = mask;
SmallVector<int, 4> used;
if (LiveRegs)
for (unsigned i = mi->getDesc().getNumDefs(),
e = mi->getDesc().getNumOperands(); i != e; ++i) {
MachineOperand &mo = mi->getOperand(i);
if (!mo.isReg()) continue;
for (int rx : regIndices(mo.getReg())) {
DomainValue *dv = LiveRegs[rx].Value;
if (dv == nullptr)
continue;
unsigned common = dv->getCommonDomains(available);
if (dv->isCollapsed()) {
if (common) available = common;
} else if (common)
used.push_back(rx);
else
kill(rx);
}
}
if (isPowerOf2_32(available)) {
unsigned domain = countTrailingZeros(available);
TII->setExecutionDomain(mi, domain);
visitHardInstr(mi, domain);
return;
}
SmallVector<LiveReg, 4> Regs;
for (SmallVectorImpl<int>::iterator i=used.begin(), e=used.end(); i!=e; ++i) {
int rx = *i;
assert(LiveRegs && "no space allocated for live registers");
const LiveReg &LR = LiveRegs[rx];
if (!LR.Value->getCommonDomains(available)) {
kill(rx);
continue;
}
bool Inserted = false;
for (SmallVectorImpl<LiveReg>::iterator i = Regs.begin(), e = Regs.end();
i != e && !Inserted; ++i) {
if (LR.Def < i->Def) {
Inserted = true;
Regs.insert(i, LR);
}
}
if (!Inserted)
Regs.push_back(LR);
}
DomainValue *dv = nullptr;
while (!Regs.empty()) {
if (!dv) {
dv = Regs.pop_back_val().Value;
dv->AvailableDomains = dv->getCommonDomains(available);
assert(dv->AvailableDomains && "Domain should have been filtered");
continue;
}
DomainValue *Latest = Regs.pop_back_val().Value;
if (Latest == dv || Latest->Next)
continue;
if (merge(dv, Latest))
continue;
for (int i : used) {
assert(LiveRegs && "no space allocated for live registers");
if (LiveRegs[i].Value == Latest)
kill(i);
}
}
if (!dv) {
dv = alloc();
dv->AvailableDomains = available;
}
dv->Instrs.push_back(mi);
for (MachineInstr::mop_iterator ii = mi->operands_begin(),
ee = mi->operands_end();
ii != ee; ++ii) {
MachineOperand &mo = *ii;
if (!mo.isReg()) continue;
for (int rx : regIndices(mo.getReg())) {
if (!LiveRegs[rx].Value || (mo.isDef() && LiveRegs[rx].Value != dv)) {
kill(rx);
setLiveReg(rx, dv);
}
}
}
}
bool ExeDepsFix::runOnMachineFunction(MachineFunction &mf) {
MF = &mf;
TII = MF->getSubtarget().getInstrInfo();
TRI = MF->getSubtarget().getRegisterInfo();
LiveRegs = nullptr;
assert(NumRegs == RC->getNumRegs() && "Bad regclass");
DEBUG(dbgs() << "********** FIX EXECUTION DEPENDENCIES: "
<< TRI->getRegClassName(RC) << " **********\n");
bool anyregs = false;
const MachineRegisterInfo &MRI = mf.getRegInfo();
for (unsigned Reg : *RC) {
if (MRI.isPhysRegUsed(Reg)) {
anyregs = true;
break;
}
}
if (!anyregs) return false;
if (AliasMap.empty()) {
AliasMap.resize(TRI->getNumRegs());
for (unsigned i = 0, e = RC->getNumRegs(); i != e; ++i)
for (MCRegAliasIterator AI(RC->getRegister(i), TRI, true);
AI.isValid(); ++AI)
AliasMap[*AI].push_back(i);
}
MachineBasicBlock *Entry = &*MF->begin();
ReversePostOrderTraversal<MachineBasicBlock*> RPOT(Entry);
SmallVector<MachineBasicBlock*, 16> Loops;
for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
MBBI = RPOT.begin(), MBBE = RPOT.end(); MBBI != MBBE; ++MBBI) {
MachineBasicBlock *MBB = *MBBI;
enterBasicBlock(MBB);
if (SeenUnknownBackEdge)
Loops.push_back(MBB);
for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
++I)
visitInstr(I);
processUndefReads(MBB);
leaveBasicBlock(MBB);
}
for (unsigned i = 0, e = Loops.size(); i != e; ++i) {
MachineBasicBlock *MBB = Loops[i];
enterBasicBlock(MBB);
for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
++I)
if (!I->isDebugValue())
processDefs(I, false);
processUndefReads(MBB);
leaveBasicBlock(MBB);
}
for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
MBBI = RPOT.begin(), MBBE = RPOT.end(); MBBI != MBBE; ++MBBI) {
LiveOutMap::const_iterator FI = LiveOuts.find(*MBBI);
if (FI == LiveOuts.end() || !FI->second)
continue;
for (unsigned i = 0, e = NumRegs; i != e; ++i)
if (FI->second[i].Value)
release(FI->second[i].Value);
delete[] FI->second;
}
LiveOuts.clear();
UndefReads.clear();
Avail.clear();
Allocator.DestroyAll();
return false;
}
FunctionPass *
llvm::createExecutionDependencyFixPass(const TargetRegisterClass *RC) {
return new ExeDepsFix(RC);
}