#define DEBUG_TYPE "regalloc"
#include "PBQP.h"
#include "VirtRegMap.h"
#include "VirtRegRewriter.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/CodeGen/LiveStackAnalysis.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/RegisterCoalescer.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <vector>
using namespace llvm;
static RegisterRegAlloc
registerPBQPRepAlloc("pbqp", "PBQP register allocator",
createPBQPRegisterAllocator);
namespace {
class VISIBILITY_HIDDEN PBQPRegAlloc : public MachineFunctionPass {
public:
static char ID;
PBQPRegAlloc() : MachineFunctionPass((intptr_t)&ID) {}
virtual const char* getPassName() const throw() {
return "PBQP Register Allocator";
}
virtual void getAnalysisUsage(AnalysisUsage &au) const {
au.addRequired<LiveIntervals>();
au.addRequiredTransitive<RegisterCoalescer>();
au.addRequired<LiveStacks>();
au.addPreserved<LiveStacks>();
au.addRequired<MachineLoopInfo>();
au.addPreserved<MachineLoopInfo>();
au.addRequired<VirtRegMap>();
MachineFunctionPass::getAnalysisUsage(au);
}
virtual bool runOnMachineFunction(MachineFunction &MF);
private:
typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
typedef std::vector<const LiveInterval*> Node2LIMap;
typedef std::vector<unsigned> AllowedSet;
typedef std::vector<AllowedSet> AllowedSetMap;
typedef std::set<unsigned> RegSet;
typedef std::pair<unsigned, unsigned> RegPair;
typedef std::map<RegPair, PBQPNum> CoalesceMap;
typedef std::set<LiveInterval*> LiveIntervalSet;
MachineFunction *mf;
const TargetMachine *tm;
const TargetRegisterInfo *tri;
const TargetInstrInfo *tii;
const MachineLoopInfo *loopInfo;
MachineRegisterInfo *mri;
LiveIntervals *lis;
LiveStacks *lss;
VirtRegMap *vrm;
LI2NodeMap li2Node;
Node2LIMap node2LI;
AllowedSetMap allowedSets;
LiveIntervalSet vregIntervalsToAlloc,
emptyVRegIntervals;
template <typename RegContainer>
PBQPVector* buildCostVector(unsigned vReg,
const RegContainer &allowed,
const CoalesceMap &cealesces,
PBQPNum spillCost) const;
template <typename RegContainer>
PBQPMatrix* buildInterferenceMatrix(const RegContainer &allowed1,
const RegContainer &allowed2) const;
template <typename RegContainer>
PBQPMatrix* buildCoalescingMatrix(const RegContainer &allowed1,
const RegContainer &allowed2,
PBQPNum cBenefit) const;
CoalesceMap findCoalesces();
void findVRegIntervalsToAlloc();
pbqp* constructPBQPProblem();
void addStackInterval(const LiveInterval *spilled,MachineRegisterInfo* mri);
bool mapPBQPToRegAlloc(pbqp *problem);
void finalizeAlloc() const;
};
char PBQPRegAlloc::ID = 0;
}
template <typename RegContainer>
PBQPVector* PBQPRegAlloc::buildCostVector(unsigned vReg,
const RegContainer &allowed,
const CoalesceMap &coalesces,
PBQPNum spillCost) const {
typedef typename RegContainer::const_iterator AllowedItr;
PBQPVector *v = new PBQPVector(allowed.size() + 1);
(*v)[0] = spillCost;
unsigned ai = 0;
for (AllowedItr itr = allowed.begin(), end = allowed.end();
itr != end; ++itr, ++ai) {
unsigned pReg = *itr;
CoalesceMap::const_iterator cmItr =
coalesces.find(RegPair(vReg, pReg));
if (cmItr == coalesces.end())
continue;
(*v)[ai + 1] = -cmItr->second;
}
return v;
}
template <typename RegContainer>
PBQPMatrix* PBQPRegAlloc::buildInterferenceMatrix(
const RegContainer &allowed1, const RegContainer &allowed2) const {
typedef typename RegContainer::const_iterator RegContainerIterator;
PBQPMatrix *m = new PBQPMatrix(allowed1.size() + 1, allowed2.size() + 1);
bool isZeroMatrix = true;
unsigned ri = 1;
for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
a1Itr != a1End; ++a1Itr) {
unsigned ci = 1;
unsigned reg1 = *a1Itr;
for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
a2Itr != a2End; ++a2Itr) {
unsigned reg2 = *a2Itr;
if ((reg1 == reg2) || tri->areAliases(reg1, reg2)) {
(*m)[ri][ci] = std::numeric_limits<PBQPNum>::infinity();
isZeroMatrix = false;
}
++ci;
}
++ri;
}
if (isZeroMatrix) {
delete m;
return 0;
}
return m;
}
template <typename RegContainer>
PBQPMatrix* PBQPRegAlloc::buildCoalescingMatrix(
const RegContainer &allowed1, const RegContainer &allowed2,
PBQPNum cBenefit) const {
typedef typename RegContainer::const_iterator RegContainerIterator;
PBQPMatrix *m = new PBQPMatrix(allowed1.size() + 1, allowed2.size() + 1);
m->reset(0);
bool isZeroMatrix = true;
unsigned ri = 1;
for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
a1Itr != a1End; ++a1Itr) {
unsigned ci = 1;
unsigned reg1 = *a1Itr;
for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
a2Itr != a2End; ++a2Itr) {
if (reg1 == *a2Itr) {
(*m)[ri][ci] = -cBenefit;
isZeroMatrix = false;
}
++ci;
}
++ri;
}
if (isZeroMatrix) {
delete m;
return 0;
}
return m;
}
PBQPRegAlloc::CoalesceMap PBQPRegAlloc::findCoalesces() {
typedef MachineFunction::const_iterator MFIterator;
typedef MachineBasicBlock::const_iterator MBBIterator;
typedef LiveInterval::const_vni_iterator VNIIterator;
CoalesceMap coalescesFound;
for (MFIterator bbItr = mf->begin(), bbEnd = mf->end();
bbItr != bbEnd; ++bbItr) {
const MachineBasicBlock *mbb = &*bbItr;
for (MBBIterator iItr = mbb->begin(), iEnd = mbb->end();
iItr != iEnd; ++iItr) {
const MachineInstr *instr = &*iItr;
unsigned srcReg, dstReg, srcSubReg, dstSubReg;
if (!tii->isMoveInstr(*instr, srcReg, dstReg, srcSubReg, dstSubReg))
continue;
if (dstReg == srcReg)
continue;
bool srcRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(srcReg),
dstRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(dstReg);
if (srcRegIsPhysical && dstRegIsPhysical)
continue;
const TargetRegisterClass *srcRegClass = srcRegIsPhysical ?
tri->getPhysicalRegisterRegClass(srcReg) : mri->getRegClass(srcReg);
const TargetRegisterClass *dstRegClass = dstRegIsPhysical ?
tri->getPhysicalRegisterRegClass(dstReg) : mri->getRegClass(dstReg);
if (srcRegClass != dstRegClass)
continue;
if (srcRegIsPhysical) {
if (std::find(srcRegClass->allocation_order_begin(*mf),
srcRegClass->allocation_order_end(*mf), srcReg) ==
srcRegClass->allocation_order_end(*mf))
continue;
}
if (dstRegIsPhysical) {
if (std::find(dstRegClass->allocation_order_begin(*mf),
dstRegClass->allocation_order_end(*mf), dstReg) ==
dstRegClass->allocation_order_end(*mf))
continue;
}
const LiveInterval *srcLI = &lis->getInterval(srcReg),
*dstLI = &lis->getInterval(dstReg);
if (srcLI->overlaps(*dstLI)) {
bool badDef = false;
for (VNIIterator
vniItr = srcLI->vni_begin(), vniEnd = srcLI->vni_end();
vniItr != vniEnd; ++vniItr) {
if (dstLI->liveAt((*vniItr)->def)) {
badDef = true;
break;
}
}
if (badDef)
continue;
for (VNIIterator
vniItr = dstLI->vni_begin(), vniEnd = dstLI->vni_end();
vniItr != vniEnd; ++vniItr) {
if ((*vniItr)->copy == instr)
continue;
if (srcLI->liveAt((*vniItr)->def)) {
badDef = true;
break;
}
}
if (badDef)
continue;
}
float cBenefit = powf(10.0f, loopInfo->getLoopDepth(mbb)) / 5.0;
coalescesFound[RegPair(srcReg, dstReg)] = cBenefit;
coalescesFound[RegPair(dstReg, srcReg)] = cBenefit;
}
}
return coalescesFound;
}
void PBQPRegAlloc::findVRegIntervalsToAlloc() {
for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
itr != end; ++itr) {
if (TargetRegisterInfo::isPhysicalRegister(itr->first))
continue;
LiveInterval *li = itr->second;
if (!li->empty()) {
vregIntervalsToAlloc.insert(li);
}
else {
emptyVRegIntervals.insert(li);
}
}
}
pbqp* PBQPRegAlloc::constructPBQPProblem() {
typedef std::vector<const LiveInterval*> LIVector;
typedef std::vector<unsigned> RegVector;
LIVector physIntervals;
li2Node.clear();
node2LI.clear();
allowedSets.clear();
for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
itr != end; ++itr) {
if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
physIntervals.push_back(itr->second);
mri->setPhysRegUsed(itr->second->reg);
}
}
for (LiveIntervalSet::const_iterator
itr = vregIntervalsToAlloc.begin(), end = vregIntervalsToAlloc.end();
itr != end; ++itr) {
const LiveInterval *li = *itr;
li2Node[li] = node2LI.size();
node2LI.push_back(li);
}
CoalesceMap coalesces(findCoalesces());
pbqp *solver = alloc_pbqp(vregIntervalsToAlloc.size());
allowedSets.resize(vregIntervalsToAlloc.size());
for (unsigned node = 0; node < node2LI.size(); ++node) {
const LiveInterval *li = node2LI[node];
const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
RegVector liAllowed(liRC->allocation_order_begin(*mf),
liRC->allocation_order_end(*mf));
for (LIVector::iterator pItr = physIntervals.begin(),
pEnd = physIntervals.end(); pItr != pEnd; ++pItr) {
if (!li->overlaps(**pItr))
continue;
unsigned pReg = (*pItr)->reg;
if (coalesces.find(RegPair(li->reg, pReg)) != coalesces.end())
continue;
RegVector::iterator eraseItr =
std::find(liAllowed.begin(), liAllowed.end(), pReg);
if (eraseItr != liAllowed.end())
liAllowed.erase(eraseItr);
const unsigned *aliasItr = tri->getAliasSet(pReg);
if (aliasItr != 0) {
for (; *aliasItr != 0; ++aliasItr) {
RegVector::iterator eraseItr =
std::find(liAllowed.begin(), liAllowed.end(), *aliasItr);
if (eraseItr != liAllowed.end()) {
liAllowed.erase(eraseItr);
}
}
}
}
allowedSets[node] = AllowedSet(liAllowed.begin(), liAllowed.end());
PBQPNum spillCost = (li->weight != 0.0) ?
li->weight : std::numeric_limits<PBQPNum>::min();
add_pbqp_nodecosts(solver, node,
buildCostVector(li->reg, allowedSets[node], coalesces,
spillCost));
}
for (unsigned node1 = 0; node1 < node2LI.size(); ++node1) {
const LiveInterval *li = node2LI[node1];
for (unsigned node2 = node1 + 1; node2 < node2LI.size(); ++node2) {
const LiveInterval *li2 = node2LI[node2];
CoalesceMap::const_iterator cmItr =
coalesces.find(RegPair(li->reg, li2->reg));
PBQPMatrix *m = 0;
if (cmItr != coalesces.end()) {
m = buildCoalescingMatrix(allowedSets[node1], allowedSets[node2],
cmItr->second);
}
else if (li->overlaps(*li2)) {
m = buildInterferenceMatrix(allowedSets[node1], allowedSets[node2]);
}
if (m != 0) {
add_pbqp_edgecosts(solver, node1, node2, m);
delete m;
}
}
}
return solver;
}
void PBQPRegAlloc::addStackInterval(const LiveInterval *spilled,
MachineRegisterInfo* mri) {
int stackSlot = vrm->getStackSlot(spilled->reg);
if (stackSlot == VirtRegMap::NO_STACK_SLOT)
return;
const TargetRegisterClass *RC = mri->getRegClass(spilled->reg);
LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot, RC);
VNInfo *vni;
if (stackInterval.getNumValNums() != 0)
vni = stackInterval.getValNumInfo(0);
else
vni = stackInterval.getNextValue(-0U, 0, lss->getVNInfoAllocator());
LiveInterval &rhsInterval = lis->getInterval(spilled->reg);
stackInterval.MergeRangesInAsValue(rhsInterval, vni);
}
bool PBQPRegAlloc::mapPBQPToRegAlloc(pbqp *problem) {
bool anotherRoundNeeded = false;
vrm->clearAllVirt();
for (unsigned node = 0; node < node2LI.size(); ++node) {
unsigned virtReg = node2LI[node]->reg,
allocSelection = get_pbqp_solution(problem, node);
if (allocSelection != 0) {
unsigned physReg = allowedSets[node][allocSelection - 1];
DOUT << "VREG " << virtReg << " -> " << tri->getName(physReg) << "\n";
assert(physReg != 0);
vrm->assignVirt2Phys(virtReg, physReg);
}
else {
vregIntervalsToAlloc.erase(&lis->getInterval(virtReg));
const LiveInterval *spillInterval = node2LI[node];
double oldSpillWeight = spillInterval->weight;
SmallVector<LiveInterval*, 8> spillIs;
std::vector<LiveInterval*> newSpills =
lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
addStackInterval(spillInterval, mri);
DOUT << "VREG " << virtReg << " -> SPILLED (Cost: "
<< oldSpillWeight << ", New vregs: ";
for (std::vector<LiveInterval*>::const_iterator
itr = newSpills.begin(), end = newSpills.end();
itr != end; ++itr) {
assert(!(*itr)->empty() && "Empty spill range.");
DOUT << (*itr)->reg << " ";
vregIntervalsToAlloc.insert(*itr);
}
DOUT << ")\n";
anotherRoundNeeded |= !newSpills.empty();
}
}
return !anotherRoundNeeded;
}
void PBQPRegAlloc::finalizeAlloc() const {
typedef LiveIntervals::iterator LIIterator;
typedef LiveInterval::Ranges::const_iterator LRIterator;
for (LiveIntervalSet::const_iterator
itr = emptyVRegIntervals.begin(), end = emptyVRegIntervals.end();
itr != end; ++itr) {
LiveInterval *li = *itr;
unsigned physReg = li->preference;
if (physReg == 0) {
const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
physReg = *liRC->allocation_order_begin(*mf);
}
vrm->assignVirt2Phys(li->reg, physReg);
}
SmallVector<MachineBasicBlock*, 8> liveInMBBs;
MachineBasicBlock *entryMBB = &*mf->begin();
for (LIIterator liItr = lis->begin(), liEnd = lis->end();
liItr != liEnd; ++liItr) {
const LiveInterval *li = liItr->second;
unsigned reg = 0;
if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
reg = li->reg;
}
else if (vrm->isAssignedReg(li->reg)) {
reg = vrm->getPhys(li->reg);
}
else {
continue;
}
for (LRIterator lrItr = li->begin(), lrEnd = li->end();
lrItr != lrEnd; ++lrItr) {
if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
for (unsigned i = 0; i < liveInMBBs.size(); ++i) {
if (liveInMBBs[i] != entryMBB) {
if (!liveInMBBs[i]->isLiveIn(reg)) {
liveInMBBs[i]->addLiveIn(reg);
}
}
}
liveInMBBs.clear();
}
}
}
}
bool PBQPRegAlloc::runOnMachineFunction(MachineFunction &MF) {
mf = &MF;
tm = &mf->getTarget();
tri = tm->getRegisterInfo();
tii = tm->getInstrInfo();
mri = &mf->getRegInfo();
lis = &getAnalysis<LiveIntervals>();
lss = &getAnalysis<LiveStacks>();
loopInfo = &getAnalysis<MachineLoopInfo>();
vrm = &getAnalysis<VirtRegMap>();
DOUT << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n";
findVRegIntervalsToAlloc();
if (vregIntervalsToAlloc.empty() && emptyVRegIntervals.empty())
return true;
if (!vregIntervalsToAlloc.empty()) {
bool pbqpAllocComplete = false;
unsigned round = 0;
while (!pbqpAllocComplete) {
DOUT << " PBQP Regalloc round " << round << ":\n";
pbqp *problem = constructPBQPProblem();
solve_pbqp(problem);
pbqpAllocComplete = mapPBQPToRegAlloc(problem);
free_pbqp(problem);
++round;
}
}
finalizeAlloc();
vregIntervalsToAlloc.clear();
emptyVRegIntervals.clear();
li2Node.clear();
node2LI.clear();
allowedSets.clear();
DOUT << "Post alloc VirtRegMap:\n" << *vrm << "\n";
std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
rewriter->runOnMachineFunction(*mf, *vrm, lis);
return true;
}
FunctionPass* llvm::createPBQPRegisterAllocator() {
return new PBQPRegAlloc();
}
#undef DEBUG_TYPE