LoopRerollPass.cpp [plain text]
#include "llvm/Transforms/Scalar.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AliasSetTracker.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpander.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
using namespace llvm;
#define DEBUG_TYPE "loop-reroll"
STATISTIC(NumRerolledLoops, "Number of rerolled loops");
static cl::opt<unsigned>
MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
cl::desc("The maximum increment for loop rerolling"));
static cl::opt<unsigned>
NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400),
cl::Hidden,
cl::desc("The maximum number of failures to tolerate"
" during fuzzy matching. (default: 400)"));
namespace {
enum IterationLimits {
IL_MaxRerollIterations = 16,
IL_All,
IL_End
};
class LoopReroll : public LoopPass {
public:
static char ID; LoopReroll() : LoopPass(ID) {
initializeLoopRerollPass(*PassRegistry::getPassRegistry());
}
bool runOnLoop(Loop *L, LPPassManager &LPM) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<AAResultsWrapperPass>();
AU.addRequired<LoopInfoWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addRequired<ScalarEvolutionWrapperPass>();
AU.addRequired<TargetLibraryInfoWrapperPass>();
}
protected:
AliasAnalysis *AA;
LoopInfo *LI;
ScalarEvolution *SE;
TargetLibraryInfo *TLI;
DominatorTree *DT;
typedef SmallVector<Instruction *, 16> SmallInstructionVector;
typedef SmallSet<Instruction *, 16> SmallInstructionSet;
DenseMap<Instruction *, int64_t> IVToIncMap;
struct SimpleLoopReduction {
SimpleLoopReduction(Instruction *P, Loop *L)
: Valid(false), Instructions(1, P) {
assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
add(L);
}
bool valid() const {
return Valid;
}
Instruction *getPHI() const {
assert(Valid && "Using invalid reduction");
return Instructions.front();
}
Instruction *getReducedValue() const {
assert(Valid && "Using invalid reduction");
return Instructions.back();
}
Instruction *get(size_t i) const {
assert(Valid && "Using invalid reduction");
return Instructions[i+1];
}
Instruction *operator [] (size_t i) const { return get(i); }
size_t size() const {
assert(Valid && "Using invalid reduction");
return Instructions.size()-1;
}
typedef SmallInstructionVector::iterator iterator;
typedef SmallInstructionVector::const_iterator const_iterator;
iterator begin() {
assert(Valid && "Using invalid reduction");
return std::next(Instructions.begin());
}
const_iterator begin() const {
assert(Valid && "Using invalid reduction");
return std::next(Instructions.begin());
}
iterator end() { return Instructions.end(); }
const_iterator end() const { return Instructions.end(); }
protected:
bool Valid;
SmallInstructionVector Instructions;
void add(Loop *L);
};
struct ReductionTracker {
typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
void restrictToScale(uint64_t Scale,
SmallInstructionSet &PossibleRedSet,
SmallInstructionSet &PossibleRedPHISet,
SmallInstructionSet &PossibleRedLastSet) {
PossibleRedIdx.clear();
PossibleRedIter.clear();
Reds.clear();
for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
if (PossibleReds[i].size() % Scale == 0) {
PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
PossibleRedPHISet.insert(PossibleReds[i].getPHI());
PossibleRedSet.insert(PossibleReds[i].getPHI());
PossibleRedIdx[PossibleReds[i].getPHI()] = i;
for (Instruction *J : PossibleReds[i]) {
PossibleRedSet.insert(J);
PossibleRedIdx[J] = i;
}
}
}
bool isPairInSame(Instruction *J1, Instruction *J2) {
DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
if (J1I != PossibleRedIdx.end()) {
DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
return true;
}
return false;
}
void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
if (PossibleRedIdx.count(J1)) {
assert(PossibleRedIdx.count(J2) &&
"Recording reduction vs. non-reduction instruction?");
PossibleRedIter[J1] = 0;
PossibleRedIter[J2] = i;
int Idx = PossibleRedIdx[J1];
assert(Idx == PossibleRedIdx[J2] &&
"Recording pair from different reductions?");
Reds.insert(Idx);
}
}
bool validateSelected();
void replaceSelected();
protected:
SmallReductionVector PossibleReds;
DenseMap<Instruction *, int> PossibleRedIdx;
DenseMap<Instruction *, int> PossibleRedIter;
DenseSet<int> Reds;
};
struct DAGRootSet {
Instruction *BaseInst;
SmallInstructionVector Roots;
SmallInstructionSet SubsumedInsts;
};
struct DAGRootTracker {
DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
ScalarEvolution *SE, AliasAnalysis *AA,
TargetLibraryInfo *TLI,
DenseMap<Instruction *, int64_t> &IncrMap)
: Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), IV(IV),
IVToIncMap(IncrMap) {}
bool findRoots();
bool validate(ReductionTracker &Reductions);
void replace(const SCEV *IterCount);
protected:
typedef MapVector<Instruction*, SmallBitVector> UsesTy;
bool findRootsRecursive(Instruction *IVU,
SmallInstructionSet SubsumedInsts);
bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
bool collectPossibleRoots(Instruction *Base,
std::map<int64_t,Instruction*> &Roots);
bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
void collectInLoopUserSet(const SmallInstructionVector &Roots,
const SmallInstructionSet &Exclude,
const SmallInstructionSet &Final,
DenseSet<Instruction *> &Users);
void collectInLoopUserSet(Instruction *Root,
const SmallInstructionSet &Exclude,
const SmallInstructionSet &Final,
DenseSet<Instruction *> &Users);
UsesTy::iterator nextInstr(int Val, UsesTy &In,
const SmallInstructionSet &Exclude,
UsesTy::iterator *StartI=nullptr);
bool isBaseInst(Instruction *I);
bool isRootInst(Instruction *I);
bool instrDependsOn(Instruction *I,
UsesTy::iterator Start,
UsesTy::iterator End);
LoopReroll *Parent;
Loop *L;
ScalarEvolution *SE;
AliasAnalysis *AA;
TargetLibraryInfo *TLI;
Instruction *IV;
int64_t Inc;
uint64_t Scale;
SmallVector<DAGRootSet,16> RootSets;
SmallInstructionVector LoopIncs;
UsesTy Uses;
DenseMap<Instruction *, int64_t> &IVToIncMap;
};
void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
void collectPossibleReductions(Loop *L,
ReductionTracker &Reductions);
bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
ReductionTracker &Reductions);
};
}
char LoopReroll::ID = 0;
INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
Pass *llvm::createLoopRerollPass() {
return new LoopReroll;
}
static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
for (User *U : I->users()) {
if (!L->contains(cast<Instruction>(U)))
return true;
}
return false;
}
void LoopReroll::collectPossibleIVs(Loop *L,
SmallInstructionVector &PossibleIVs) {
BasicBlock *Header = L->getHeader();
for (BasicBlock::iterator I = Header->begin(),
IE = Header->getFirstInsertionPt(); I != IE; ++I) {
if (!isa<PHINode>(I))
continue;
if (!I->getType()->isIntegerTy())
continue;
if (const SCEVAddRecExpr *PHISCEV =
dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
if (PHISCEV->getLoop() != L)
continue;
if (!PHISCEV->isAffine())
continue;
if (const SCEVConstant *IncSCEV =
dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
const APInt &AInt = IncSCEV->getValue()->getValue().abs();
if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc))
continue;
IVToIncMap[&*I] = IncSCEV->getValue()->getSExtValue();
DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
<< "\n");
PossibleIVs.push_back(&*I);
}
}
}
}
void LoopReroll::SimpleLoopReduction::add(Loop *L) {
assert(!Valid && "Cannot add to an already-valid chain");
Instruction *C = Instructions.front();
if (C->user_empty())
return;
do {
C = cast<Instruction>(*C->user_begin());
if (C->hasOneUse()) {
if (!C->isBinaryOp())
return;
if (!(isa<PHINode>(Instructions.back()) ||
C->isSameOperationAs(Instructions.back())))
return;
Instructions.push_back(C);
}
} while (C->hasOneUse());
if (Instructions.size() < 2 ||
!C->isSameOperationAs(Instructions.back()) ||
C->use_empty())
return;
for (User *U : C->users()) {
if (L->contains(cast<Instruction>(U)))
if (cast<Instruction>(U) != Instructions.front())
return;
}
Instructions.push_back(C);
Valid = true;
}
void LoopReroll::collectPossibleReductions(Loop *L,
ReductionTracker &Reductions) {
BasicBlock *Header = L->getHeader();
for (BasicBlock::iterator I = Header->begin(),
IE = Header->getFirstInsertionPt(); I != IE; ++I) {
if (!isa<PHINode>(I))
continue;
if (!I->getType()->isSingleValueType())
continue;
SimpleLoopReduction SLR(&*I, L);
if (!SLR.valid())
continue;
DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
SLR.size() << " chained instructions)\n");
Reductions.addSLR(SLR);
}
}
void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Instruction *Root, const SmallInstructionSet &Exclude,
const SmallInstructionSet &Final,
DenseSet<Instruction *> &Users) {
SmallInstructionVector Queue(1, Root);
while (!Queue.empty()) {
Instruction *I = Queue.pop_back_val();
if (!Users.insert(I).second)
continue;
if (!Final.count(I))
for (Use &U : I->uses()) {
Instruction *User = cast<Instruction>(U.getUser());
if (PHINode *PN = dyn_cast<PHINode>(User)) {
if (PN->getIncomingBlock(U) == L->getHeader())
continue;
}
if (L->contains(User) && !Exclude.count(User)) {
Queue.push_back(User);
}
}
for (User::op_iterator OI = I->op_begin(),
OIE = I->op_end(); OI != OIE; ++OI) {
if (Instruction *Op = dyn_cast<Instruction>(*OI))
if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
!Final.count(Op))
Queue.push_back(Op);
}
}
}
void LoopReroll::DAGRootTracker::collectInLoopUserSet(
const SmallInstructionVector &Roots,
const SmallInstructionSet &Exclude,
const SmallInstructionSet &Final,
DenseSet<Instruction *> &Users) {
for (SmallInstructionVector::const_iterator I = Roots.begin(),
IE = Roots.end(); I != IE; ++I)
collectInLoopUserSet(*I, Exclude, Final, Users);
}
static bool isSimpleLoadStore(Instruction *I) {
if (LoadInst *LI = dyn_cast<LoadInst>(I))
return LI->isSimple();
if (StoreInst *SI = dyn_cast<StoreInst>(I))
return SI->isSimple();
if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
return !MI->isVolatile();
return false;
}
static bool isSimpleArithmeticOp(User *IVU) {
if (Instruction *I = dyn_cast<Instruction>(IVU)) {
switch (I->getOpcode()) {
default: return false;
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::Shl:
case Instruction::AShr:
case Instruction::LShr:
case Instruction::GetElementPtr:
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
return true;
}
}
return false;
}
static bool isLoopIncrement(User *U, Instruction *IV) {
BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
if (!BO || BO->getOpcode() != Instruction::Add)
return false;
for (auto *UU : BO->users()) {
PHINode *PN = dyn_cast<PHINode>(UU);
if (PN && PN == IV)
return true;
}
return false;
}
bool LoopReroll::DAGRootTracker::
collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
SmallInstructionVector BaseUsers;
for (auto *I : Base->users()) {
ConstantInt *CI = nullptr;
if (isLoopIncrement(I, IV)) {
LoopIncs.push_back(cast<Instruction>(I));
continue;
}
if (auto *BO = dyn_cast<BinaryOperator>(I)) {
if (BO->getOpcode() == Instruction::Add ||
BO->getOpcode() == Instruction::Or)
CI = dyn_cast<ConstantInt>(BO->getOperand(1));
} else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
CI = dyn_cast<ConstantInt>(LastOperand);
}
if (!CI) {
if (Instruction *II = dyn_cast<Instruction>(I)) {
BaseUsers.push_back(II);
continue;
} else {
DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
return false;
}
}
int64_t V = std::abs(CI->getValue().getSExtValue());
if (Roots.find(V) != Roots.end())
return false;
Roots[V] = cast<Instruction>(I);
}
if (Roots.empty())
return false;
if (BaseUsers.size()) {
if (Roots.find(0) != Roots.end()) {
DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
return false;
}
Roots[0] = Base;
}
unsigned NumBaseUses = BaseUsers.size();
if (NumBaseUses == 0)
NumBaseUses = Roots.begin()->second->getNumUses();
for (auto &KV : Roots) {
if (KV.first == 0)
continue;
if (KV.second->getNumUses() != NumBaseUses) {
DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
<< "#Base=" << NumBaseUses << ", #Root=" <<
KV.second->getNumUses() << "\n");
return false;
}
}
return true;
}
bool LoopReroll::DAGRootTracker::
findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
if (I->getNumUses() > IL_MaxRerollIterations)
return false;
if ((I->getOpcode() == Instruction::Mul ||
I->getOpcode() == Instruction::PHI) &&
I != IV &&
findRootsBase(I, SubsumedInsts))
return true;
SubsumedInsts.insert(I);
for (User *V : I->users()) {
Instruction *I = dyn_cast<Instruction>(V);
if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end())
continue;
if (!I || !isSimpleArithmeticOp(I) ||
!findRootsRecursive(I, SubsumedInsts))
return false;
}
return true;
}
bool LoopReroll::DAGRootTracker::
findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
if (IVU->getOpcode() != Instruction::Mul &&
IVU->getOpcode() != Instruction::PHI)
return false;
std::map<int64_t, Instruction*> V;
if (!collectPossibleRoots(IVU, V))
return false;
if (V.find(0) == V.end())
SubsumedInsts.insert(IVU);
DAGRootSet DRS;
DRS.BaseInst = nullptr;
for (auto &KV : V) {
if (!DRS.BaseInst) {
DRS.BaseInst = KV.second;
DRS.SubsumedInsts = SubsumedInsts;
} else if (DRS.Roots.empty()) {
DRS.Roots.push_back(KV.second);
} else if (V.find(KV.first - 1) != V.end()) {
DRS.Roots.push_back(KV.second);
} else {
RootSets.push_back(DRS);
DRS.BaseInst = KV.second;
DRS.SubsumedInsts = SubsumedInsts;
DRS.Roots.clear();
}
}
RootSets.push_back(DRS);
return true;
}
bool LoopReroll::DAGRootTracker::findRoots() {
Inc = IVToIncMap[IV];
assert(RootSets.empty() && "Unclean state!");
if (std::abs(Inc) == 1) {
for (auto *IVU : IV->users()) {
if (isLoopIncrement(IVU, IV))
LoopIncs.push_back(cast<Instruction>(IVU));
}
if (!findRootsRecursive(IV, SmallInstructionSet()))
return false;
LoopIncs.push_back(IV);
} else {
if (!findRootsBase(IV, SmallInstructionSet()))
return false;
}
if (RootSets.empty()) {
DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
return false;
}
for (auto &V : RootSets) {
if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
DEBUG(dbgs()
<< "LRR: Aborting because not all root sets have the same size\n");
return false;
}
}
for (auto &V : RootSets) {
const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst));
if (!ADR)
return false;
unsigned N = V.Roots.size() + 1;
const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR);
const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) {
DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n");
return false;
}
}
Scale = RootSets[0].Roots.size() + 1;
if (Scale > IL_MaxRerollIterations) {
DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
<< "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
<< "\n");
return false;
}
DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
return true;
}
bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
for (auto &I : *L->getHeader()) {
Uses[&I].resize(IL_End);
}
SmallInstructionSet Exclude;
for (auto &DRS : RootSets) {
Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
Exclude.insert(DRS.BaseInst);
}
Exclude.insert(LoopIncs.begin(), LoopIncs.end());
for (auto &DRS : RootSets) {
DenseSet<Instruction*> VBase;
collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
for (auto *I : VBase) {
Uses[I].set(0);
}
unsigned Idx = 1;
for (auto *Root : DRS.Roots) {
DenseSet<Instruction*> V;
collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
if (V.size() != VBase.size()) {
DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
return false;
}
for (auto *I : V) {
Uses[I].set(Idx);
}
++Idx;
}
for (auto *I : DRS.SubsumedInsts) {
Uses[I].set(IL_All);
}
}
Exclude.clear();
for (auto &DRS : RootSets) {
Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
Exclude.insert(DRS.BaseInst);
}
DenseSet<Instruction*> V;
collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
for (auto *I : V) {
Uses[I].set(IL_All);
}
return true;
}
LoopReroll::DAGRootTracker::UsesTy::iterator
LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
const SmallInstructionSet &Exclude,
UsesTy::iterator *StartI) {
UsesTy::iterator I = StartI ? *StartI : In.begin();
while (I != In.end() && (I->second.test(Val) == 0 ||
Exclude.count(I->first) != 0))
++I;
return I;
}
bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
for (auto &DRS : RootSets) {
if (DRS.BaseInst == I)
return true;
}
return false;
}
bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
for (auto &DRS : RootSets) {
if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end())
return true;
}
return false;
}
bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
UsesTy::iterator Start,
UsesTy::iterator End) {
for (auto *U : I->users()) {
for (auto It = Start; It != End; ++It)
if (U == It->first)
return true;
}
return false;
}
static bool isIgnorableInst(const Instruction *I) {
if (isa<DbgInfoIntrinsic>(I))
return true;
const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I);
if (!II)
return false;
switch (II->getIntrinsicID()) {
default:
return false;
case llvm::Intrinsic::annotation:
case Intrinsic::ptr_annotation:
case Intrinsic::var_annotation:
return true;
}
return false;
}
bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
SmallInstructionSet PossibleRedSet;
SmallInstructionSet PossibleRedLastSet;
SmallInstructionSet PossibleRedPHISet;
Reductions.restrictToScale(Scale, PossibleRedSet,
PossibleRedPHISet, PossibleRedLastSet);
if (!collectUsedInstructions(PossibleRedSet))
return false;
for (auto *I : PossibleRedPHISet) {
Uses[I].set(IL_All);
}
for (auto &KV : Uses) {
if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) {
DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
<< *KV.first << " (#uses=" << KV.second.count() << ")\n");
return false;
}
}
DEBUG(
for (auto &KV : Uses) {
dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
}
);
for (unsigned Iter = 1; Iter < Scale; ++Iter) {
bool FutureSideEffects = false;
AliasSetTracker AST(*AA);
DenseMap<Value *, Value *> BaseMap;
SmallInstructionSet Visited;
auto BaseIt = nextInstr(0, Uses, Visited);
auto RootIt = nextInstr(Iter, Uses, Visited);
auto LastRootIt = Uses.begin();
while (BaseIt != Uses.end() && RootIt != Uses.end()) {
Instruction *BaseInst = BaseIt->first;
Instruction *RootInst = RootIt->first;
bool Continue = false;
if (isBaseInst(BaseInst)) {
Visited.insert(BaseInst);
BaseIt = nextInstr(0, Uses, Visited);
Continue = true;
}
if (isRootInst(RootInst)) {
LastRootIt = RootIt;
Visited.insert(RootInst);
RootIt = nextInstr(Iter, Uses, Visited);
Continue = true;
}
if (Continue) continue;
if (!BaseInst->isSameOperationAs(RootInst)) {
auto TryIt = RootIt;
unsigned N = NumToleratedFailedMatches;
while (TryIt != Uses.end() &&
!BaseInst->isSameOperationAs(TryIt->first) &&
N--) {
++TryIt;
TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
}
if (TryIt == Uses.end() || TryIt == RootIt ||
instrDependsOn(TryIt->first, RootIt, TryIt)) {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
" vs. " << *RootInst << "\n");
return false;
}
RootIt = TryIt;
RootInst = TryIt->first;
}
for (; LastRootIt < RootIt; ++LastRootIt) {
Instruction *I = LastRootIt->first;
if (LastRootIt->second.find_first() < (int)Iter)
continue;
if (I->mayWriteToMemory())
AST.add(I);
if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
!isSafeToSpeculativelyExecute(I))
FutureSideEffects = true;
}
if (RootIt->second.count() > 1) {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
" vs. " << *RootInst << " (prev. case overlap)\n");
return false;
}
if (RootInst->mayReadFromMemory())
for (auto &K : AST) {
if (K.aliasesUnknownInst(RootInst, *AA)) {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
" vs. " << *RootInst << " (depends on future store)\n");
return false;
}
}
if (FutureSideEffects && ((!isSimpleLoadStore(BaseInst) &&
!isSafeToSpeculativelyExecute(BaseInst)) ||
(!isSimpleLoadStore(RootInst) &&
!isSafeToSpeculativelyExecute(RootInst)))) {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
" vs. " << *RootInst <<
" (side effects prevent reordering)\n");
return false;
}
bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
if (!(InReduction && BaseInst->isAssociative())) {
bool Swapped = false, SomeOpMatched = false;
for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
Value *Op2 = RootInst->getOperand(j);
if (InReduction)
if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
if (Reductions.isPairInSame(RootInst, Op2I))
continue;
DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
if (BMI != BaseMap.end()) {
Op2 = BMI->second;
} else {
for (auto &DRS : RootSets) {
if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
Op2 = DRS.BaseInst;
break;
}
}
}
if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
BaseInst->getOperand(!j) == Op2) {
Swapped = true;
} else {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
<< " vs. " << *RootInst << " (operand " << j << ")\n");
return false;
}
}
SomeOpMatched = true;
}
}
if ((!PossibleRedLastSet.count(BaseInst) &&
hasUsesOutsideLoop(BaseInst, L)) ||
(!PossibleRedLastSet.count(RootInst) &&
hasUsesOutsideLoop(RootInst, L))) {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
" vs. " << *RootInst << " (uses outside loop)\n");
return false;
}
Reductions.recordPair(BaseInst, RootInst, Iter);
BaseMap.insert(std::make_pair(RootInst, BaseInst));
LastRootIt = RootIt;
Visited.insert(BaseInst);
Visited.insert(RootInst);
BaseIt = nextInstr(0, Uses, Visited);
RootIt = nextInstr(Iter, Uses, Visited);
}
assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
"Mismatched set sizes!");
}
DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
*IV << "\n");
return true;
}
void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
BasicBlock *Header = L->getHeader();
for (BasicBlock::reverse_iterator J = Header->rbegin();
J != Header->rend();) {
unsigned I = Uses[&*J].find_first();
if (I > 0 && I < IL_All) {
Instruction *D = &*J;
DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
D->eraseFromParent();
continue;
}
++J;
}
bool Negative = IVToIncMap[IV] < 0;
const DataLayout &DL = Header->getModule()->getDataLayout();
for (auto &DRS : RootSets) {
const SCEVAddRecExpr *RealIVSCEV =
cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
const SCEV *Start = RealIVSCEV->getStart();
const SCEVAddRecExpr *H = cast<SCEVAddRecExpr>(SE->getAddRecExpr(
Start, SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1), L,
SCEV::FlagAnyWrap));
{ SCEVExpander Expander(*SE, DL, "reroll");
Value *NewIV = Expander.expandCodeFor(H, IV->getType(), &Header->front());
for (auto &KV : Uses) {
if (KV.second.find_first() == 0)
KV.first->replaceUsesOfWith(DRS.BaseInst, NewIV);
}
if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
if (Uses[BI].find_first() == IL_All) {
const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
const SCEV *ICMinus1SCEV = SE->getMinusSCEV(
ICSCEV, SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1));
Value *ICMinus1; if (isa<SCEVConstant>(ICMinus1SCEV)) {
ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
} else {
BasicBlock *Preheader = L->getLoopPreheader();
if (!Preheader)
Preheader = InsertPreheaderForLoop(L, Parent);
ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
Preheader->getTerminator());
}
Value *Cond =
new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond");
BI->setCondition(Cond);
if (BI->getSuccessor(1) != Header)
BI->swapSuccessors();
}
}
}
}
SimplifyInstructionsInBlock(Header, TLI);
DeleteDeadPHIs(Header, TLI);
}
bool LoopReroll::ReductionTracker::validateSelected() {
for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
RI != RIE; ++RI) {
int i = *RI;
int PrevIter = 0, BaseCount = 0, Count = 0;
for (Instruction *J : PossibleReds[i]) {
int Iter = PossibleRedIter[J];
if (Iter != PrevIter && Iter != PrevIter + 1 &&
!PossibleReds[i].getReducedValue()->isAssociative()) {
DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
J << "\n");
return false;
}
if (Iter != PrevIter) {
if (Count != BaseCount) {
DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
" reduction use count " << Count <<
" is not equal to the base use count " <<
BaseCount << "\n");
return false;
}
Count = 0;
}
++Count;
if (Iter == 0)
++BaseCount;
PrevIter = Iter;
}
}
return true;
}
void LoopReroll::ReductionTracker::replaceSelected() {
for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
RI != RIE; ++RI) {
int i = *RI;
int j = 0;
for (int e = PossibleReds[i].size(); j != e; ++j)
if (PossibleRedIter[PossibleReds[i][j]] != 0) {
--j;
break;
}
SmallInstructionVector Users;
for (User *U : PossibleReds[i].getReducedValue()->users()) {
Users.push_back(cast<Instruction>(U));
}
for (SmallInstructionVector::iterator J = Users.begin(),
JE = Users.end(); J != JE; ++J)
(*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
PossibleReds[i][j]);
}
}
bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
const SCEV *IterCount,
ReductionTracker &Reductions) {
DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, IVToIncMap);
if (!DAGRoots.findRoots())
return false;
DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
*IV << "\n");
if (!DAGRoots.validate(Reductions))
return false;
if (!Reductions.validateSelected())
return false;
Reductions.replaceSelected();
DAGRoots.replace(IterCount);
++NumRerolledLoops;
return true;
}
bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
if (skipOptnoneFunction(L))
return false;
AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
BasicBlock *Header = L->getHeader();
DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
"] Loop %" << Header->getName() << " (" <<
L->getNumBlocks() << " block(s))\n");
bool Changed = false;
if (L->getNumBlocks() > 1)
return Changed;
if (!SE->hasLoopInvariantBackedgeTakenCount(L))
return Changed;
const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
const SCEV *IterCount = SE->getAddExpr(LIBETC, SE->getOne(LIBETC->getType()));
DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
SmallInstructionVector PossibleIVs;
IVToIncMap.clear();
collectPossibleIVs(L, PossibleIVs);
if (PossibleIVs.empty()) {
DEBUG(dbgs() << "LRR: No possible IVs found\n");
return Changed;
}
ReductionTracker Reductions;
collectPossibleReductions(L, Reductions);
for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
IE = PossibleIVs.end(); I != IE; ++I)
if (reroll(*I, L, Header, IterCount, Reductions)) {
Changed = true;
break;
}
return Changed;
}