1 //===-- LoopReroll.cpp - Loop rerolling pass ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass implements a simple loop reroller.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/MapVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallBitVector.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AliasSetTracker.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionExpander.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Analysis/TargetLibraryInfo.h"
34 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Transforms/Utils/LoopUtils.h"
40 #define DEBUG_TYPE "loop-reroll"
42 STATISTIC(NumRerolledLoops, "Number of rerolled loops");
44 static cl::opt<unsigned>
45 MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
46 cl::desc("The maximum increment for loop rerolling"));
48 // This loop re-rolling transformation aims to transform loops like this:
52 // for (int i = 0; i < 500; i += 3) {
59 // into a loop like this:
62 // for (int i = 0; i < 500; ++i)
66 // It does this by looking for loops that, besides the latch code, are composed
67 // of isomorphic DAGs of instructions, with each DAG rooted at some increment
68 // to the induction variable, and where each DAG is isomorphic to the DAG
69 // rooted at the induction variable (excepting the sub-DAGs which root the
70 // other induction-variable increments). In other words, we're looking for loop
71 // bodies of the form:
73 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
75 // %iv.1 = add %iv, 1 <-- a root increment
77 // %iv.2 = add %iv, 2 <-- a root increment
79 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
82 // %iv.next = add %iv, scale
83 // %cmp = icmp(%iv, ...)
84 // br %cmp, header, exit
86 // where each f(i) is a set of instructions that, collectively, are a function
87 // only of i (and other loop-invariant values).
89 // As a special case, we can also reroll loops like this:
93 // for (int i = 0; i < 500; ++i) {
102 // void bar(int *x) {
103 // for (int i = 0; i < 1500; ++i)
107 // in which case, we're looking for inputs like this:
109 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
110 // %scaled.iv = mul %iv, scale
112 // %scaled.iv.1 = add %scaled.iv, 1
114 // %scaled.iv.2 = add %scaled.iv, 2
116 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
117 // f(%scaled.iv.scale_m_1)
119 // %iv.next = add %iv, 1
120 // %cmp = icmp(%iv, ...)
121 // br %cmp, header, exit
124 enum IterationLimits {
125 /// The maximum number of iterations that we'll try and reroll. This
126 /// has to be less than 25 in order to fit into a SmallBitVector.
127 IL_MaxRerollIterations = 16,
128 /// The bitvector index used by loop induction variables and other
129 /// instructions that belong to no one particular iteration.
134 class LoopReroll : public LoopPass {
136 static char ID; // Pass ID, replacement for typeid
137 LoopReroll() : LoopPass(ID) {
138 initializeLoopRerollPass(*PassRegistry::getPassRegistry());
141 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
143 void getAnalysisUsage(AnalysisUsage &AU) const override {
144 AU.addRequired<AliasAnalysis>();
145 AU.addRequired<LoopInfoWrapperPass>();
146 AU.addPreserved<LoopInfoWrapperPass>();
147 AU.addRequired<DominatorTreeWrapperPass>();
148 AU.addPreserved<DominatorTreeWrapperPass>();
149 AU.addRequired<ScalarEvolution>();
150 AU.addRequired<TargetLibraryInfoWrapperPass>();
157 const DataLayout *DL;
158 TargetLibraryInfo *TLI;
161 typedef SmallVector<Instruction *, 16> SmallInstructionVector;
162 typedef SmallSet<Instruction *, 16> SmallInstructionSet;
164 // A chain of isomorphic instructions, indentified by a single-use PHI,
165 // representing a reduction. Only the last value may be used outside the
167 struct SimpleLoopReduction {
168 SimpleLoopReduction(Instruction *P, Loop *L)
169 : Valid(false), Instructions(1, P) {
170 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
178 Instruction *getPHI() const {
179 assert(Valid && "Using invalid reduction");
180 return Instructions.front();
183 Instruction *getReducedValue() const {
184 assert(Valid && "Using invalid reduction");
185 return Instructions.back();
188 Instruction *get(size_t i) const {
189 assert(Valid && "Using invalid reduction");
190 return Instructions[i+1];
193 Instruction *operator [] (size_t i) const { return get(i); }
195 // The size, ignoring the initial PHI.
196 size_t size() const {
197 assert(Valid && "Using invalid reduction");
198 return Instructions.size()-1;
201 typedef SmallInstructionVector::iterator iterator;
202 typedef SmallInstructionVector::const_iterator const_iterator;
205 assert(Valid && "Using invalid reduction");
206 return std::next(Instructions.begin());
209 const_iterator begin() const {
210 assert(Valid && "Using invalid reduction");
211 return std::next(Instructions.begin());
214 iterator end() { return Instructions.end(); }
215 const_iterator end() const { return Instructions.end(); }
219 SmallInstructionVector Instructions;
224 // The set of all reductions, and state tracking of possible reductions
225 // during loop instruction processing.
226 struct ReductionTracker {
227 typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
229 // Add a new possible reduction.
230 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
232 // Setup to track possible reductions corresponding to the provided
233 // rerolling scale. Only reductions with a number of non-PHI instructions
234 // that is divisible by the scale are considered. Three instructions sets
236 // - A set of all possible instructions in eligible reductions.
237 // - A set of all PHIs in eligible reductions
238 // - A set of all reduced values (last instructions) in eligible
240 void restrictToScale(uint64_t Scale,
241 SmallInstructionSet &PossibleRedSet,
242 SmallInstructionSet &PossibleRedPHISet,
243 SmallInstructionSet &PossibleRedLastSet) {
244 PossibleRedIdx.clear();
245 PossibleRedIter.clear();
248 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
249 if (PossibleReds[i].size() % Scale == 0) {
250 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
251 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
253 PossibleRedSet.insert(PossibleReds[i].getPHI());
254 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
255 for (Instruction *J : PossibleReds[i]) {
256 PossibleRedSet.insert(J);
257 PossibleRedIdx[J] = i;
262 // The functions below are used while processing the loop instructions.
264 // Are the two instructions both from reductions, and furthermore, from
265 // the same reduction?
266 bool isPairInSame(Instruction *J1, Instruction *J2) {
267 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
268 if (J1I != PossibleRedIdx.end()) {
269 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
270 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
277 // The two provided instructions, the first from the base iteration, and
278 // the second from iteration i, form a matched pair. If these are part of
279 // a reduction, record that fact.
280 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
281 if (PossibleRedIdx.count(J1)) {
282 assert(PossibleRedIdx.count(J2) &&
283 "Recording reduction vs. non-reduction instruction?");
285 PossibleRedIter[J1] = 0;
286 PossibleRedIter[J2] = i;
288 int Idx = PossibleRedIdx[J1];
289 assert(Idx == PossibleRedIdx[J2] &&
290 "Recording pair from different reductions?");
295 // The functions below can be called after we've finished processing all
296 // instructions in the loop, and we know which reductions were selected.
298 // Is the provided instruction the PHI of a reduction selected for
300 bool isSelectedPHI(Instruction *J) {
301 if (!isa<PHINode>(J))
304 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
307 if (cast<Instruction>(J) == PossibleReds[i].getPHI())
314 bool validateSelected();
315 void replaceSelected();
318 // The vector of all possible reductions (for any scale).
319 SmallReductionVector PossibleReds;
321 DenseMap<Instruction *, int> PossibleRedIdx;
322 DenseMap<Instruction *, int> PossibleRedIter;
326 // The set of all DAG roots, and state tracking of all roots
327 // for a particular induction variable.
328 struct DAGRootTracker {
329 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
330 ScalarEvolution *SE, AliasAnalysis *AA,
331 TargetLibraryInfo *TLI, const DataLayout *DL)
332 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI),
336 /// Stage 1: Find all the DAG roots for the induction variable.
338 /// Stage 2: Validate if the found roots are valid.
339 bool validate(ReductionTracker &Reductions);
340 /// Stage 3: Assuming validate() returned true, perform the
342 /// @param IterCount The maximum iteration count of L.
343 void replace(const SCEV *IterCount);
346 typedef MapVector<Instruction*, SmallBitVector> UsesTy;
348 bool findScaleFromMul();
349 bool collectAllRoots();
351 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
352 void collectInLoopUserSet(const SmallInstructionVector &Roots,
353 const SmallInstructionSet &Exclude,
354 const SmallInstructionSet &Final,
355 DenseSet<Instruction *> &Users);
356 void collectInLoopUserSet(Instruction *Root,
357 const SmallInstructionSet &Exclude,
358 const SmallInstructionSet &Final,
359 DenseSet<Instruction *> &Users);
361 UsesTy::iterator nextInstr(int Val, UsesTy &In, UsesTy::iterator I);
365 // Members of Parent, replicated here for brevity.
369 TargetLibraryInfo *TLI;
370 const DataLayout *DL;
372 // The loop induction variable.
376 // Loop reroll count; if Inc == 1, this records the scaling applied
377 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
378 // If Inc is not 1, Scale = Inc.
380 // If Scale != Inc, then RealIV is IV after its multiplication.
382 // The roots themselves.
383 SmallInstructionVector Roots;
384 // All increment instructions for IV.
385 SmallInstructionVector LoopIncs;
386 // Map of all instructions in the loop (in order) to the iterations
387 // they are used in (or specially, IL_LoopIncIdx for instructions
388 // used in the loop increment mechanism).
392 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
393 void collectPossibleReductions(Loop *L,
394 ReductionTracker &Reductions);
395 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
396 ReductionTracker &Reductions);
400 char LoopReroll::ID = 0;
401 INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
402 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
403 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
404 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
405 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
406 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
407 INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
409 Pass *llvm::createLoopRerollPass() {
410 return new LoopReroll;
413 // Returns true if the provided instruction is used outside the given loop.
414 // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
415 // non-loop blocks to be outside the loop.
416 static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
417 for (User *U : I->users()) {
418 if (!L->contains(cast<Instruction>(U)))
424 // Collect the list of loop induction variables with respect to which it might
425 // be possible to reroll the loop.
426 void LoopReroll::collectPossibleIVs(Loop *L,
427 SmallInstructionVector &PossibleIVs) {
428 BasicBlock *Header = L->getHeader();
429 for (BasicBlock::iterator I = Header->begin(),
430 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
431 if (!isa<PHINode>(I))
433 if (!I->getType()->isIntegerTy())
436 if (const SCEVAddRecExpr *PHISCEV =
437 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
438 if (PHISCEV->getLoop() != L)
440 if (!PHISCEV->isAffine())
442 if (const SCEVConstant *IncSCEV =
443 dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
444 if (!IncSCEV->getValue()->getValue().isStrictlyPositive())
446 if (IncSCEV->getValue()->uge(MaxInc))
449 DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " <<
451 PossibleIVs.push_back(I);
457 // Add the remainder of the reduction-variable chain to the instruction vector
458 // (the initial PHINode has already been added). If successful, the object is
460 void LoopReroll::SimpleLoopReduction::add(Loop *L) {
461 assert(!Valid && "Cannot add to an already-valid chain");
463 // The reduction variable must be a chain of single-use instructions
464 // (including the PHI), except for the last value (which is used by the PHI
465 // and also outside the loop).
466 Instruction *C = Instructions.front();
469 C = cast<Instruction>(*C->user_begin());
470 if (C->hasOneUse()) {
471 if (!C->isBinaryOp())
474 if (!(isa<PHINode>(Instructions.back()) ||
475 C->isSameOperationAs(Instructions.back())))
478 Instructions.push_back(C);
480 } while (C->hasOneUse());
482 if (Instructions.size() < 2 ||
483 !C->isSameOperationAs(Instructions.back()) ||
487 // C is now the (potential) last instruction in the reduction chain.
488 for (User *U : C->users()) {
489 // The only in-loop user can be the initial PHI.
490 if (L->contains(cast<Instruction>(U)))
491 if (cast<Instruction>(U) != Instructions.front())
495 Instructions.push_back(C);
499 // Collect the vector of possible reduction variables.
500 void LoopReroll::collectPossibleReductions(Loop *L,
501 ReductionTracker &Reductions) {
502 BasicBlock *Header = L->getHeader();
503 for (BasicBlock::iterator I = Header->begin(),
504 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
505 if (!isa<PHINode>(I))
507 if (!I->getType()->isSingleValueType())
510 SimpleLoopReduction SLR(I, L);
514 DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
515 SLR.size() << " chained instructions)\n");
516 Reductions.addSLR(SLR);
520 // Collect the set of all users of the provided root instruction. This set of
521 // users contains not only the direct users of the root instruction, but also
522 // all users of those users, and so on. There are two exceptions:
524 // 1. Instructions in the set of excluded instructions are never added to the
525 // use set (even if they are users). This is used, for example, to exclude
526 // including root increments in the use set of the primary IV.
528 // 2. Instructions in the set of final instructions are added to the use set
529 // if they are users, but their users are not added. This is used, for
530 // example, to prevent a reduction update from forcing all later reduction
531 // updates into the use set.
532 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
533 Instruction *Root, const SmallInstructionSet &Exclude,
534 const SmallInstructionSet &Final,
535 DenseSet<Instruction *> &Users) {
536 SmallInstructionVector Queue(1, Root);
537 while (!Queue.empty()) {
538 Instruction *I = Queue.pop_back_val();
539 if (!Users.insert(I).second)
543 for (Use &U : I->uses()) {
544 Instruction *User = cast<Instruction>(U.getUser());
545 if (PHINode *PN = dyn_cast<PHINode>(User)) {
546 // Ignore "wrap-around" uses to PHIs of this loop's header.
547 if (PN->getIncomingBlock(U) == L->getHeader())
551 if (L->contains(User) && !Exclude.count(User)) {
552 Queue.push_back(User);
556 // We also want to collect single-user "feeder" values.
557 for (User::op_iterator OI = I->op_begin(),
558 OIE = I->op_end(); OI != OIE; ++OI) {
559 if (Instruction *Op = dyn_cast<Instruction>(*OI))
560 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
567 // Collect all of the users of all of the provided root instructions (combined
568 // into a single set).
569 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
570 const SmallInstructionVector &Roots,
571 const SmallInstructionSet &Exclude,
572 const SmallInstructionSet &Final,
573 DenseSet<Instruction *> &Users) {
574 for (SmallInstructionVector::const_iterator I = Roots.begin(),
575 IE = Roots.end(); I != IE; ++I)
576 collectInLoopUserSet(*I, Exclude, Final, Users);
579 static bool isSimpleLoadStore(Instruction *I) {
580 if (LoadInst *LI = dyn_cast<LoadInst>(I))
581 return LI->isSimple();
582 if (StoreInst *SI = dyn_cast<StoreInst>(I))
583 return SI->isSimple();
584 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
585 return !MI->isVolatile();
589 bool LoopReroll::DAGRootTracker::findRoots() {
591 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(IV));
592 Inc = cast<SCEVConstant>(RealIVSCEV->getOperand(1))->
593 getValue()->getZExtValue();
595 // The effective induction variable, IV, is normally also the real induction
596 // variable. When we're dealing with a loop like:
597 // for (int i = 0; i < 500; ++i)
601 // then the real IV is still i, but the effective IV is (3*i).
604 if (Inc == 1 && !findScaleFromMul())
607 // The set of increment instructions for each increment value.
608 if (!collectAllRoots())
611 if (Roots.size() > IL_MaxRerollIterations) {
612 DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
613 << "#Found=" << Roots.size() << ", #Max=" << IL_MaxRerollIterations
621 // Recognize loops that are setup like this:
623 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
624 // %scaled.iv = mul %iv, scale
626 // %scaled.iv.1 = add %scaled.iv, 1
628 // %scaled.iv.2 = add %scaled.iv, 2
630 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
631 // f(%scaled.iv.scale_m_1)
633 // %iv.next = add %iv, 1
634 // %cmp = icmp(%iv, ...)
635 // br %cmp, header, exit
637 // and, if found, set IV = %scaled.iv, and add %iv.next to LoopIncs.
638 bool LoopReroll::DAGRootTracker::findScaleFromMul() {
640 // This is a special case: here we're looking for all uses (except for
641 // the increment) to be multiplied by a common factor. The increment must
642 // be by one. This is to capture loops like:
643 // for (int i = 0; i < 500; ++i) {
644 // foo(3*i); foo(3*i+1); foo(3*i+2);
646 if (RealIV->getNumUses() != 2)
648 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(RealIV));
649 Instruction *User1 = cast<Instruction>(*RealIV->user_begin()),
650 *User2 = cast<Instruction>(*std::next(RealIV->user_begin()));
651 if (!SE->isSCEVable(User1->getType()) || !SE->isSCEVable(User2->getType()))
653 const SCEVAddRecExpr *User1SCEV =
654 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User1)),
656 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User2));
657 if (!User1SCEV || !User1SCEV->isAffine() ||
658 !User2SCEV || !User2SCEV->isAffine())
661 // We assume below that User1 is the scale multiply and User2 is the
662 // increment. If this can't be true, then swap them.
663 if (User1SCEV == RealIVSCEV->getPostIncExpr(*SE)) {
664 std::swap(User1, User2);
665 std::swap(User1SCEV, User2SCEV);
668 if (User2SCEV != RealIVSCEV->getPostIncExpr(*SE))
670 assert(User2SCEV->getStepRecurrence(*SE)->isOne() &&
671 "Invalid non-unit step for multiplicative scaling");
672 LoopIncs.push_back(User2);
674 if (const SCEVConstant *MulScale =
675 dyn_cast<SCEVConstant>(User1SCEV->getStepRecurrence(*SE))) {
676 // Make sure that both the start and step have the same multiplier.
677 if (RealIVSCEV->getStart()->getType() != MulScale->getType())
679 if (SE->getMulExpr(RealIVSCEV->getStart(), MulScale) !=
680 User1SCEV->getStart())
683 ConstantInt *MulScaleCI = MulScale->getValue();
684 if (!MulScaleCI->uge(2) || MulScaleCI->uge(MaxInc))
686 Scale = MulScaleCI->getZExtValue();
691 DEBUG(dbgs() << "LRR: Found possible scaling " << *User1 << "\n");
693 assert(Scale <= MaxInc && "Scale is too large");
694 assert(Scale > 1 && "Scale must be at least 2");
699 // Collect all root increments with respect to the provided induction variable
700 // (normally the PHI, but sometimes a multiply). A root increment is an
701 // instruction, normally an add, with a positive constant less than Scale. In a
702 // rerollable loop, each of these increments is the root of an instruction
703 // graph isomorphic to the others. Also, we collect the final induction
704 // increment (the increment equal to the Scale), and its users in LoopIncs.
705 bool LoopReroll::DAGRootTracker::collectAllRoots() {
706 Roots.resize(Scale-1);
708 for (User *U : IV->users()) {
709 Instruction *UI = cast<Instruction>(U);
710 if (!SE->isSCEVable(UI->getType()))
712 if (UI->getType() != IV->getType())
714 if (!L->contains(UI))
716 if (hasUsesOutsideLoop(UI, L))
719 if (const SCEVConstant *Diff = dyn_cast<SCEVConstant>(SE->getMinusSCEV(
720 SE->getSCEV(UI), SE->getSCEV(IV)))) {
721 uint64_t Idx = Diff->getValue()->getValue().getZExtValue();
722 if (Idx > 0 && Idx < Scale) {
724 // No duplicates allowed.
727 } else if (Idx == Scale && Inc > 1) {
728 LoopIncs.push_back(UI);
733 for (unsigned i = 0; i < Scale-1; ++i) {
741 bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
742 // Populate the MapVector with all instructions in the block, in order first,
743 // so we can iterate over the contents later in perfect order.
744 for (auto &I : *L->getHeader()) {
745 Uses[&I].resize(IL_End);
748 SmallInstructionSet Exclude;
749 Exclude.insert(Roots.begin(), Roots.end());
750 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
752 DenseSet<Instruction*> VBase;
753 collectInLoopUserSet(IV, Exclude, PossibleRedSet, VBase);
754 for (auto *I : VBase) {
759 for (auto *Root : Roots) {
760 DenseSet<Instruction*> V;
761 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
763 // While we're here, check the use sets are the same size.
764 if (V.size() != VBase.size()) {
765 DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
775 // Make sure the loop increments are also accounted for.
777 Exclude.insert(Roots.begin(), Roots.end());
779 DenseSet<Instruction*> V;
780 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
782 Uses[I].set(IL_LoopIncIdx);
785 Uses[RealIV].set(IL_LoopIncIdx);
791 LoopReroll::DAGRootTracker::UsesTy::iterator
792 LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
793 UsesTy::iterator I) {
794 while (I != In.end() && I->second.test(Val) == 0)
799 bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
800 // We now need to check for equivalence of the use graph of each root with
801 // that of the primary induction variable (excluding the roots). Our goal
802 // here is not to solve the full graph isomorphism problem, but rather to
803 // catch common cases without a lot of work. As a result, we will assume
804 // that the relative order of the instructions in each unrolled iteration
805 // is the same (although we will not make an assumption about how the
806 // different iterations are intermixed). Note that while the order must be
807 // the same, the instructions may not be in the same basic block.
809 // An array of just the possible reductions for this scale factor. When we
810 // collect the set of all users of some root instructions, these reduction
811 // instructions are treated as 'final' (their uses are not considered).
812 // This is important because we don't want the root use set to search down
813 // the reduction chain.
814 SmallInstructionSet PossibleRedSet;
815 SmallInstructionSet PossibleRedLastSet;
816 SmallInstructionSet PossibleRedPHISet;
817 Reductions.restrictToScale(Scale, PossibleRedSet,
818 PossibleRedPHISet, PossibleRedLastSet);
820 // Populate "Uses" with where each instruction is used.
821 if (!collectUsedInstructions(PossibleRedSet))
824 // Make sure we mark the reduction PHIs as used in all iterations.
825 for (auto *I : PossibleRedPHISet) {
826 Uses[I].set(IL_LoopIncIdx);
829 // Make sure all instructions in the loop are in one and only one
831 for (auto &KV : Uses) {
832 if (KV.second.count() != 1) {
833 DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
834 << *KV.first << " (#uses=" << KV.second.count() << ")\n");
840 for (auto &KV : Uses) {
841 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
845 for (unsigned Iter = 1; Iter < Scale; ++Iter) {
846 // In addition to regular aliasing information, we need to look for
847 // instructions from later (future) iterations that have side effects
848 // preventing us from reordering them past other instructions with side
850 bool FutureSideEffects = false;
851 AliasSetTracker AST(*AA);
852 // The map between instructions in f(%iv.(i+1)) and f(%iv).
853 DenseMap<Value *, Value *> BaseMap;
855 // Compare iteration Iter to the base.
856 auto BaseIt = nextInstr(0, Uses, Uses.begin());
857 auto RootIt = nextInstr(Iter, Uses, Uses.begin());
858 auto LastRootIt = Uses.begin();
860 while (BaseIt != Uses.end() && RootIt != Uses.end()) {
861 Instruction *BaseInst = BaseIt->first;
862 Instruction *RootInst = RootIt->first;
864 // Skip over the IV or root instructions; only match their users.
865 bool Continue = false;
866 if (BaseInst == RealIV || BaseInst == IV) {
867 BaseIt = nextInstr(0, Uses, ++BaseIt);
870 if (std::find(Roots.begin(), Roots.end(), RootInst) != Roots.end()) {
872 RootIt = nextInstr(Iter, Uses, ++RootIt);
875 if (Continue) continue;
877 // All instructions between the last root and this root
878 // belong to some other iteration. If they belong to a
879 // future iteration, then they're dangerous to alias with.
880 for (; LastRootIt != RootIt; ++LastRootIt) {
881 Instruction *I = LastRootIt->first;
882 if (LastRootIt->second.find_first() < (int)Iter)
884 if (I->mayWriteToMemory())
886 // Note: This is specifically guarded by a check on isa<PHINode>,
887 // which while a valid (somewhat arbitrary) micro-optimization, is
888 // needed because otherwise isSafeToSpeculativelyExecute returns
889 // false on PHI nodes.
890 if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
891 !isSafeToSpeculativelyExecute(I, DL))
892 // Intervening instructions cause side effects.
893 FutureSideEffects = true;
896 if (!BaseInst->isSameOperationAs(RootInst)) {
897 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
898 " vs. " << *RootInst << "\n");
902 // Make sure that this instruction, which is in the use set of this
903 // root instruction, does not also belong to the base set or the set of
904 // some other root instruction.
905 if (RootIt->second.count() > 1) {
906 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
907 " vs. " << *RootInst << " (prev. case overlap)\n");
911 // Make sure that we don't alias with any instruction in the alias set
912 // tracker. If we do, then we depend on a future iteration, and we
914 if (RootInst->mayReadFromMemory())
915 for (auto &K : AST) {
916 if (K.aliasesUnknownInst(RootInst, *AA)) {
917 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
918 " vs. " << *RootInst << " (depends on future store)\n");
923 // If we've past an instruction from a future iteration that may have
924 // side effects, and this instruction might also, then we can't reorder
925 // them, and this matching fails. As an exception, we allow the alias
926 // set tracker to handle regular (simple) load/store dependencies.
927 if (FutureSideEffects &&
928 ((!isSimpleLoadStore(BaseInst) &&
929 !isSafeToSpeculativelyExecute(BaseInst, DL)) ||
930 (!isSimpleLoadStore(RootInst) &&
931 !isSafeToSpeculativelyExecute(RootInst, DL)))) {
932 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
933 " vs. " << *RootInst <<
934 " (side effects prevent reordering)\n");
938 // For instructions that are part of a reduction, if the operation is
939 // associative, then don't bother matching the operands (because we
940 // already know that the instructions are isomorphic, and the order
941 // within the iteration does not matter). For non-associative reductions,
942 // we do need to match the operands, because we need to reject
943 // out-of-order instructions within an iteration!
944 // For example (assume floating-point addition), we need to reject this:
945 // x += a[i]; x += b[i];
946 // x += a[i+1]; x += b[i+1];
947 // x += b[i+2]; x += a[i+2];
948 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
950 if (!(InReduction && BaseInst->isAssociative())) {
951 bool Swapped = false, SomeOpMatched = false;
952 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
953 Value *Op2 = RootInst->getOperand(j);
955 // If this is part of a reduction (and the operation is not
956 // associatve), then we match all operands, but not those that are
957 // part of the reduction.
959 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
960 if (Reductions.isPairInSame(RootInst, Op2I))
963 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
964 if (BMI != BaseMap.end())
966 else if (Roots[Iter-1] == (Instruction*) Op2)
969 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
970 // If we've not already decided to swap the matched operands, and
971 // we've not already matched our first operand (note that we could
972 // have skipped matching the first operand because it is part of a
973 // reduction above), and the instruction is commutative, then try
974 // the swapped match.
975 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
976 BaseInst->getOperand(!j) == Op2) {
979 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
980 << " vs. " << *RootInst << " (operand " << j << ")\n");
985 SomeOpMatched = true;
989 if ((!PossibleRedLastSet.count(BaseInst) &&
990 hasUsesOutsideLoop(BaseInst, L)) ||
991 (!PossibleRedLastSet.count(RootInst) &&
992 hasUsesOutsideLoop(RootInst, L))) {
993 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
994 " vs. " << *RootInst << " (uses outside loop)\n");
998 Reductions.recordPair(BaseInst, RootInst, Iter);
999 BaseMap.insert(std::make_pair(RootInst, BaseInst));
1001 LastRootIt = RootIt;
1002 BaseIt = nextInstr(0, Uses, ++BaseIt);
1003 RootIt = nextInstr(Iter, Uses, ++RootIt);
1005 assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
1006 "Mismatched set sizes!");
1009 DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
1015 void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1016 BasicBlock *Header = L->getHeader();
1017 // Remove instructions associated with non-base iterations.
1018 for (BasicBlock::reverse_iterator J = Header->rbegin();
1019 J != Header->rend();) {
1020 unsigned I = Uses[&*J].find_first();
1021 if (I > 0 && I < IL_LoopIncIdx) {
1022 Instruction *D = &*J;
1023 DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1024 D->eraseFromParent();
1031 // Insert the new induction variable.
1032 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(RealIV));
1033 const SCEV *Start = RealIVSCEV->getStart();
1035 Start = SE->getMulExpr(Start,
1036 SE->getConstant(Start->getType(), Scale));
1037 const SCEVAddRecExpr *H =
1038 cast<SCEVAddRecExpr>(SE->getAddRecExpr(Start,
1039 SE->getConstant(RealIVSCEV->getType(), 1),
1040 L, SCEV::FlagAnyWrap));
1041 { // Limit the lifetime of SCEVExpander.
1042 SCEVExpander Expander(*SE, "reroll");
1043 Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
1045 for (auto &KV : Uses) {
1046 if (KV.second.find_first() == 0)
1047 KV.first->replaceUsesOfWith(IV, NewIV);
1050 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1051 // FIXME: Why do we need this check?
1052 if (Uses[BI].find_first() == IL_LoopIncIdx) {
1053 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1056 SE->getMulExpr(ICSCEV, SE->getConstant(ICSCEV->getType(), Scale));
1057 // Iteration count SCEV minus 1
1058 const SCEV *ICMinus1SCEV =
1059 SE->getMinusSCEV(ICSCEV, SE->getConstant(ICSCEV->getType(), 1));
1061 Value *ICMinus1; // Iteration count minus 1
1062 if (isa<SCEVConstant>(ICMinus1SCEV)) {
1063 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
1065 BasicBlock *Preheader = L->getLoopPreheader();
1067 Preheader = InsertPreheaderForLoop(L, Parent);
1069 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
1070 Preheader->getTerminator());
1074 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond");
1075 BI->setCondition(Cond);
1077 if (BI->getSuccessor(1) != Header)
1078 BI->swapSuccessors();
1083 SimplifyInstructionsInBlock(Header, DL, TLI);
1084 DeleteDeadPHIs(Header, TLI);
1087 // Validate the selected reductions. All iterations must have an isomorphic
1088 // part of the reduction chain and, for non-associative reductions, the chain
1089 // entries must appear in order.
1090 bool LoopReroll::ReductionTracker::validateSelected() {
1091 // For a non-associative reduction, the chain entries must appear in order.
1092 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1095 int PrevIter = 0, BaseCount = 0, Count = 0;
1096 for (Instruction *J : PossibleReds[i]) {
1097 // Note that all instructions in the chain must have been found because
1098 // all instructions in the function must have been assigned to some
1100 int Iter = PossibleRedIter[J];
1101 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1102 !PossibleReds[i].getReducedValue()->isAssociative()) {
1103 DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
1108 if (Iter != PrevIter) {
1109 if (Count != BaseCount) {
1110 DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1111 " reduction use count " << Count <<
1112 " is not equal to the base use count " <<
1131 // For all selected reductions, remove all parts except those in the first
1132 // iteration (and the PHI). Replace outside uses of the reduced value with uses
1133 // of the first-iteration reduced value (in other words, reroll the selected
1135 void LoopReroll::ReductionTracker::replaceSelected() {
1136 // Fixup reductions to refer to the last instruction associated with the
1137 // first iteration (not the last).
1138 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1142 for (int e = PossibleReds[i].size(); j != e; ++j)
1143 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1148 // Replace users with the new end-of-chain value.
1149 SmallInstructionVector Users;
1150 for (User *U : PossibleReds[i].getReducedValue()->users()) {
1151 Users.push_back(cast<Instruction>(U));
1154 for (SmallInstructionVector::iterator J = Users.begin(),
1155 JE = Users.end(); J != JE; ++J)
1156 (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1157 PossibleReds[i][j]);
1161 // Reroll the provided loop with respect to the provided induction variable.
1162 // Generally, we're looking for a loop like this:
1164 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
1166 // %iv.1 = add %iv, 1 <-- a root increment
1168 // %iv.2 = add %iv, 2 <-- a root increment
1170 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1173 // %iv.next = add %iv, scale
1174 // %cmp = icmp(%iv, ...)
1175 // br %cmp, header, exit
1177 // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1178 // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1179 // be intermixed with eachother. The restriction imposed by this algorithm is
1180 // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1181 // etc. be the same.
1183 // First, we collect the use set of %iv, excluding the other increment roots.
1184 // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1185 // times, having collected the use set of f(%iv.(i+1)), during which we:
1186 // - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1187 // the next unmatched instruction in f(%iv.(i+1)).
1188 // - Ensure that both matched instructions don't have any external users
1189 // (with the exception of last-in-chain reduction instructions).
1190 // - Track the (aliasing) write set, and other side effects, of all
1191 // instructions that belong to future iterations that come before the matched
1192 // instructions. If the matched instructions read from that write set, then
1193 // f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1194 // f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1195 // if any of these future instructions had side effects (could not be
1196 // speculatively executed), and so do the matched instructions, when we
1197 // cannot reorder those side-effect-producing instructions, and rerolling
1200 // Finally, we make sure that all loop instructions are either loop increment
1201 // roots, belong to simple latch code, parts of validated reductions, part of
1202 // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1203 // have been validated), then we reroll the loop.
1204 bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1205 const SCEV *IterCount,
1206 ReductionTracker &Reductions) {
1207 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DL);
1209 if (!DAGRoots.findRoots())
1211 DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
1214 if (!DAGRoots.validate(Reductions))
1216 if (!Reductions.validateSelected())
1218 // At this point, we've validated the rerolling, and we're committed to
1221 Reductions.replaceSelected();
1222 DAGRoots.replace(IterCount);
1228 bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
1229 if (skipOptnoneFunction(L))
1232 AA = &getAnalysis<AliasAnalysis>();
1233 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1234 SE = &getAnalysis<ScalarEvolution>();
1235 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1236 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1237 DL = DLP ? &DLP->getDataLayout() : nullptr;
1238 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1240 BasicBlock *Header = L->getHeader();
1241 DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1242 "] Loop %" << Header->getName() << " (" <<
1243 L->getNumBlocks() << " block(s))\n");
1245 bool Changed = false;
1247 // For now, we'll handle only single BB loops.
1248 if (L->getNumBlocks() > 1)
1251 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1254 const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
1255 const SCEV *IterCount =
1256 SE->getAddExpr(LIBETC, SE->getConstant(LIBETC->getType(), 1));
1257 DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1259 // First, we need to find the induction variable with respect to which we can
1260 // reroll (there may be several possible options).
1261 SmallInstructionVector PossibleIVs;
1262 collectPossibleIVs(L, PossibleIVs);
1264 if (PossibleIVs.empty()) {
1265 DEBUG(dbgs() << "LRR: No possible IVs found\n");
1269 ReductionTracker Reductions;
1270 collectPossibleReductions(L, Reductions);
1272 // For each possible IV, collect the associated possible set of 'root' nodes
1273 // (i+1, i+2, etc.).
1274 for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1275 IE = PossibleIVs.end(); I != IE; ++I)
1276 if (reroll(*I, L, Header, IterCount, Reductions)) {