LoopRerollPass.cpp [plain text]
#include "llvm/Transforms/Scalar.h"
#include "llvm/ADT/STLExtras.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/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/Target/TargetLibraryInfo.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"));
namespace {
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<AliasAnalysis>();
AU.addRequired<LoopInfo>();
AU.addPreserved<LoopInfo>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addRequired<ScalarEvolution>();
AU.addRequired<TargetLibraryInfo>();
}
protected:
AliasAnalysis *AA;
LoopInfo *LI;
ScalarEvolution *SE;
const DataLayout *DL;
TargetLibraryInfo *TLI;
DominatorTree *DT;
typedef SmallVector<Instruction *, 16> SmallInstructionVector;
typedef SmallSet<Instruction *, 16> SmallInstructionSet;
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 (SimpleLoopReduction::iterator J = PossibleReds[i].begin(),
JE = PossibleReds[i].end(); J != JE; ++J) {
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 isSelectedPHI(Instruction *J) {
if (!isa<PHINode>(J))
return false;
for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
RI != RIE; ++RI) {
int i = *RI;
if (cast<Instruction>(J) == PossibleReds[i].getPHI())
return true;
}
return false;
}
bool validateSelected();
void replaceSelected();
protected:
SmallReductionVector PossibleReds;
DenseMap<Instruction *, int> PossibleRedIdx;
DenseMap<Instruction *, int> PossibleRedIter;
DenseSet<int> Reds;
};
void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
void collectPossibleReductions(Loop *L,
ReductionTracker &Reductions);
void collectInLoopUserSet(Loop *L,
const SmallInstructionVector &Roots,
const SmallInstructionSet &Exclude,
const SmallInstructionSet &Final,
DenseSet<Instruction *> &Users);
void collectInLoopUserSet(Loop *L,
Instruction * Root,
const SmallInstructionSet &Exclude,
const SmallInstructionSet &Final,
DenseSet<Instruction *> &Users);
bool findScaleFromMul(Instruction *RealIV, uint64_t &Scale,
Instruction *&IV,
SmallInstructionVector &LoopIncs);
bool collectAllRoots(Loop *L, uint64_t Inc, uint64_t Scale, Instruction *IV,
SmallVector<SmallInstructionVector, 32> &Roots,
SmallInstructionSet &AllRoots,
SmallInstructionVector &LoopIncs);
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_AG_DEPENDENCY(AliasAnalysis)
INITIALIZE_PASS_DEPENDENCY(LoopInfo)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
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))) {
if (!IncSCEV->getValue()->getValue().isStrictlyPositive())
continue;
if (IncSCEV->getValue()->uge(MaxInc))
continue;
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();
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::collectInLoopUserSet(Loop *L,
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::collectInLoopUserSet(Loop *L,
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(L, *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;
}
bool LoopReroll::findScaleFromMul(Instruction *RealIV, uint64_t &Scale,
Instruction *&IV,
SmallInstructionVector &LoopIncs) {
if (RealIV->getNumUses() != 2)
return false;
const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(RealIV));
Instruction *User1 = cast<Instruction>(*RealIV->user_begin()),
*User2 = cast<Instruction>(*std::next(RealIV->user_begin()));
if (!SE->isSCEVable(User1->getType()) || !SE->isSCEVable(User2->getType()))
return false;
const SCEVAddRecExpr *User1SCEV =
dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User1)),
*User2SCEV =
dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User2));
if (!User1SCEV || !User1SCEV->isAffine() ||
!User2SCEV || !User2SCEV->isAffine())
return false;
if (User1SCEV == RealIVSCEV->getPostIncExpr(*SE)) {
std::swap(User1, User2);
std::swap(User1SCEV, User2SCEV);
}
if (User2SCEV != RealIVSCEV->getPostIncExpr(*SE))
return false;
assert(User2SCEV->getStepRecurrence(*SE)->isOne() &&
"Invalid non-unit step for multiplicative scaling");
LoopIncs.push_back(User2);
if (const SCEVConstant *MulScale =
dyn_cast<SCEVConstant>(User1SCEV->getStepRecurrence(*SE))) {
if (RealIVSCEV->getStart()->getType() != MulScale->getType())
return false;
if (SE->getMulExpr(RealIVSCEV->getStart(), MulScale) !=
User1SCEV->getStart())
return false;
ConstantInt *MulScaleCI = MulScale->getValue();
if (!MulScaleCI->uge(2) || MulScaleCI->uge(MaxInc))
return false;
Scale = MulScaleCI->getZExtValue();
IV = User1;
} else
return false;
DEBUG(dbgs() << "LRR: Found possible scaling " << *User1 << "\n");
return true;
}
bool LoopReroll::collectAllRoots(Loop *L, uint64_t Inc, uint64_t Scale,
Instruction *IV,
SmallVector<SmallInstructionVector, 32> &Roots,
SmallInstructionSet &AllRoots,
SmallInstructionVector &LoopIncs) {
for (User *U : IV->users()) {
Instruction *UI = cast<Instruction>(U);
if (!SE->isSCEVable(UI->getType()))
continue;
if (UI->getType() != IV->getType())
continue;
if (!L->contains(UI))
continue;
if (hasUsesOutsideLoop(UI, L))
continue;
if (const SCEVConstant *Diff = dyn_cast<SCEVConstant>(SE->getMinusSCEV(
SE->getSCEV(UI), SE->getSCEV(IV)))) {
uint64_t Idx = Diff->getValue()->getValue().getZExtValue();
if (Idx > 0 && Idx < Scale) {
Roots[Idx-1].push_back(UI);
AllRoots.insert(UI);
} else if (Idx == Scale && Inc > 1) {
LoopIncs.push_back(UI);
}
}
}
if (Roots[0].empty())
return false;
bool AllSame = true;
for (unsigned i = 1; i < Scale-1; ++i)
if (Roots[i].size() != Roots[0].size()) {
AllSame = false;
break;
}
if (!AllSame)
return false;
return true;
}
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 (SimpleLoopReduction::iterator J = PossibleReds[i].begin(),
JE = PossibleReds[i].end(); J != JE; ++J) {
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) {
const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(IV));
uint64_t Inc = cast<SCEVConstant>(RealIVSCEV->getOperand(1))->
getValue()->getZExtValue();
SmallInstructionVector LoopIncs;
uint64_t Scale = Inc;
Instruction *RealIV = IV;
if (Inc == 1 && !findScaleFromMul(RealIV, Scale, IV, LoopIncs))
return false;
assert(Scale <= MaxInc && "Scale is too large");
assert(Scale > 1 && "Scale must be at least 2");
SmallVector<SmallInstructionVector, 32> Roots(Scale-1);
SmallInstructionSet AllRoots;
if (!collectAllRoots(L, Inc, Scale, IV, Roots, AllRoots, LoopIncs))
return false;
DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
*RealIV << "\n");
SmallInstructionSet PossibleRedSet;
SmallInstructionSet PossibleRedLastSet, PossibleRedPHISet;
Reductions.restrictToScale(Scale, PossibleRedSet, PossibleRedPHISet,
PossibleRedLastSet);
SmallInstructionSet Exclude(AllRoots);
Exclude.insert(LoopIncs.begin(), LoopIncs.end());
DenseSet<Instruction *> BaseUseSet;
collectInLoopUserSet(L, IV, Exclude, PossibleRedSet, BaseUseSet);
DenseSet<Instruction *> AllRootUses;
std::vector<DenseSet<Instruction *> > RootUseSets(Scale-1);
bool MatchFailed = false;
for (unsigned i = 0; i < Scale-1 && !MatchFailed; ++i) {
DenseSet<Instruction *> &RootUseSet = RootUseSets[i];
collectInLoopUserSet(L, Roots[i], SmallInstructionSet(),
PossibleRedSet, RootUseSet);
DEBUG(dbgs() << "LRR: base use set size: " << BaseUseSet.size() <<
" vs. iteration increment " << (i+1) <<
" use set size: " << RootUseSet.size() << "\n");
if (BaseUseSet.size() != RootUseSet.size()) {
MatchFailed = true;
break;
}
bool FutureSideEffects = false;
AliasSetTracker AST(*AA);
DenseMap<Value *, Value *> BaseMap;
assert(L->getNumBlocks() == 1 && "Cannot handle multi-block loops");
for (BasicBlock::iterator J1 = Header->begin(), J2 = Header->begin(),
JE = Header->end(); J1 != JE && !MatchFailed; ++J1) {
if (cast<Instruction>(J1) == RealIV)
continue;
if (cast<Instruction>(J1) == IV)
continue;
if (!BaseUseSet.count(J1))
continue;
if (PossibleRedPHISet.count(J1)) continue;
while (J2 != JE && (!RootUseSet.count(J2) ||
std::find(Roots[i].begin(), Roots[i].end(), J2) !=
Roots[i].end())) {
if (!isa<PHINode>(J2) && !BaseUseSet.count(J2) &&
!AllRootUses.count(J2)) {
if (J2->mayWriteToMemory())
AST.add(J2);
if (!isSimpleLoadStore(J2) && !isSafeToSpeculativelyExecute(J2, DL))
FutureSideEffects = true;
}
++J2;
}
if (!J1->isSameOperationAs(J2)) {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
" vs. " << *J2 << "\n");
MatchFailed = true;
break;
}
if (BaseUseSet.count(J2) || AllRootUses.count(J2)) {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
" vs. " << *J2 << " (prev. case overlap)\n");
MatchFailed = true;
break;
}
if (J2->mayReadFromMemory()) {
for (AliasSetTracker::iterator K = AST.begin(), KE = AST.end();
K != KE && !MatchFailed; ++K) {
if (K->aliasesUnknownInst(J2, *AA)) {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
" vs. " << *J2 << " (depends on future store)\n");
MatchFailed = true;
break;
}
}
}
if (FutureSideEffects &&
((!isSimpleLoadStore(J1) &&
!isSafeToSpeculativelyExecute(J1, DL)) ||
(!isSimpleLoadStore(J2) &&
!isSafeToSpeculativelyExecute(J2, DL)))) {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
" vs. " << *J2 <<
" (side effects prevent reordering)\n");
MatchFailed = true;
break;
}
bool InReduction = Reductions.isPairInSame(J1, J2);
if (!(InReduction && J1->isAssociative())) {
bool Swapped = false, SomeOpMatched = false;
for (unsigned j = 0; j < J1->getNumOperands() && !MatchFailed; ++j) {
Value *Op2 = J2->getOperand(j);
if (InReduction)
if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
if (Reductions.isPairInSame(J2, Op2I))
continue;
DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
if (BMI != BaseMap.end())
Op2 = BMI->second;
else if (std::find(Roots[i].begin(), Roots[i].end(),
(Instruction*) Op2) != Roots[i].end())
Op2 = IV;
if (J1->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
if (!Swapped && J1->isCommutative() && !SomeOpMatched &&
J1->getOperand(!j) == Op2) {
Swapped = true;
} else {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
" vs. " << *J2 << " (operand " << j << ")\n");
MatchFailed = true;
break;
}
}
SomeOpMatched = true;
}
}
if ((!PossibleRedLastSet.count(J1) && hasUsesOutsideLoop(J1, L)) ||
(!PossibleRedLastSet.count(J2) && hasUsesOutsideLoop(J2, L))) {
DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
" vs. " << *J2 << " (uses outside loop)\n");
MatchFailed = true;
break;
}
if (!MatchFailed)
BaseMap.insert(std::pair<Value *, Value *>(J2, J1));
AllRootUses.insert(J2);
Reductions.recordPair(J1, J2, i+1);
++J2;
}
}
if (MatchFailed)
return false;
DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
*RealIV << "\n");
DenseSet<Instruction *> LoopIncUseSet;
collectInLoopUserSet(L, LoopIncs, SmallInstructionSet(),
SmallInstructionSet(), LoopIncUseSet);
DEBUG(dbgs() << "LRR: Loop increment set size: " <<
LoopIncUseSet.size() << "\n");
for (BasicBlock::iterator J = Header->begin(), JE = Header->end();
J != JE; ++J) {
if (isa<DbgInfoIntrinsic>(J))
continue;
if (cast<Instruction>(J) == RealIV)
continue;
if (cast<Instruction>(J) == IV)
continue;
if (BaseUseSet.count(J) || AllRootUses.count(J) ||
(LoopIncUseSet.count(J) && (J->isTerminator() ||
isSafeToSpeculativelyExecute(J, DL))))
continue;
if (AllRoots.count(J))
continue;
if (Reductions.isSelectedPHI(J))
continue;
DEBUG(dbgs() << "LRR: aborting reroll based on " << *RealIV <<
" unprocessed instruction found: " << *J << "\n");
MatchFailed = true;
break;
}
if (MatchFailed)
return false;
DEBUG(dbgs() << "LRR: all instructions processed from " <<
*RealIV << "\n");
if (!Reductions.validateSelected())
return false;
Reductions.replaceSelected();
for (BasicBlock::reverse_iterator J = Header->rbegin();
J != Header->rend();) {
if (AllRootUses.count(&*J)) {
Instruction *D = &*J;
DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
D->eraseFromParent();
continue;
}
++J;
}
const SCEV *Start = RealIVSCEV->getStart();
if (Inc == 1)
Start = SE->getMulExpr(Start,
SE->getConstant(Start->getType(), Scale));
const SCEVAddRecExpr *H =
cast<SCEVAddRecExpr>(SE->getAddRecExpr(Start,
SE->getConstant(RealIVSCEV->getType(), 1),
L, SCEV::FlagAnyWrap));
{ SCEVExpander Expander(*SE, "reroll");
Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
for (DenseSet<Instruction *>::iterator J = BaseUseSet.begin(),
JE = BaseUseSet.end(); J != JE; ++J)
(*J)->replaceUsesOfWith(IV, NewIV);
if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
if (LoopIncUseSet.count(BI)) {
const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
if (Inc == 1)
ICSCEV =
SE->getMulExpr(ICSCEV, SE->getConstant(ICSCEV->getType(), Scale));
const SCEV *ICMinus1SCEV =
SE->getMinusSCEV(ICSCEV, SE->getConstant(ICSCEV->getType(), 1));
Value *ICMinus1; if (isa<SCEVConstant>(ICMinus1SCEV)) {
ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
} else {
BasicBlock *Preheader = L->getLoopPreheader();
if (!Preheader)
Preheader = InsertPreheaderForLoop(L, this);
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, DL, TLI);
DeleteDeadPHIs(Header, TLI);
++NumRerolledLoops;
return true;
}
bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
if (skipOptnoneFunction(L))
return false;
AA = &getAnalysis<AliasAnalysis>();
LI = &getAnalysis<LoopInfo>();
SE = &getAnalysis<ScalarEvolution>();
TLI = &getAnalysis<TargetLibraryInfo>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
DL = DLP ? &DLP->getDataLayout() : nullptr;
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->getConstant(LIBETC->getType(), 1));
DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
SmallInstructionVector PossibleIVs;
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;
}