1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
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 performs a strength reduction on array references inside loops that
11 // have as one or more of their components the loop induction variable.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "loop-reduce"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Type.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/LoopPass.h"
25 #include "llvm/Analysis/ScalarEvolutionExpander.h"
26 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ValueHandle.h"
36 #include "llvm/Target/TargetLowering.h"
40 STATISTIC(NumReduced , "Number of IV uses strength reduced");
41 STATISTIC(NumInserted, "Number of PHIs inserted");
42 STATISTIC(NumVariable, "Number of PHIs with variable strides");
43 STATISTIC(NumEliminated, "Number of strides eliminated");
44 STATISTIC(NumShadow, "Number of Shadow IVs optimized");
45 STATISTIC(NumImmSunk, "Number of common expr immediates sunk into uses");
46 STATISTIC(NumLoopCond, "Number of loop terminating conds optimized");
48 static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
56 /// IVStrideUse - Keep track of one use of a strided induction variable, where
57 /// the stride is stored externally. The Offset member keeps track of the
58 /// offset from the IV, User is the actual user of the operand, and
59 /// 'OperandValToReplace' is the operand of the User that is the use.
60 struct VISIBILITY_HIDDEN IVStrideUse {
63 Value *OperandValToReplace;
65 // isUseOfPostIncrementedValue - True if this should use the
66 // post-incremented version of this IV, not the preincremented version.
67 // This can only be set in special cases, such as the terminating setcc
68 // instruction for a loop or uses dominated by the loop.
69 bool isUseOfPostIncrementedValue;
71 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
72 : Offset(Offs), User(U), OperandValToReplace(O),
73 isUseOfPostIncrementedValue(false) {}
76 /// IVUsersOfOneStride - This structure keeps track of all instructions that
77 /// have an operand that is based on the trip count multiplied by some stride.
78 /// The stride for all of these users is common and kept external to this
80 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
81 /// Users - Keep track of all of the users of this stride as well as the
82 /// initial value and the operand that uses the IV.
83 std::vector<IVStrideUse> Users;
85 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
86 Users.push_back(IVStrideUse(Offset, User, Operand));
90 /// IVInfo - This structure keeps track of one IV expression inserted during
91 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
92 /// well as the PHI node and increment value created for rewrite.
93 struct VISIBILITY_HIDDEN IVExpr {
98 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi)
99 : Stride(stride), Base(base), PHI(phi) {}
102 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
103 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
104 struct VISIBILITY_HIDDEN IVsOfOneStride {
105 std::vector<IVExpr> IVs;
107 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI) {
108 IVs.push_back(IVExpr(Stride, Base, PHI));
112 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
118 /// IVUsesByStride - Keep track of all uses of induction variables that we
119 /// are interested in. The key of the map is the stride of the access.
120 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
122 /// IVsByStride - Keep track of all IVs that have been inserted for a
123 /// particular stride.
124 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
126 /// StrideNoReuse - Keep track of all the strides whose ivs cannot be
127 /// reused (nor should they be rewritten to reuse other strides).
128 SmallSet<SCEVHandle, 4> StrideNoReuse;
130 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
131 /// We use this to iterate over the IVUsesByStride collection without being
132 /// dependent on random ordering of pointers in the process.
133 SmallVector<SCEVHandle, 16> StrideOrder;
135 /// DeadInsts - Keep track of instructions we may have made dead, so that
136 /// we can remove them after we are done working.
137 SmallVector<Instruction*, 16> DeadInsts;
139 /// TLI - Keep a pointer of a TargetLowering to consult for determining
140 /// transformation profitability.
141 const TargetLowering *TLI;
144 static char ID; // Pass ID, replacement for typeid
145 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
146 LoopPass(&ID), TLI(tli) {
149 bool runOnLoop(Loop *L, LPPassManager &LPM);
151 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
152 // We split critical edges, so we change the CFG. However, we do update
153 // many analyses if they are around.
154 AU.addPreservedID(LoopSimplifyID);
155 AU.addPreserved<LoopInfo>();
156 AU.addPreserved<DominanceFrontier>();
157 AU.addPreserved<DominatorTree>();
159 AU.addRequiredID(LoopSimplifyID);
160 AU.addRequired<LoopInfo>();
161 AU.addRequired<DominatorTree>();
162 AU.addRequired<ScalarEvolution>();
163 AU.addPreserved<ScalarEvolution>();
167 bool AddUsersIfInteresting(Instruction *I, Loop *L,
168 SmallPtrSet<Instruction*,16> &Processed);
169 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
170 IVStrideUse* &CondUse,
171 const SCEVHandle* &CondStride);
173 void OptimizeIndvars(Loop *L);
174 void OptimizeLoopCountIV(Loop *L);
175 void OptimizeLoopTermCond(Loop *L);
177 /// OptimizeShadowIV - If IV is used in a int-to-float cast
178 /// inside the loop then try to eliminate the cast opeation.
179 void OptimizeShadowIV(Loop *L);
181 /// OptimizeSMax - Rewrite the loop's terminating condition
182 /// if it uses an smax computation.
183 ICmpInst *OptimizeSMax(Loop *L, ICmpInst *Cond,
184 IVStrideUse* &CondUse);
186 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
187 const SCEVHandle *&CondStride);
188 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
189 SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
190 IVExpr&, const Type*,
191 const std::vector<BasedUser>& UsersToProcess);
192 bool ValidScale(bool, int64_t,
193 const std::vector<BasedUser>& UsersToProcess);
194 SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
195 IVUsersOfOneStride &Uses,
197 bool &AllUsesAreAddresses,
198 bool &AllUsesAreOutsideLoop,
199 std::vector<BasedUser> &UsersToProcess);
200 bool ShouldUseFullStrengthReductionMode(
201 const std::vector<BasedUser> &UsersToProcess,
203 bool AllUsesAreAddresses,
205 void PrepareToStrengthReduceFully(
206 std::vector<BasedUser> &UsersToProcess,
208 SCEVHandle CommonExprs,
210 SCEVExpander &PreheaderRewriter);
211 void PrepareToStrengthReduceFromSmallerStride(
212 std::vector<BasedUser> &UsersToProcess,
214 const IVExpr &ReuseIV,
215 Instruction *PreInsertPt);
216 void PrepareToStrengthReduceWithNewPhi(
217 std::vector<BasedUser> &UsersToProcess,
219 SCEVHandle CommonExprs,
221 Instruction *IVIncInsertPt,
223 SCEVExpander &PreheaderRewriter);
224 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
225 IVUsersOfOneStride &Uses,
227 void DeleteTriviallyDeadInstructions();
231 char LoopStrengthReduce::ID = 0;
232 static RegisterPass<LoopStrengthReduce>
233 X("loop-reduce", "Loop Strength Reduction");
235 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
236 return new LoopStrengthReduce(TLI);
239 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
240 /// specified set are trivially dead, delete them and see if this makes any of
241 /// their operands subsequently dead.
242 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
243 if (DeadInsts.empty()) return;
245 // Sort the deadinsts list so that we can trivially eliminate duplicates as we
246 // go. The code below never adds a non-dead instruction to the worklist, but
247 // callers may not be so careful.
248 array_pod_sort(DeadInsts.begin(), DeadInsts.end());
250 // Drop duplicate instructions and those with uses.
251 for (unsigned i = 0, e = DeadInsts.size()-1; i < e; ++i) {
252 Instruction *I = DeadInsts[i];
253 if (!I->use_empty()) DeadInsts[i] = 0;
254 while (i != e && DeadInsts[i+1] == I)
258 while (!DeadInsts.empty()) {
259 Instruction *I = DeadInsts.back();
260 DeadInsts.pop_back();
262 if (I == 0 || !isInstructionTriviallyDead(I))
265 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
266 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
269 DeadInsts.push_back(U);
273 I->eraseFromParent();
278 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a
279 /// subexpression that is an AddRec from a loop other than L. An outer loop
280 /// of L is OK, but not an inner loop nor a disjoint loop.
281 static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
282 // This is very common, put it first.
283 if (isa<SCEVConstant>(S))
285 if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
286 for (unsigned int i=0; i< AE->getNumOperands(); i++)
287 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
291 if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
292 if (const Loop *newLoop = AE->getLoop()) {
295 // if newLoop is an outer loop of L, this is OK.
296 if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
301 if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
302 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
303 containsAddRecFromDifferentLoop(DE->getRHS(), L);
305 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
306 // need this when it is.
307 if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
308 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
309 containsAddRecFromDifferentLoop(DE->getRHS(), L);
311 if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
312 return containsAddRecFromDifferentLoop(CE->getOperand(), L);
316 /// getSCEVStartAndStride - Compute the start and stride of this expression,
317 /// returning false if the expression is not a start/stride pair, or true if it
318 /// is. The stride must be a loop invariant expression, but the start may be
319 /// a mix of loop invariant and loop variant expressions. The start cannot,
320 /// however, contain an AddRec from a different loop, unless that loop is an
321 /// outer loop of the current loop.
322 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
323 SCEVHandle &Start, SCEVHandle &Stride,
324 ScalarEvolution *SE, DominatorTree *DT) {
325 SCEVHandle TheAddRec = Start; // Initialize to zero.
327 // If the outer level is an AddExpr, the operands are all start values except
328 // for a nested AddRecExpr.
329 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
330 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
331 if (const SCEVAddRecExpr *AddRec =
332 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
333 if (AddRec->getLoop() == L)
334 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
336 return false; // Nested IV of some sort?
338 Start = SE->getAddExpr(Start, AE->getOperand(i));
341 } else if (isa<SCEVAddRecExpr>(SH)) {
344 return false; // not analyzable.
347 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
348 if (!AddRec || AddRec->getLoop() != L) return false;
350 // FIXME: Generalize to non-affine IV's.
351 if (!AddRec->isAffine()) return false;
353 // If Start contains an SCEVAddRecExpr from a different loop, other than an
354 // outer loop of the current loop, reject it. SCEV has no concept of
355 // operating on more than one loop at a time so don't confuse it with such
357 if (containsAddRecFromDifferentLoop(AddRec->getOperand(0), L))
360 Start = SE->getAddExpr(Start, AddRec->getOperand(0));
362 if (!isa<SCEVConstant>(AddRec->getOperand(1))) {
363 // If stride is an instruction, make sure it dominates the loop preheader.
364 // Otherwise we could end up with a use before def situation.
365 BasicBlock *Preheader = L->getLoopPreheader();
366 if (!AddRec->getOperand(1)->dominates(Preheader, DT))
369 DOUT << "[" << L->getHeader()->getName()
370 << "] Variable stride: " << *AddRec << "\n";
373 Stride = AddRec->getOperand(1);
377 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
378 /// and now we need to decide whether the user should use the preinc or post-inc
379 /// value. If this user should use the post-inc version of the IV, return true.
381 /// Choosing wrong here can break dominance properties (if we choose to use the
382 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
383 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
384 /// should use the post-inc value).
385 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
386 Loop *L, DominatorTree *DT, Pass *P,
387 SmallVectorImpl<Instruction*> &DeadInsts){
388 // If the user is in the loop, use the preinc value.
389 if (L->contains(User->getParent())) return false;
391 BasicBlock *LatchBlock = L->getLoopLatch();
393 // Ok, the user is outside of the loop. If it is dominated by the latch
394 // block, use the post-inc value.
395 if (DT->dominates(LatchBlock, User->getParent()))
398 // There is one case we have to be careful of: PHI nodes. These little guys
399 // can live in blocks that do not dominate the latch block, but (since their
400 // uses occur in the predecessor block, not the block the PHI lives in) should
401 // still use the post-inc value. Check for this case now.
402 PHINode *PN = dyn_cast<PHINode>(User);
403 if (!PN) return false; // not a phi, not dominated by latch block.
405 // Look at all of the uses of IV by the PHI node. If any use corresponds to
406 // a block that is not dominated by the latch block, give up and use the
407 // preincremented value.
408 unsigned NumUses = 0;
409 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
410 if (PN->getIncomingValue(i) == IV) {
412 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
416 // Okay, all uses of IV by PN are in predecessor blocks that really are
417 // dominated by the latch block. Use the post-incremented value.
421 /// isAddressUse - Returns true if the specified instruction is using the
422 /// specified value as an address.
423 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
424 bool isAddress = isa<LoadInst>(Inst);
425 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
426 if (SI->getOperand(1) == OperandVal)
428 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
429 // Addressing modes can also be folded into prefetches and a variety
431 switch (II->getIntrinsicID()) {
433 case Intrinsic::prefetch:
434 case Intrinsic::x86_sse2_loadu_dq:
435 case Intrinsic::x86_sse2_loadu_pd:
436 case Intrinsic::x86_sse_loadu_ps:
437 case Intrinsic::x86_sse_storeu_ps:
438 case Intrinsic::x86_sse2_storeu_pd:
439 case Intrinsic::x86_sse2_storeu_dq:
440 case Intrinsic::x86_sse2_storel_dq:
441 if (II->getOperand(1) == OperandVal)
449 /// getAccessType - Return the type of the memory being accessed.
450 static const Type *getAccessType(const Instruction *Inst) {
451 const Type *UseTy = Inst->getType();
452 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
453 UseTy = SI->getOperand(0)->getType();
454 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
455 // Addressing modes can also be folded into prefetches and a variety
457 switch (II->getIntrinsicID()) {
459 case Intrinsic::x86_sse_storeu_ps:
460 case Intrinsic::x86_sse2_storeu_pd:
461 case Intrinsic::x86_sse2_storeu_dq:
462 case Intrinsic::x86_sse2_storel_dq:
463 UseTy = II->getOperand(1)->getType();
470 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
471 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
472 /// return true. Otherwise, return false.
473 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
474 SmallPtrSet<Instruction*,16> &Processed) {
475 if (!SE->isSCEVable(I->getType()))
476 return false; // Void and FP expressions cannot be reduced.
478 // LSR is not APInt clean, do not touch integers bigger than 64-bits.
479 if (SE->getTypeSizeInBits(I->getType()) > 64)
482 if (!Processed.insert(I))
483 return true; // Instruction already handled.
485 // Get the symbolic expression for this instruction.
486 SCEVHandle ISE = SE->getSCEV(I);
487 if (isa<SCEVCouldNotCompute>(ISE)) return false;
489 // Get the start and stride for this expression.
490 SCEVHandle Start = SE->getIntegerSCEV(0, ISE->getType());
491 SCEVHandle Stride = Start;
492 if (!getSCEVStartAndStride(ISE, L, Start, Stride, SE, DT))
493 return false; // Non-reducible symbolic expression, bail out.
495 std::vector<Instruction *> IUsers;
496 // Collect all I uses now because IVUseShouldUsePostIncValue may
497 // invalidate use_iterator.
498 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
499 IUsers.push_back(cast<Instruction>(*UI));
501 for (unsigned iused_index = 0, iused_size = IUsers.size();
502 iused_index != iused_size; ++iused_index) {
504 Instruction *User = IUsers[iused_index];
506 // Do not infinitely recurse on PHI nodes.
507 if (isa<PHINode>(User) && Processed.count(User))
510 // Descend recursively, but not into PHI nodes outside the current loop.
511 // It's important to see the entire expression outside the loop to get
512 // choices that depend on addressing mode use right, although we won't
513 // consider references ouside the loop in all cases.
514 // If User is already in Processed, we don't want to recurse into it again,
515 // but do want to record a second reference in the same instruction.
516 bool AddUserToIVUsers = false;
517 if (LI->getLoopFor(User->getParent()) != L) {
518 if (isa<PHINode>(User) || Processed.count(User) ||
519 !AddUsersIfInteresting(User, L, Processed)) {
520 DOUT << "FOUND USER in other loop: " << *User
521 << " OF SCEV: " << *ISE << "\n";
522 AddUserToIVUsers = true;
524 } else if (Processed.count(User) ||
525 !AddUsersIfInteresting(User, L, Processed)) {
526 DOUT << "FOUND USER: " << *User
527 << " OF SCEV: " << *ISE << "\n";
528 AddUserToIVUsers = true;
531 if (AddUserToIVUsers) {
532 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
533 if (StrideUses.Users.empty()) // First occurrence of this stride?
534 StrideOrder.push_back(Stride);
536 // Okay, we found a user that we cannot reduce. Analyze the instruction
537 // and decide what to do with it. If we are a use inside of the loop, use
538 // the value before incrementation, otherwise use it after incrementation.
539 if (IVUseShouldUsePostIncValue(User, I, L, DT, this, DeadInsts)) {
540 // The value used will be incremented by the stride more than we are
541 // expecting, so subtract this off.
542 SCEVHandle NewStart = SE->getMinusSCEV(Start, Stride);
543 StrideUses.addUser(NewStart, User, I);
544 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
545 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
547 StrideUses.addUser(Start, User, I);
555 /// BasedUser - For a particular base value, keep information about how we've
556 /// partitioned the expression so far.
558 /// SE - The current ScalarEvolution object.
561 /// Base - The Base value for the PHI node that needs to be inserted for
562 /// this use. As the use is processed, information gets moved from this
563 /// field to the Imm field (below). BasedUser values are sorted by this
567 /// Inst - The instruction using the induction variable.
570 /// OperandValToReplace - The operand value of Inst to replace with the
572 Value *OperandValToReplace;
574 /// Imm - The immediate value that should be added to the base immediately
575 /// before Inst, because it will be folded into the imm field of the
576 /// instruction. This is also sometimes used for loop-variant values that
577 /// must be added inside the loop.
580 /// Phi - The induction variable that performs the striding that
581 /// should be used for this user.
584 // isUseOfPostIncrementedValue - True if this should use the
585 // post-incremented version of this IV, not the preincremented version.
586 // This can only be set in special cases, such as the terminating setcc
587 // instruction for a loop and uses outside the loop that are dominated by
589 bool isUseOfPostIncrementedValue;
591 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
592 : SE(se), Base(IVSU.Offset), Inst(IVSU.User),
593 OperandValToReplace(IVSU.OperandValToReplace),
594 Imm(SE->getIntegerSCEV(0, Base->getType())),
595 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
597 // Once we rewrite the code to insert the new IVs we want, update the
598 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
600 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
601 Instruction *InsertPt,
602 SCEVExpander &Rewriter, Loop *L, Pass *P,
603 SmallVectorImpl<Instruction*> &DeadInsts);
605 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
607 SCEVExpander &Rewriter,
608 Instruction *IP, Loop *L);
613 void BasedUser::dump() const {
614 cerr << " Base=" << *Base;
615 cerr << " Imm=" << *Imm;
616 cerr << " Inst: " << *Inst;
619 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
621 SCEVExpander &Rewriter,
622 Instruction *IP, Loop *L) {
623 // Figure out where we *really* want to insert this code. In particular, if
624 // the user is inside of a loop that is nested inside of L, we really don't
625 // want to insert this expression before the user, we'd rather pull it out as
626 // many loops as possible.
627 LoopInfo &LI = Rewriter.getLoopInfo();
628 Instruction *BaseInsertPt = IP;
630 // Figure out the most-nested loop that IP is in.
631 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
633 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
634 // the preheader of the outer-most loop where NewBase is not loop invariant.
635 if (L->contains(IP->getParent()))
636 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
637 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
638 InsertLoop = InsertLoop->getParentLoop();
641 Value *Base = Rewriter.expandCodeFor(NewBase, Ty, BaseInsertPt);
643 // If there is no immediate value, skip the next part.
647 // If we are inserting the base and imm values in the same block, make sure to
648 // adjust the IP position if insertion reused a result.
649 if (IP == BaseInsertPt)
650 IP = Rewriter.getInsertionPoint();
652 // Always emit the immediate (if non-zero) into the same block as the user.
653 SCEVHandle NewValSCEV = SE->getAddExpr(SE->getUnknown(Base), Imm);
654 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
658 // Once we rewrite the code to insert the new IVs we want, update the
659 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
660 // to it. NewBasePt is the last instruction which contributes to the
661 // value of NewBase in the case that it's a diffferent instruction from
662 // the PHI that NewBase is computed from, or null otherwise.
664 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
665 Instruction *NewBasePt,
666 SCEVExpander &Rewriter, Loop *L, Pass *P,
667 SmallVectorImpl<Instruction*> &DeadInsts){
668 if (!isa<PHINode>(Inst)) {
669 // By default, insert code at the user instruction.
670 BasicBlock::iterator InsertPt = Inst;
672 // However, if the Operand is itself an instruction, the (potentially
673 // complex) inserted code may be shared by many users. Because of this, we
674 // want to emit code for the computation of the operand right before its old
675 // computation. This is usually safe, because we obviously used to use the
676 // computation when it was computed in its current block. However, in some
677 // cases (e.g. use of a post-incremented induction variable) the NewBase
678 // value will be pinned to live somewhere after the original computation.
679 // In this case, we have to back off.
681 // If this is a use outside the loop (which means after, since it is based
682 // on a loop indvar) we use the post-incremented value, so that we don't
683 // artificially make the preinc value live out the bottom of the loop.
684 if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
685 if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
686 InsertPt = NewBasePt;
688 } else if (Instruction *OpInst
689 = dyn_cast<Instruction>(OperandValToReplace)) {
691 while (isa<PHINode>(InsertPt)) ++InsertPt;
694 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
695 OperandValToReplace->getType(),
696 Rewriter, InsertPt, L);
697 // Replace the use of the operand Value with the new Phi we just created.
698 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
700 DOUT << " Replacing with ";
701 DEBUG(WriteAsOperand(*DOUT, NewVal, /*PrintType=*/false));
702 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
706 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
707 // expression into each operand block that uses it. Note that PHI nodes can
708 // have multiple entries for the same predecessor. We use a map to make sure
709 // that a PHI node only has a single Value* for each predecessor (which also
710 // prevents us from inserting duplicate code in some blocks).
711 DenseMap<BasicBlock*, Value*> InsertedCode;
712 PHINode *PN = cast<PHINode>(Inst);
713 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
714 if (PN->getIncomingValue(i) == OperandValToReplace) {
715 // If the original expression is outside the loop, put the replacement
716 // code in the same place as the original expression,
717 // which need not be an immediate predecessor of this PHI. This way we
718 // need only one copy of it even if it is referenced multiple times in
719 // the PHI. We don't do this when the original expression is inside the
720 // loop because multiple copies sometimes do useful sinking of code in
722 Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
723 if (L->contains(OldLoc->getParent())) {
724 // If this is a critical edge, split the edge so that we do not insert
725 // the code on all predecessor/successor paths. We do this unless this
726 // is the canonical backedge for this loop, as this can make some
727 // inserted code be in an illegal position.
728 BasicBlock *PHIPred = PN->getIncomingBlock(i);
729 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
730 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
732 // First step, split the critical edge.
733 SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
735 // Next step: move the basic block. In particular, if the PHI node
736 // is outside of the loop, and PredTI is in the loop, we want to
737 // move the block to be immediately before the PHI block, not
738 // immediately after PredTI.
739 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
740 BasicBlock *NewBB = PN->getIncomingBlock(i);
741 NewBB->moveBefore(PN->getParent());
744 // Splitting the edge can reduce the number of PHI entries we have.
745 e = PN->getNumIncomingValues();
748 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
750 // Insert the code into the end of the predecessor block.
751 Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
752 PN->getIncomingBlock(i)->getTerminator() :
753 OldLoc->getParent()->getTerminator();
754 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
755 Rewriter, InsertPt, L);
757 DOUT << " Changing PHI use to ";
758 DEBUG(WriteAsOperand(*DOUT, Code, /*PrintType=*/false));
759 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
762 // Replace the use of the operand Value with the new Phi we just created.
763 PN->setIncomingValue(i, Code);
768 // PHI node might have become a constant value after SplitCriticalEdge.
769 DeadInsts.push_back(Inst);
773 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
774 /// mode, and does not need to be put in a register first.
775 static bool fitsInAddressMode(const SCEVHandle &V, const Type *UseTy,
776 const TargetLowering *TLI, bool HasBaseReg) {
777 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
778 int64_t VC = SC->getValue()->getSExtValue();
780 TargetLowering::AddrMode AM;
782 AM.HasBaseReg = HasBaseReg;
783 return TLI->isLegalAddressingMode(AM, UseTy);
785 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
786 return (VC > -(1 << 16) && VC < (1 << 16)-1);
790 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
791 if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
793 TargetLowering::AddrMode AM;
795 AM.HasBaseReg = HasBaseReg;
796 return TLI->isLegalAddressingMode(AM, UseTy);
798 // Default: assume global addresses are not legal.
805 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
806 /// loop varying to the Imm operand.
807 static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
808 Loop *L, ScalarEvolution *SE) {
809 if (Val->isLoopInvariant(L)) return; // Nothing to do.
811 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
812 std::vector<SCEVHandle> NewOps;
813 NewOps.reserve(SAE->getNumOperands());
815 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
816 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
817 // If this is a loop-variant expression, it must stay in the immediate
818 // field of the expression.
819 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
821 NewOps.push_back(SAE->getOperand(i));
825 Val = SE->getIntegerSCEV(0, Val->getType());
827 Val = SE->getAddExpr(NewOps);
828 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
829 // Try to pull immediates out of the start value of nested addrec's.
830 SCEVHandle Start = SARE->getStart();
831 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
833 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
835 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
837 // Otherwise, all of Val is variant, move the whole thing over.
838 Imm = SE->getAddExpr(Imm, Val);
839 Val = SE->getIntegerSCEV(0, Val->getType());
844 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
845 /// that can fit into the immediate field of instructions in the target.
846 /// Accumulate these immediate values into the Imm value.
847 static void MoveImmediateValues(const TargetLowering *TLI,
849 SCEVHandle &Val, SCEVHandle &Imm,
850 bool isAddress, Loop *L,
851 ScalarEvolution *SE) {
852 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
853 std::vector<SCEVHandle> NewOps;
854 NewOps.reserve(SAE->getNumOperands());
856 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
857 SCEVHandle NewOp = SAE->getOperand(i);
858 MoveImmediateValues(TLI, UseTy, NewOp, Imm, isAddress, L, SE);
860 if (!NewOp->isLoopInvariant(L)) {
861 // If this is a loop-variant expression, it must stay in the immediate
862 // field of the expression.
863 Imm = SE->getAddExpr(Imm, NewOp);
865 NewOps.push_back(NewOp);
870 Val = SE->getIntegerSCEV(0, Val->getType());
872 Val = SE->getAddExpr(NewOps);
874 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
875 // Try to pull immediates out of the start value of nested addrec's.
876 SCEVHandle Start = SARE->getStart();
877 MoveImmediateValues(TLI, UseTy, Start, Imm, isAddress, L, SE);
879 if (Start != SARE->getStart()) {
880 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
882 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
885 } else if (const SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
886 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
887 if (isAddress && fitsInAddressMode(SME->getOperand(0), UseTy, TLI, false) &&
888 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
890 SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
891 SCEVHandle NewOp = SME->getOperand(1);
892 MoveImmediateValues(TLI, UseTy, NewOp, SubImm, isAddress, L, SE);
894 // If we extracted something out of the subexpressions, see if we can
896 if (NewOp != SME->getOperand(1)) {
897 // Scale SubImm up by "8". If the result is a target constant, we are
899 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
900 if (fitsInAddressMode(SubImm, UseTy, TLI, false)) {
901 // Accumulate the immediate.
902 Imm = SE->getAddExpr(Imm, SubImm);
904 // Update what is left of 'Val'.
905 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
912 // Loop-variant expressions must stay in the immediate field of the
914 if ((isAddress && fitsInAddressMode(Val, UseTy, TLI, false)) ||
915 !Val->isLoopInvariant(L)) {
916 Imm = SE->getAddExpr(Imm, Val);
917 Val = SE->getIntegerSCEV(0, Val->getType());
921 // Otherwise, no immediates to move.
924 static void MoveImmediateValues(const TargetLowering *TLI,
926 SCEVHandle &Val, SCEVHandle &Imm,
927 bool isAddress, Loop *L,
928 ScalarEvolution *SE) {
929 const Type *UseTy = getAccessType(User);
930 MoveImmediateValues(TLI, UseTy, Val, Imm, isAddress, L, SE);
933 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
934 /// added together. This is used to reassociate common addition subexprs
935 /// together for maximal sharing when rewriting bases.
936 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
938 ScalarEvolution *SE) {
939 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
940 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
941 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
942 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
943 SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
944 if (SARE->getOperand(0) == Zero) {
945 SubExprs.push_back(Expr);
947 // Compute the addrec with zero as its base.
948 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
949 Ops[0] = Zero; // Start with zero base.
950 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
953 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
955 } else if (!Expr->isZero()) {
957 SubExprs.push_back(Expr);
961 // This is logically local to the following function, but C++ says we have
962 // to make it file scope.
963 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
965 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
966 /// the Uses, removing any common subexpressions, except that if all such
967 /// subexpressions can be folded into an addressing mode for all uses inside
968 /// the loop (this case is referred to as "free" in comments herein) we do
969 /// not remove anything. This looks for things like (a+b+c) and
970 /// (a+c+d) and computes the common (a+c) subexpression. The common expression
971 /// is *removed* from the Bases and returned.
973 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
974 ScalarEvolution *SE, Loop *L,
975 const TargetLowering *TLI) {
976 unsigned NumUses = Uses.size();
978 // Only one use? This is a very common case, so we handle it specially and
980 SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
981 SCEVHandle Result = Zero;
982 SCEVHandle FreeResult = Zero;
984 // If the use is inside the loop, use its base, regardless of what it is:
985 // it is clearly shared across all the IV's. If the use is outside the loop
986 // (which means after it) we don't want to factor anything *into* the loop,
987 // so just use 0 as the base.
988 if (L->contains(Uses[0].Inst->getParent()))
989 std::swap(Result, Uses[0].Base);
993 // To find common subexpressions, count how many of Uses use each expression.
994 // If any subexpressions are used Uses.size() times, they are common.
995 // Also track whether all uses of each expression can be moved into an
996 // an addressing mode "for free"; such expressions are left within the loop.
997 // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
998 std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
1000 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
1001 // order we see them.
1002 std::vector<SCEVHandle> UniqueSubExprs;
1004 std::vector<SCEVHandle> SubExprs;
1005 unsigned NumUsesInsideLoop = 0;
1006 for (unsigned i = 0; i != NumUses; ++i) {
1007 // If the user is outside the loop, just ignore it for base computation.
1008 // Since the user is outside the loop, it must be *after* the loop (if it
1009 // were before, it could not be based on the loop IV). We don't want users
1010 // after the loop to affect base computation of values *inside* the loop,
1011 // because we can always add their offsets to the result IV after the loop
1012 // is done, ensuring we get good code inside the loop.
1013 if (!L->contains(Uses[i].Inst->getParent()))
1015 NumUsesInsideLoop++;
1017 // If the base is zero (which is common), return zero now, there are no
1018 // CSEs we can find.
1019 if (Uses[i].Base == Zero) return Zero;
1021 // If this use is as an address we may be able to put CSEs in the addressing
1022 // mode rather than hoisting them.
1023 bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
1024 // We may need the UseTy below, but only when isAddrUse, so compute it
1025 // only in that case.
1026 const Type *UseTy = 0;
1028 UseTy = getAccessType(Uses[i].Inst);
1030 // Split the expression into subexprs.
1031 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
1032 // Add one to SubExpressionUseData.Count for each subexpr present, and
1033 // if the subexpr is not a valid immediate within an addressing mode use,
1034 // set SubExpressionUseData.notAllUsesAreFree. We definitely want to
1035 // hoist these out of the loop (if they are common to all uses).
1036 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1037 if (++SubExpressionUseData[SubExprs[j]].Count == 1)
1038 UniqueSubExprs.push_back(SubExprs[j]);
1039 if (!isAddrUse || !fitsInAddressMode(SubExprs[j], UseTy, TLI, false))
1040 SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
1045 // Now that we know how many times each is used, build Result. Iterate over
1046 // UniqueSubexprs so that we have a stable ordering.
1047 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
1048 std::map<SCEVHandle, SubExprUseData>::iterator I =
1049 SubExpressionUseData.find(UniqueSubExprs[i]);
1050 assert(I != SubExpressionUseData.end() && "Entry not found?");
1051 if (I->second.Count == NumUsesInsideLoop) { // Found CSE!
1052 if (I->second.notAllUsesAreFree)
1053 Result = SE->getAddExpr(Result, I->first);
1055 FreeResult = SE->getAddExpr(FreeResult, I->first);
1057 // Remove non-cse's from SubExpressionUseData.
1058 SubExpressionUseData.erase(I);
1061 if (FreeResult != Zero) {
1062 // We have some subexpressions that can be subsumed into addressing
1063 // modes in every use inside the loop. However, it's possible that
1064 // there are so many of them that the combined FreeResult cannot
1065 // be subsumed, or that the target cannot handle both a FreeResult
1066 // and a Result in the same instruction (for example because it would
1067 // require too many registers). Check this.
1068 for (unsigned i=0; i<NumUses; ++i) {
1069 if (!L->contains(Uses[i].Inst->getParent()))
1071 // We know this is an addressing mode use; if there are any uses that
1072 // are not, FreeResult would be Zero.
1073 const Type *UseTy = getAccessType(Uses[i].Inst);
1074 if (!fitsInAddressMode(FreeResult, UseTy, TLI, Result!=Zero)) {
1075 // FIXME: could split up FreeResult into pieces here, some hoisted
1076 // and some not. There is no obvious advantage to this.
1077 Result = SE->getAddExpr(Result, FreeResult);
1084 // If we found no CSE's, return now.
1085 if (Result == Zero) return Result;
1087 // If we still have a FreeResult, remove its subexpressions from
1088 // SubExpressionUseData. This means they will remain in the use Bases.
1089 if (FreeResult != Zero) {
1090 SeparateSubExprs(SubExprs, FreeResult, SE);
1091 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1092 std::map<SCEVHandle, SubExprUseData>::iterator I =
1093 SubExpressionUseData.find(SubExprs[j]);
1094 SubExpressionUseData.erase(I);
1099 // Otherwise, remove all of the CSE's we found from each of the base values.
1100 for (unsigned i = 0; i != NumUses; ++i) {
1101 // Uses outside the loop don't necessarily include the common base, but
1102 // the final IV value coming into those uses does. Instead of trying to
1103 // remove the pieces of the common base, which might not be there,
1104 // subtract off the base to compensate for this.
1105 if (!L->contains(Uses[i].Inst->getParent())) {
1106 Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
1110 // Split the expression into subexprs.
1111 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
1113 // Remove any common subexpressions.
1114 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
1115 if (SubExpressionUseData.count(SubExprs[j])) {
1116 SubExprs.erase(SubExprs.begin()+j);
1120 // Finally, add the non-shared expressions together.
1121 if (SubExprs.empty())
1122 Uses[i].Base = Zero;
1124 Uses[i].Base = SE->getAddExpr(SubExprs);
1131 /// ValidScale - Check whether the given Scale is valid for all loads and
1132 /// stores in UsersToProcess.
1134 bool LoopStrengthReduce::ValidScale(bool HasBaseReg, int64_t Scale,
1135 const std::vector<BasedUser>& UsersToProcess) {
1139 for (unsigned i = 0, e = UsersToProcess.size(); i!=e; ++i) {
1140 // If this is a load or other access, pass the type of the access in.
1141 const Type *AccessTy = Type::VoidTy;
1142 if (isAddressUse(UsersToProcess[i].Inst,
1143 UsersToProcess[i].OperandValToReplace))
1144 AccessTy = getAccessType(UsersToProcess[i].Inst);
1145 else if (isa<PHINode>(UsersToProcess[i].Inst))
1148 TargetLowering::AddrMode AM;
1149 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
1150 AM.BaseOffs = SC->getValue()->getSExtValue();
1151 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
1154 // If load[imm+r*scale] is illegal, bail out.
1155 if (!TLI->isLegalAddressingMode(AM, AccessTy))
1161 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
1163 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
1167 Ty1 = SE->getEffectiveSCEVType(Ty1);
1168 Ty2 = SE->getEffectiveSCEVType(Ty2);
1171 if (Ty1->canLosslesslyBitCastTo(Ty2))
1173 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
1178 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
1179 /// of a previous stride and it is a legal value for the target addressing
1180 /// mode scale component and optional base reg. This allows the users of
1181 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
1182 /// reuse is possible. Factors can be negative on same targets, e.g. ARM.
1184 /// If all uses are outside the loop, we don't require that all multiplies
1185 /// be folded into the addressing mode, nor even that the factor be constant;
1186 /// a multiply (executed once) outside the loop is better than another IV
1187 /// within. Well, usually.
1188 SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
1189 bool AllUsesAreAddresses,
1190 bool AllUsesAreOutsideLoop,
1191 const SCEVHandle &Stride,
1192 IVExpr &IV, const Type *Ty,
1193 const std::vector<BasedUser>& UsersToProcess) {
1194 if (StrideNoReuse.count(Stride))
1195 return SE->getIntegerSCEV(0, Stride->getType());
1197 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
1198 int64_t SInt = SC->getValue()->getSExtValue();
1199 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1201 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1202 IVsByStride.find(StrideOrder[NewStride]);
1203 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first) ||
1204 StrideNoReuse.count(SI->first))
1206 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1207 if (SI->first != Stride &&
1208 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
1210 int64_t Scale = SInt / SSInt;
1211 // Check that this stride is valid for all the types used for loads and
1212 // stores; if it can be used for some and not others, we might as well use
1213 // the original stride everywhere, since we have to create the IV for it
1214 // anyway. If the scale is 1, then we don't need to worry about folding
1217 (AllUsesAreAddresses &&
1218 ValidScale(HasBaseReg, Scale, UsersToProcess)))
1219 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1220 IE = SI->second.IVs.end(); II != IE; ++II)
1221 // FIXME: Only handle base == 0 for now.
1222 // Only reuse previous IV if it would not require a type conversion.
1223 if (II->Base->isZero() &&
1224 !RequiresTypeConversion(II->Base->getType(), Ty)) {
1226 return SE->getIntegerSCEV(Scale, Stride->getType());
1229 } else if (AllUsesAreOutsideLoop) {
1230 // Accept nonconstant strides here; it is really really right to substitute
1231 // an existing IV if we can.
1232 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1234 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1235 IVsByStride.find(StrideOrder[NewStride]);
1236 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1238 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1239 if (SI->first != Stride && SSInt != 1)
1241 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1242 IE = SI->second.IVs.end(); II != IE; ++II)
1243 // Accept nonzero base here.
1244 // Only reuse previous IV if it would not require a type conversion.
1245 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1250 // Special case, old IV is -1*x and this one is x. Can treat this one as
1252 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1254 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1255 IVsByStride.find(StrideOrder[NewStride]);
1256 if (SI == IVsByStride.end())
1258 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1259 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
1260 if (Stride == ME->getOperand(1) &&
1261 SC->getValue()->getSExtValue() == -1LL)
1262 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1263 IE = SI->second.IVs.end(); II != IE; ++II)
1264 // Accept nonzero base here.
1265 // Only reuse previous IV if it would not require type conversion.
1266 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1268 return SE->getIntegerSCEV(-1LL, Stride->getType());
1272 return SE->getIntegerSCEV(0, Stride->getType());
1275 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1276 /// returns true if Val's isUseOfPostIncrementedValue is true.
1277 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1278 return Val.isUseOfPostIncrementedValue;
1281 /// isNonConstantNegative - Return true if the specified scev is negated, but
1283 static bool isNonConstantNegative(const SCEVHandle &Expr) {
1284 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1285 if (!Mul) return false;
1287 // If there is a constant factor, it will be first.
1288 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1289 if (!SC) return false;
1291 // Return true if the value is negative, this matches things like (-42 * V).
1292 return SC->getValue()->getValue().isNegative();
1295 // CollectIVUsers - Transform our list of users and offsets to a bit more
1296 // complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1297 // of the strided accesses, as well as the old information from Uses. We
1298 // progressively move information from the Base field to the Imm field, until
1299 // we eventually have the full access expression to rewrite the use.
1300 SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1301 IVUsersOfOneStride &Uses,
1303 bool &AllUsesAreAddresses,
1304 bool &AllUsesAreOutsideLoop,
1305 std::vector<BasedUser> &UsersToProcess) {
1306 UsersToProcess.reserve(Uses.Users.size());
1307 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
1308 UsersToProcess.push_back(BasedUser(Uses.Users[i], SE));
1310 // Move any loop variant operands from the offset field to the immediate
1311 // field of the use, so that we don't try to use something before it is
1313 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1314 UsersToProcess.back().Imm, L, SE);
1315 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1316 "Base value is not loop invariant!");
1319 // We now have a whole bunch of uses of like-strided induction variables, but
1320 // they might all have different bases. We want to emit one PHI node for this
1321 // stride which we fold as many common expressions (between the IVs) into as
1322 // possible. Start by identifying the common expressions in the base values
1323 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1324 // "A+B"), emit it to the preheader, then remove the expression from the
1325 // UsersToProcess base values.
1326 SCEVHandle CommonExprs =
1327 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1329 // Next, figure out what we can represent in the immediate fields of
1330 // instructions. If we can represent anything there, move it to the imm
1331 // fields of the BasedUsers. We do this so that it increases the commonality
1332 // of the remaining uses.
1333 unsigned NumPHI = 0;
1334 bool HasAddress = false;
1335 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1336 // If the user is not in the current loop, this means it is using the exit
1337 // value of the IV. Do not put anything in the base, make sure it's all in
1338 // the immediate field to allow as much factoring as possible.
1339 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1340 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1341 UsersToProcess[i].Base);
1342 UsersToProcess[i].Base =
1343 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1345 // Not all uses are outside the loop.
1346 AllUsesAreOutsideLoop = false;
1348 // Addressing modes can be folded into loads and stores. Be careful that
1349 // the store is through the expression, not of the expression though.
1351 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1352 UsersToProcess[i].OperandValToReplace);
1353 if (isa<PHINode>(UsersToProcess[i].Inst)) {
1361 // If this use isn't an address, then not all uses are addresses.
1362 if (!isAddress && !isPHI)
1363 AllUsesAreAddresses = false;
1365 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1366 UsersToProcess[i].Imm, isAddress, L, SE);
1370 // If one of the use is a PHI node and all other uses are addresses, still
1371 // allow iv reuse. Essentially we are trading one constant multiplication
1372 // for one fewer iv.
1374 AllUsesAreAddresses = false;
1376 // There are no in-loop address uses.
1377 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1378 AllUsesAreAddresses = false;
1383 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1384 /// is valid and profitable for the given set of users of a stride. In
1385 /// full strength-reduction mode, all addresses at the current stride are
1386 /// strength-reduced all the way down to pointer arithmetic.
1388 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1389 const std::vector<BasedUser> &UsersToProcess,
1391 bool AllUsesAreAddresses,
1392 SCEVHandle Stride) {
1393 if (!EnableFullLSRMode)
1396 // The heuristics below aim to avoid increasing register pressure, but
1397 // fully strength-reducing all the addresses increases the number of
1398 // add instructions, so don't do this when optimizing for size.
1399 // TODO: If the loop is large, the savings due to simpler addresses
1400 // may oughtweight the costs of the extra increment instructions.
1401 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1404 // TODO: For now, don't do full strength reduction if there could
1405 // potentially be greater-stride multiples of the current stride
1406 // which could reuse the current stride IV.
1407 if (StrideOrder.back() != Stride)
1410 // Iterate through the uses to find conditions that automatically rule out
1412 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1413 const SCEV *Base = UsersToProcess[i].Base;
1414 const SCEV *Imm = UsersToProcess[i].Imm;
1415 // If any users have a loop-variant component, they can't be fully
1416 // strength-reduced.
1417 if (Imm && !Imm->isLoopInvariant(L))
1419 // If there are to users with the same base and the difference between
1420 // the two Imm values can't be folded into the address, full
1421 // strength reduction would increase register pressure.
1423 const SCEV *CurImm = UsersToProcess[i].Imm;
1424 if ((CurImm || Imm) && CurImm != Imm) {
1425 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1426 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1427 const Instruction *Inst = UsersToProcess[i].Inst;
1428 const Type *UseTy = getAccessType(Inst);
1429 SCEVHandle Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1430 if (!Diff->isZero() &&
1431 (!AllUsesAreAddresses ||
1432 !fitsInAddressMode(Diff, UseTy, TLI, /*HasBaseReg=*/true)))
1435 } while (++i != e && Base == UsersToProcess[i].Base);
1438 // If there's exactly one user in this stride, fully strength-reducing it
1439 // won't increase register pressure. If it's starting from a non-zero base,
1440 // it'll be simpler this way.
1441 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1444 // Otherwise, if there are any users in this stride that don't require
1445 // a register for their base, full strength-reduction will increase
1446 // register pressure.
1447 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1448 if (UsersToProcess[i].Base->isZero())
1451 // Otherwise, go for it.
1455 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1456 /// with the specified start and step values in the specified loop.
1458 /// If NegateStride is true, the stride should be negated by using a
1459 /// subtract instead of an add.
1461 /// Return the created phi node.
1463 static PHINode *InsertAffinePhi(SCEVHandle Start, SCEVHandle Step,
1464 Instruction *IVIncInsertPt,
1466 SCEVExpander &Rewriter) {
1467 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1468 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1470 BasicBlock *Header = L->getHeader();
1471 BasicBlock *Preheader = L->getLoopPreheader();
1472 BasicBlock *LatchBlock = L->getLoopLatch();
1473 const Type *Ty = Start->getType();
1474 Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
1476 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1477 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1480 // If the stride is negative, insert a sub instead of an add for the
1482 bool isNegative = isNonConstantNegative(Step);
1483 SCEVHandle IncAmount = Step;
1485 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1487 // Insert an add instruction right before the terminator corresponding
1488 // to the back-edge or just before the only use. The location is determined
1489 // by the caller and passed in as IVIncInsertPt.
1490 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1491 Preheader->getTerminator());
1494 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1497 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1500 if (!isa<ConstantInt>(StepV)) ++NumVariable;
1502 PN->addIncoming(IncV, LatchBlock);
1508 static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1509 // We want to emit code for users inside the loop first. To do this, we
1510 // rearrange BasedUser so that the entries at the end have
1511 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1512 // vector (so we handle them first).
1513 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1514 PartitionByIsUseOfPostIncrementedValue);
1516 // Sort this by base, so that things with the same base are handled
1517 // together. By partitioning first and stable-sorting later, we are
1518 // guaranteed that within each base we will pop off users from within the
1519 // loop before users outside of the loop with a particular base.
1521 // We would like to use stable_sort here, but we can't. The problem is that
1522 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1523 // we don't have anything to do a '<' comparison on. Because we think the
1524 // number of uses is small, do a horrible bubble sort which just relies on
1526 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1527 // Get a base value.
1528 SCEVHandle Base = UsersToProcess[i].Base;
1530 // Compact everything with this base to be consecutive with this one.
1531 for (unsigned j = i+1; j != e; ++j) {
1532 if (UsersToProcess[j].Base == Base) {
1533 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1540 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1541 /// UsersToProcess, meaning lowering addresses all the way down to direct
1542 /// pointer arithmetic.
1545 LoopStrengthReduce::PrepareToStrengthReduceFully(
1546 std::vector<BasedUser> &UsersToProcess,
1548 SCEVHandle CommonExprs,
1550 SCEVExpander &PreheaderRewriter) {
1551 DOUT << " Fully reducing all users\n";
1553 // Rewrite the UsersToProcess records, creating a separate PHI for each
1554 // unique Base value.
1555 Instruction *IVIncInsertPt = L->getLoopLatch()->getTerminator();
1556 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1557 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1558 // pick the first Imm value here to start with, and adjust it for the
1560 SCEVHandle Imm = UsersToProcess[i].Imm;
1561 SCEVHandle Base = UsersToProcess[i].Base;
1562 SCEVHandle Start = SE->getAddExpr(CommonExprs, Base, Imm);
1563 PHINode *Phi = InsertAffinePhi(Start, Stride, IVIncInsertPt, L,
1565 // Loop over all the users with the same base.
1567 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1568 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1569 UsersToProcess[i].Phi = Phi;
1570 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1571 "ShouldUseFullStrengthReductionMode should reject this!");
1572 } while (++i != e && Base == UsersToProcess[i].Base);
1576 /// FindIVIncInsertPt - Return the location to insert the increment instruction.
1577 /// If the only use if a use of postinc value, (must be the loop termination
1578 /// condition), then insert it just before the use.
1579 static Instruction *FindIVIncInsertPt(std::vector<BasedUser> &UsersToProcess,
1581 if (UsersToProcess.size() == 1 &&
1582 UsersToProcess[0].isUseOfPostIncrementedValue &&
1583 L->contains(UsersToProcess[0].Inst->getParent()))
1584 return UsersToProcess[0].Inst;
1585 return L->getLoopLatch()->getTerminator();
1588 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1589 /// given users to share.
1592 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1593 std::vector<BasedUser> &UsersToProcess,
1595 SCEVHandle CommonExprs,
1597 Instruction *IVIncInsertPt,
1599 SCEVExpander &PreheaderRewriter) {
1600 DOUT << " Inserting new PHI:\n";
1602 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1603 Stride, IVIncInsertPt, L,
1606 // Remember this in case a later stride is multiple of this.
1607 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1609 // All the users will share this new IV.
1610 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1611 UsersToProcess[i].Phi = Phi;
1614 DEBUG(WriteAsOperand(*DOUT, Phi, /*PrintType=*/false));
1618 /// PrepareToStrengthReduceFromSmallerStride - Prepare for the given users to
1619 /// reuse an induction variable with a stride that is a factor of the current
1620 /// induction variable.
1623 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1624 std::vector<BasedUser> &UsersToProcess,
1626 const IVExpr &ReuseIV,
1627 Instruction *PreInsertPt) {
1628 DOUT << " Rewriting in terms of existing IV of STRIDE " << *ReuseIV.Stride
1629 << " and BASE " << *ReuseIV.Base << "\n";
1631 // All the users will share the reused IV.
1632 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1633 UsersToProcess[i].Phi = ReuseIV.PHI;
1635 Constant *C = dyn_cast<Constant>(CommonBaseV);
1637 (!C->isNullValue() &&
1638 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1640 // We want the common base emitted into the preheader! This is just
1641 // using cast as a copy so BitCast (no-op cast) is appropriate
1642 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1643 "commonbase", PreInsertPt);
1646 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1647 const Type *AccessTy,
1648 std::vector<BasedUser> &UsersToProcess,
1649 const TargetLowering *TLI) {
1650 SmallVector<Instruction*, 16> AddrModeInsts;
1651 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1652 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1654 ExtAddrMode AddrMode =
1655 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1656 AccessTy, UsersToProcess[i].Inst,
1657 AddrModeInsts, *TLI);
1658 if (GV && GV != AddrMode.BaseGV)
1660 if (Offset && !AddrMode.BaseOffs)
1661 // FIXME: How to accurate check it's immediate offset is folded.
1663 AddrModeInsts.clear();
1668 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1669 /// stride of IV. All of the users may have different starting values, and this
1670 /// may not be the only stride.
1671 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1672 IVUsersOfOneStride &Uses,
1674 // If all the users are moved to another stride, then there is nothing to do.
1675 if (Uses.Users.empty())
1678 // Keep track if every use in UsersToProcess is an address. If they all are,
1679 // we may be able to rewrite the entire collection of them in terms of a
1680 // smaller-stride IV.
1681 bool AllUsesAreAddresses = true;
1683 // Keep track if every use of a single stride is outside the loop. If so,
1684 // we want to be more aggressive about reusing a smaller-stride IV; a
1685 // multiply outside the loop is better than another IV inside. Well, usually.
1686 bool AllUsesAreOutsideLoop = true;
1688 // Transform our list of users and offsets to a bit more complex table. In
1689 // this new vector, each 'BasedUser' contains 'Base' the base of the
1690 // strided accessas well as the old information from Uses. We progressively
1691 // move information from the Base field to the Imm field, until we eventually
1692 // have the full access expression to rewrite the use.
1693 std::vector<BasedUser> UsersToProcess;
1694 SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1695 AllUsesAreOutsideLoop,
1698 // Sort the UsersToProcess array so that users with common bases are
1699 // next to each other.
1700 SortUsersToProcess(UsersToProcess);
1702 // If we managed to find some expressions in common, we'll need to carry
1703 // their value in a register and add it in for each use. This will take up
1704 // a register operand, which potentially restricts what stride values are
1706 bool HaveCommonExprs = !CommonExprs->isZero();
1707 const Type *ReplacedTy = CommonExprs->getType();
1709 // If all uses are addresses, consider sinking the immediate part of the
1710 // common expression back into uses if they can fit in the immediate fields.
1711 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1712 SCEVHandle NewCommon = CommonExprs;
1713 SCEVHandle Imm = SE->getIntegerSCEV(0, ReplacedTy);
1714 MoveImmediateValues(TLI, Type::VoidTy, NewCommon, Imm, true, L, SE);
1715 if (!Imm->isZero()) {
1718 // If the immediate part of the common expression is a GV, check if it's
1719 // possible to fold it into the target addressing mode.
1720 GlobalValue *GV = 0;
1721 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
1722 GV = dyn_cast<GlobalValue>(SU->getValue());
1724 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
1725 Offset = SC->getValue()->getSExtValue();
1727 // Pass VoidTy as the AccessTy to be conservative, because
1728 // there could be multiple access types among all the uses.
1729 DoSink = IsImmFoldedIntoAddrMode(GV, Offset, Type::VoidTy,
1730 UsersToProcess, TLI);
1733 DOUT << " Sinking " << *Imm << " back down into uses\n";
1734 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1735 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1736 CommonExprs = NewCommon;
1737 HaveCommonExprs = !CommonExprs->isZero();
1743 // Now that we know what we need to do, insert the PHI node itself.
1745 DOUT << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1747 << " Common base: " << *CommonExprs << "\n";
1749 SCEVExpander Rewriter(*SE, *LI);
1750 SCEVExpander PreheaderRewriter(*SE, *LI);
1752 BasicBlock *Preheader = L->getLoopPreheader();
1753 Instruction *PreInsertPt = Preheader->getTerminator();
1754 BasicBlock *LatchBlock = L->getLoopLatch();
1755 Instruction *IVIncInsertPt = LatchBlock->getTerminator();
1757 Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
1759 SCEVHandle RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1760 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1761 SE->getIntegerSCEV(0, Type::Int32Ty),
1764 /// Choose a strength-reduction strategy and prepare for it by creating
1765 /// the necessary PHIs and adjusting the bookkeeping.
1766 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1767 AllUsesAreAddresses, Stride)) {
1768 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1771 // Emit the initial base value into the loop preheader.
1772 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1775 // If all uses are addresses, check if it is possible to reuse an IV. The
1776 // new IV must have a stride that is a multiple of the old stride; the
1777 // multiple must be a number that can be encoded in the scale field of the
1778 // target addressing mode; and we must have a valid instruction after this
1779 // substitution, including the immediate field, if any.
1780 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1781 AllUsesAreOutsideLoop,
1782 Stride, ReuseIV, ReplacedTy,
1784 if (!RewriteFactor->isZero())
1785 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1786 ReuseIV, PreInsertPt);
1788 IVIncInsertPt = FindIVIncInsertPt(UsersToProcess, L);
1789 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1790 CommonBaseV, IVIncInsertPt,
1791 L, PreheaderRewriter);
1795 // Process all the users now, replacing their strided uses with
1796 // strength-reduced forms. This outer loop handles all bases, the inner
1797 // loop handles all users of a particular base.
1798 while (!UsersToProcess.empty()) {
1799 SCEVHandle Base = UsersToProcess.back().Base;
1800 Instruction *Inst = UsersToProcess.back().Inst;
1802 // Emit the code for Base into the preheader.
1804 if (!Base->isZero()) {
1805 BaseV = PreheaderRewriter.expandCodeFor(Base, Base->getType(),
1808 DOUT << " INSERTING code for BASE = " << *Base << ":";
1809 if (BaseV->hasName())
1810 DOUT << " Result value name = %" << BaseV->getNameStr();
1813 // If BaseV is a non-zero constant, make sure that it gets inserted into
1814 // the preheader, instead of being forward substituted into the uses. We
1815 // do this by forcing a BitCast (noop cast) to be inserted into the
1816 // preheader in this case.
1817 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false)) {
1818 // We want this constant emitted into the preheader! This is just
1819 // using cast as a copy so BitCast (no-op cast) is appropriate
1820 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1825 // Emit the code to add the immediate offset to the Phi value, just before
1826 // the instructions that we identified as using this stride and base.
1828 // FIXME: Use emitted users to emit other users.
1829 BasedUser &User = UsersToProcess.back();
1831 DOUT << " Examining ";
1832 if (User.isUseOfPostIncrementedValue)
1837 DEBUG(WriteAsOperand(*DOUT, UsersToProcess.back().OperandValToReplace,
1838 /*PrintType=*/false));
1839 DOUT << " in Inst: " << *(User.Inst);
1841 // If this instruction wants to use the post-incremented value, move it
1842 // after the post-inc and use its value instead of the PHI.
1843 Value *RewriteOp = User.Phi;
1844 if (User.isUseOfPostIncrementedValue) {
1845 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1846 // If this user is in the loop, make sure it is the last thing in the
1847 // loop to ensure it is dominated by the increment. In case it's the
1848 // only use of the iv, the increment instruction is already before the
1850 if (L->contains(User.Inst->getParent()) && User.Inst != IVIncInsertPt)
1851 User.Inst->moveBefore(IVIncInsertPt);
1854 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
1856 if (SE->getTypeSizeInBits(RewriteOp->getType()) !=
1857 SE->getTypeSizeInBits(ReplacedTy)) {
1858 assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1859 SE->getTypeSizeInBits(ReplacedTy) &&
1860 "Unexpected widening cast!");
1861 RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1864 // If we had to insert new instructions for RewriteOp, we have to
1865 // consider that they may not have been able to end up immediately
1866 // next to RewriteOp, because non-PHI instructions may never precede
1867 // PHI instructions in a block. In this case, remember where the last
1868 // instruction was inserted so that if we're replacing a different
1869 // PHI node, we can use the later point to expand the final
1871 Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
1872 if (RewriteOp == User.Phi) NewBasePt = 0;
1874 // Clear the SCEVExpander's expression map so that we are guaranteed
1875 // to have the code emitted where we expect it.
1878 // If we are reusing the iv, then it must be multiplied by a constant
1879 // factor to take advantage of the addressing mode scale component.
1880 if (!RewriteFactor->isZero()) {
1881 // If we're reusing an IV with a nonzero base (currently this happens
1882 // only when all reuses are outside the loop) subtract that base here.
1883 // The base has been used to initialize the PHI node but we don't want
1885 if (!ReuseIV.Base->isZero()) {
1886 SCEVHandle typedBase = ReuseIV.Base;
1887 if (SE->getTypeSizeInBits(RewriteExpr->getType()) !=
1888 SE->getTypeSizeInBits(ReuseIV.Base->getType())) {
1889 // It's possible the original IV is a larger type than the new IV,
1890 // in which case we have to truncate the Base. We checked in
1891 // RequiresTypeConversion that this is valid.
1892 assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1893 SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
1894 "Unexpected lengthening conversion!");
1895 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1896 RewriteExpr->getType());
1898 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1901 // Multiply old variable, with base removed, by new scale factor.
1902 RewriteExpr = SE->getMulExpr(RewriteFactor,
1905 // The common base is emitted in the loop preheader. But since we
1906 // are reusing an IV, it has not been used to initialize the PHI node.
1907 // Add it to the expression used to rewrite the uses.
1908 // When this use is outside the loop, we earlier subtracted the
1909 // common base, and are adding it back here. Use the same expression
1910 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1911 if (!CommonExprs->isZero()) {
1912 if (L->contains(User.Inst->getParent()))
1913 RewriteExpr = SE->getAddExpr(RewriteExpr,
1914 SE->getUnknown(CommonBaseV));
1916 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1920 // Now that we know what we need to do, insert code before User for the
1921 // immediate and any loop-variant expressions.
1923 // Add BaseV to the PHI value if needed.
1924 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1926 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1930 // Mark old value we replaced as possibly dead, so that it is eliminated
1931 // if we just replaced the last use of that value.
1932 DeadInsts.push_back(cast<Instruction>(User.OperandValToReplace));
1934 UsersToProcess.pop_back();
1937 // If there are any more users to process with the same base, process them
1938 // now. We sorted by base above, so we just have to check the last elt.
1939 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1940 // TODO: Next, find out which base index is the most common, pull it out.
1943 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1944 // different starting values, into different PHIs.
1947 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1948 /// set the IV user and stride information and return true, otherwise return
1950 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
1951 const SCEVHandle *&CondStride) {
1952 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1954 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1955 IVUsesByStride.find(StrideOrder[Stride]);
1956 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1958 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1959 E = SI->second.Users.end(); UI != E; ++UI)
1960 if (UI->User == Cond) {
1961 // NOTE: we could handle setcc instructions with multiple uses here, but
1962 // InstCombine does it as well for simple uses, it's not clear that it
1963 // occurs enough in real life to handle.
1965 CondStride = &SI->first;
1973 // Constant strides come first which in turns are sorted by their absolute
1974 // values. If absolute values are the same, then positive strides comes first.
1976 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1977 struct StrideCompare {
1978 const ScalarEvolution *SE;
1979 explicit StrideCompare(const ScalarEvolution *se) : SE(se) {}
1981 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1982 const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1983 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1985 int64_t LV = LHSC->getValue()->getSExtValue();
1986 int64_t RV = RHSC->getValue()->getSExtValue();
1987 uint64_t ALV = (LV < 0) ? -LV : LV;
1988 uint64_t ARV = (RV < 0) ? -RV : RV;
1996 // If it's the same value but different type, sort by bit width so
1997 // that we emit larger induction variables before smaller
1998 // ones, letting the smaller be re-written in terms of larger ones.
1999 return SE->getTypeSizeInBits(RHS->getType()) <
2000 SE->getTypeSizeInBits(LHS->getType());
2002 return LHSC && !RHSC;
2007 /// ChangeCompareStride - If a loop termination compare instruction is the
2008 /// only use of its stride, and the compaison is against a constant value,
2009 /// try eliminate the stride by moving the compare instruction to another
2010 /// stride and change its constant operand accordingly. e.g.
2016 /// if (v2 < 10) goto loop
2021 /// if (v1 < 30) goto loop
2022 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
2023 IVStrideUse* &CondUse,
2024 const SCEVHandle* &CondStride) {
2025 if (StrideOrder.size() < 2 ||
2026 IVUsesByStride[*CondStride].Users.size() != 1)
2028 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
2029 if (!SC) return Cond;
2031 ICmpInst::Predicate Predicate = Cond->getPredicate();
2032 int64_t CmpSSInt = SC->getValue()->getSExtValue();
2033 unsigned BitWidth = SE->getTypeSizeInBits((*CondStride)->getType());
2034 uint64_t SignBit = 1ULL << (BitWidth-1);
2035 const Type *CmpTy = Cond->getOperand(0)->getType();
2036 const Type *NewCmpTy = NULL;
2037 unsigned TyBits = SE->getTypeSizeInBits(CmpTy);
2038 unsigned NewTyBits = 0;
2039 SCEVHandle *NewStride = NULL;
2040 Value *NewCmpLHS = NULL;
2041 Value *NewCmpRHS = NULL;
2043 SCEVHandle NewOffset = SE->getIntegerSCEV(0, CmpTy);
2045 if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
2046 int64_t CmpVal = C->getValue().getSExtValue();
2048 // Check stride constant and the comparision constant signs to detect
2050 if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
2053 // Look for a suitable stride / iv as replacement.
2054 for (unsigned i = 0, e = StrideOrder.size(); i != e; ++i) {
2055 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2056 IVUsesByStride.find(StrideOrder[i]);
2057 if (!isa<SCEVConstant>(SI->first))
2059 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2060 if (SSInt == CmpSSInt ||
2061 abs(SSInt) < abs(CmpSSInt) ||
2062 (SSInt % CmpSSInt) != 0)
2065 Scale = SSInt / CmpSSInt;
2066 int64_t NewCmpVal = CmpVal * Scale;
2067 APInt Mul = APInt(BitWidth*2, CmpVal, true);
2068 Mul = Mul * APInt(BitWidth*2, Scale, true);
2069 // Check for overflow.
2070 if (!Mul.isSignedIntN(BitWidth))
2073 // Watch out for overflow.
2074 if (ICmpInst::isSignedPredicate(Predicate) &&
2075 (CmpVal & SignBit) != (NewCmpVal & SignBit))
2078 if (NewCmpVal == CmpVal)
2080 // Pick the best iv to use trying to avoid a cast.
2082 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2083 E = SI->second.Users.end(); UI != E; ++UI) {
2084 NewCmpLHS = UI->OperandValToReplace;
2085 if (NewCmpLHS->getType() == CmpTy)
2091 NewCmpTy = NewCmpLHS->getType();
2092 NewTyBits = SE->getTypeSizeInBits(NewCmpTy);
2093 const Type *NewCmpIntTy = IntegerType::get(NewTyBits);
2094 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
2095 // Check if it is possible to rewrite it using
2096 // an iv / stride of a smaller integer type.
2097 unsigned Bits = NewTyBits;
2098 if (ICmpInst::isSignedPredicate(Predicate))
2100 uint64_t Mask = (1ULL << Bits) - 1;
2101 if (((uint64_t)NewCmpVal & Mask) != (uint64_t)NewCmpVal)
2105 // Don't rewrite if use offset is non-constant and the new type is
2106 // of a different type.
2107 // FIXME: too conservative?
2108 if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->Offset))
2111 bool AllUsesAreAddresses = true;
2112 bool AllUsesAreOutsideLoop = true;
2113 std::vector<BasedUser> UsersToProcess;
2114 SCEVHandle CommonExprs = CollectIVUsers(SI->first, SI->second, L,
2115 AllUsesAreAddresses,
2116 AllUsesAreOutsideLoop,
2118 // Avoid rewriting the compare instruction with an iv of new stride
2119 // if it's likely the new stride uses will be rewritten using the
2120 // stride of the compare instruction.
2121 if (AllUsesAreAddresses &&
2122 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
2125 // If scale is negative, use swapped predicate unless it's testing
2127 if (Scale < 0 && !Cond->isEquality())
2128 Predicate = ICmpInst::getSwappedPredicate(Predicate);
2130 NewStride = &StrideOrder[i];
2131 if (!isa<PointerType>(NewCmpTy))
2132 NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
2134 ConstantInt *CI = ConstantInt::get(NewCmpIntTy, NewCmpVal);
2135 NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
2137 NewOffset = TyBits == NewTyBits
2138 ? SE->getMulExpr(CondUse->Offset,
2139 SE->getConstant(ConstantInt::get(CmpTy, Scale)))
2140 : SE->getConstant(ConstantInt::get(NewCmpIntTy,
2141 cast<SCEVConstant>(CondUse->Offset)->getValue()->getSExtValue()*Scale));
2146 // Forgo this transformation if it the increment happens to be
2147 // unfortunately positioned after the condition, and the condition
2148 // has multiple uses which prevent it from being moved immediately
2149 // before the branch. See
2150 // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2151 // for an example of this situation.
2152 if (!Cond->hasOneUse()) {
2153 for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2160 // Create a new compare instruction using new stride / iv.
2161 ICmpInst *OldCond = Cond;
2162 // Insert new compare instruction.
2163 Cond = new ICmpInst(Predicate, NewCmpLHS, NewCmpRHS,
2164 L->getHeader()->getName() + ".termcond",
2167 // Remove the old compare instruction. The old indvar is probably dead too.
2168 DeadInsts.push_back(cast<Instruction>(CondUse->OperandValToReplace));
2169 OldCond->replaceAllUsesWith(Cond);
2170 OldCond->eraseFromParent();
2172 IVUsesByStride[*CondStride].Users.pop_back();
2173 IVUsesByStride[*NewStride].addUser(NewOffset, Cond, NewCmpLHS);
2174 CondUse = &IVUsesByStride[*NewStride].Users.back();
2175 CondStride = NewStride;
2183 /// OptimizeSMax - Rewrite the loop's terminating condition if it uses
2184 /// an smax computation.
2186 /// This is a narrow solution to a specific, but acute, problem. For loops
2192 /// } while (++i < n);
2194 /// where the comparison is signed, the trip count isn't just 'n', because
2195 /// 'n' could be negative. And unfortunately this can come up even for loops
2196 /// where the user didn't use a C do-while loop. For example, seemingly
2197 /// well-behaved top-test loops will commonly be lowered like this:
2203 /// } while (++i < n);
2206 /// and then it's possible for subsequent optimization to obscure the if
2207 /// test in such a way that indvars can't find it.
2209 /// When indvars can't find the if test in loops like this, it creates a
2210 /// signed-max expression, which allows it to give the loop a canonical
2211 /// induction variable:
2214 /// smax = n < 1 ? 1 : n;
2217 /// } while (++i != smax);
2219 /// Canonical induction variables are necessary because the loop passes
2220 /// are designed around them. The most obvious example of this is the
2221 /// LoopInfo analysis, which doesn't remember trip count values. It
2222 /// expects to be able to rediscover the trip count each time it is
2223 /// needed, and it does this using a simple analyis that only succeeds if
2224 /// the loop has a canonical induction variable.
2226 /// However, when it comes time to generate code, the maximum operation
2227 /// can be quite costly, especially if it's inside of an outer loop.
2229 /// This function solves this problem by detecting this type of loop and
2230 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2231 /// the instructions for the maximum computation.
2233 ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
2234 IVStrideUse* &CondUse) {
2235 // Check that the loop matches the pattern we're looking for.
2236 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2237 Cond->getPredicate() != CmpInst::ICMP_NE)
2240 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2241 if (!Sel || !Sel->hasOneUse()) return Cond;
2243 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2244 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2246 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2248 // Add one to the backedge-taken count to get the trip count.
2249 SCEVHandle IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
2251 // Check for a max calculation that matches the pattern.
2252 const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
2253 if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
2255 SCEVHandle SMaxLHS = SMax->getOperand(0);
2256 SCEVHandle SMaxRHS = SMax->getOperand(1);
2257 if (!SMaxLHS || SMaxLHS != One) return Cond;
2259 // Check the relevant induction variable for conformance to
2261 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2262 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2263 if (!AR || !AR->isAffine() ||
2264 AR->getStart() != One ||
2265 AR->getStepRecurrence(*SE) != One)
2268 assert(AR->getLoop() == L &&
2269 "Loop condition operand is an addrec in a different loop!");
2271 // Check the right operand of the select, and remember it, as it will
2272 // be used in the new comparison instruction.
2274 if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
2275 NewRHS = Sel->getOperand(1);
2276 else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
2277 NewRHS = Sel->getOperand(2);
2278 if (!NewRHS) return Cond;
2280 // Ok, everything looks ok to change the condition into an SLT or SGE and
2281 // delete the max calculation.
2283 new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
2286 Cond->getOperand(0), NewRHS, "scmp", Cond);
2288 // Delete the max calculation instructions.
2289 Cond->replaceAllUsesWith(NewCond);
2290 Cond->eraseFromParent();
2291 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2292 Sel->eraseFromParent();
2293 if (Cmp->use_empty())
2294 Cmp->eraseFromParent();
2295 CondUse->User = NewCond;
2299 /// OptimizeShadowIV - If IV is used in a int-to-float cast
2300 /// inside the loop then try to eliminate the cast opeation.
2301 void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2303 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2304 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2307 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e;
2309 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2310 IVUsesByStride.find(StrideOrder[Stride]);
2311 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
2312 if (!isa<SCEVConstant>(SI->first))
2315 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2316 E = SI->second.Users.end(); UI != E; /* empty */) {
2317 std::vector<IVStrideUse>::iterator CandidateUI = UI;
2319 Instruction *ShadowUse = CandidateUI->User;
2320 const Type *DestTy = NULL;
2322 /* If shadow use is a int->float cast then insert a second IV
2323 to eliminate this cast.
2325 for (unsigned i = 0; i < n; ++i)
2331 for (unsigned i = 0; i < n; ++i, ++d)
2334 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->User))
2335 DestTy = UCast->getDestTy();
2336 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->User))
2337 DestTy = SCast->getDestTy();
2338 if (!DestTy) continue;
2341 // If target does not support DestTy natively then do not apply
2342 // this transformation.
2343 MVT DVT = TLI->getValueType(DestTy);
2344 if (!TLI->isTypeLegal(DVT)) continue;
2347 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2349 if (PH->getNumIncomingValues() != 2) continue;
2351 const Type *SrcTy = PH->getType();
2352 int Mantissa = DestTy->getFPMantissaWidth();
2353 if (Mantissa == -1) continue;
2354 if ((int)SE->getTypeSizeInBits(SrcTy) > Mantissa)
2357 unsigned Entry, Latch;
2358 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2366 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2367 if (!Init) continue;
2368 ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2370 BinaryOperator *Incr =
2371 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2372 if (!Incr) continue;
2373 if (Incr->getOpcode() != Instruction::Add
2374 && Incr->getOpcode() != Instruction::Sub)
2377 /* Initialize new IV, double d = 0.0 in above example. */
2378 ConstantInt *C = NULL;
2379 if (Incr->getOperand(0) == PH)
2380 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2381 else if (Incr->getOperand(1) == PH)
2382 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2388 /* Add new PHINode. */
2389 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2391 /* create new increment. '++d' in above example. */
2392 ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2393 BinaryOperator *NewIncr =
2394 BinaryOperator::Create(Incr->getOpcode(),
2395 NewPH, CFP, "IV.S.next.", Incr);
2397 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2398 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2400 /* Remove cast operation */
2401 ShadowUse->replaceAllUsesWith(NewPH);
2402 ShadowUse->eraseFromParent();
2403 SI->second.Users.erase(CandidateUI);
2410 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2411 // uses in the loop, look to see if we can eliminate some, in favor of using
2412 // common indvars for the different uses.
2413 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2414 // TODO: implement optzns here.
2416 OptimizeShadowIV(L);
2419 /// OptimizeLoopTermCond - Change loop terminating condition to use the
2420 /// postinc iv when possible.
2421 void LoopStrengthReduce::OptimizeLoopTermCond(Loop *L) {
2422 // Finally, get the terminating condition for the loop if possible. If we
2423 // can, we want to change it to use a post-incremented version of its
2424 // induction variable, to allow coalescing the live ranges for the IV into
2425 // one register value.
2426 BasicBlock *LatchBlock = L->getLoopLatch();
2427 BasicBlock *ExitBlock = L->getExitingBlock();
2429 // Multiple exits, just look at the exit in the latch block if there is one.
2430 ExitBlock = LatchBlock;
2431 BranchInst *TermBr = dyn_cast<BranchInst>(ExitBlock->getTerminator());
2434 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2437 // Search IVUsesByStride to find Cond's IVUse if there is one.
2438 IVStrideUse *CondUse = 0;
2439 const SCEVHandle *CondStride = 0;
2440 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2441 if (!FindIVUserForCond(Cond, CondUse, CondStride))
2442 return; // setcc doesn't use the IV.
2444 if (ExitBlock != LatchBlock) {
2445 if (!Cond->hasOneUse())
2446 // See below, we don't want the condition to be cloned.
2449 // If exiting block is the latch block, we know it's safe and profitable to
2450 // transform the icmp to use post-inc iv. Otherwise do so only if it would
2451 // not reuse another iv and its iv would be reused by other uses. We are
2452 // optimizing for the case where the icmp is the only use of the iv.
2453 IVUsersOfOneStride &StrideUses = IVUsesByStride[*CondStride];
2454 for (unsigned i = 0, e = StrideUses.Users.size(); i != e; ++i) {
2455 if (StrideUses.Users[i].User == Cond)
2457 if (!StrideUses.Users[i].isUseOfPostIncrementedValue)
2461 // FIXME: This is expensive, and worse still ChangeCompareStride does a
2462 // similar check. Can we perform all the icmp related transformations after
2463 // StrengthReduceStridedIVUsers?
2464 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride)) {
2465 int64_t SInt = SC->getValue()->getSExtValue();
2466 for (unsigned NewStride = 0, ee = StrideOrder.size(); NewStride != ee;
2468 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2469 IVUsesByStride.find(StrideOrder[NewStride]);
2470 if (!isa<SCEVConstant>(SI->first) || SI->first == *CondStride)
2473 cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2475 return; // This can definitely be reused.
2476 if (unsigned(abs(SSInt)) < SInt || (SSInt % SInt) != 0)
2478 int64_t Scale = SSInt / SInt;
2479 bool AllUsesAreAddresses = true;
2480 bool AllUsesAreOutsideLoop = true;
2481 std::vector<BasedUser> UsersToProcess;
2482 SCEVHandle CommonExprs = CollectIVUsers(SI->first, SI->second, L,
2483 AllUsesAreAddresses,
2484 AllUsesAreOutsideLoop,
2486 // Avoid rewriting the compare instruction with an iv of new stride
2487 // if it's likely the new stride uses will be rewritten using the
2488 // stride of the compare instruction.
2489 if (AllUsesAreAddresses &&
2490 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
2495 StrideNoReuse.insert(*CondStride);
2498 // If the trip count is computed in terms of an smax (due to ScalarEvolution
2499 // being unable to find a sufficient guard, for example), change the loop
2500 // comparison to use SLT instead of NE.
2501 Cond = OptimizeSMax(L, Cond, CondUse);
2503 // If possible, change stride and operands of the compare instruction to
2504 // eliminate one stride.
2505 if (ExitBlock == LatchBlock)
2506 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
2508 // It's possible for the setcc instruction to be anywhere in the loop, and
2509 // possible for it to have multiple users. If it is not immediately before
2510 // the latch block branch, move it.
2511 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2512 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
2513 Cond->moveBefore(TermBr);
2515 // Otherwise, clone the terminating condition and insert into the loopend.
2516 Cond = cast<ICmpInst>(Cond->clone());
2517 Cond->setName(L->getHeader()->getName() + ".termcond");
2518 LatchBlock->getInstList().insert(TermBr, Cond);
2520 // Clone the IVUse, as the old use still exists!
2521 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
2522 CondUse->OperandValToReplace);
2523 CondUse = &IVUsesByStride[*CondStride].Users.back();
2527 // If we get to here, we know that we can transform the setcc instruction to
2528 // use the post-incremented version of the IV, allowing us to coalesce the
2529 // live ranges for the IV correctly.
2530 CondUse->Offset = SE->getMinusSCEV(CondUse->Offset, *CondStride);
2531 CondUse->isUseOfPostIncrementedValue = true;
2537 // OptimizeLoopCountIV - If, after all sharing of IVs, the IV used for deciding
2538 // when to exit the loop is used only for that purpose, try to rearrange things
2539 // so it counts down to a test against zero.
2540 void LoopStrengthReduce::OptimizeLoopCountIV(Loop *L) {
2542 // If the number of times the loop is executed isn't computable, give up.
2543 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2544 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2547 // Get the terminating condition for the loop if possible (this isn't
2548 // necessarily in the latch, or a block that's a predecessor of the header).
2549 SmallVector<BasicBlock*, 8> ExitBlocks;
2550 L->getExitBlocks(ExitBlocks);
2551 if (ExitBlocks.size() != 1) return;
2553 // Okay, there is one exit block. Try to find the condition that causes the
2554 // loop to be exited.
2555 BasicBlock *ExitBlock = ExitBlocks[0];
2557 BasicBlock *ExitingBlock = 0;
2558 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2560 if (L->contains(*PI)) {
2561 if (ExitingBlock == 0)
2564 return; // More than one block exiting!
2566 assert(ExitingBlock && "No exits from loop, something is broken!");
2568 // Okay, we've computed the exiting block. See what condition causes us to
2571 // FIXME: we should be able to handle switch instructions (with a single exit)
2572 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2573 if (TermBr == 0) return;
2574 assert(TermBr->isConditional() && "If unconditional, it can't be in loop!");
2575 if (!isa<ICmpInst>(TermBr->getCondition()))
2577 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2579 // Handle only tests for equality for the moment, and only stride 1.
2580 if (Cond->getPredicate() != CmpInst::ICMP_EQ)
2582 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2583 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2584 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2585 if (!AR || !AR->isAffine() || AR->getStepRecurrence(*SE) != One)
2588 // Make sure the IV is only used for counting. Value may be preinc or
2589 // postinc; 2 uses in either case.
2590 if (!Cond->getOperand(0)->hasNUses(2))
2592 PHINode *phi = dyn_cast<PHINode>(Cond->getOperand(0));
2594 if (phi && phi->getParent()==L->getHeader()) {
2595 // value tested is preinc. Find the increment.
2596 // A CmpInst is not a BinaryOperator; we depend on this.
2597 Instruction::use_iterator UI = phi->use_begin();
2598 incr = dyn_cast<BinaryOperator>(UI);
2600 incr = dyn_cast<BinaryOperator>(++UI);
2601 // 1 use for postinc value, the phi. Unnecessarily conservative?
2602 if (!incr || !incr->hasOneUse() || incr->getOpcode()!=Instruction::Add)
2605 // Value tested is postinc. Find the phi node.
2606 incr = dyn_cast<BinaryOperator>(Cond->getOperand(0));
2607 if (!incr || incr->getOpcode()!=Instruction::Add)
2610 Instruction::use_iterator UI = Cond->getOperand(0)->use_begin();
2611 phi = dyn_cast<PHINode>(UI);
2613 phi = dyn_cast<PHINode>(++UI);
2614 // 1 use for preinc value, the increment.
2615 if (!phi || phi->getParent()!=L->getHeader() || !phi->hasOneUse())
2619 // Replace the increment with a decrement.
2620 BinaryOperator *decr =
2621 BinaryOperator::Create(Instruction::Sub, incr->getOperand(0),
2622 incr->getOperand(1), "tmp", incr);
2623 incr->replaceAllUsesWith(decr);
2624 incr->eraseFromParent();
2626 // Substitute endval-startval for the original startval, and 0 for the
2627 // original endval. Since we're only testing for equality this is OK even
2628 // if the computation wraps around.
2629 BasicBlock *Preheader = L->getLoopPreheader();
2630 Instruction *PreInsertPt = Preheader->getTerminator();
2631 int inBlock = L->contains(phi->getIncomingBlock(0)) ? 1 : 0;
2632 Value *startVal = phi->getIncomingValue(inBlock);
2633 Value *endVal = Cond->getOperand(1);
2634 // FIXME check for case where both are constant
2635 ConstantInt* Zero = ConstantInt::get(Cond->getOperand(1)->getType(), 0);
2636 BinaryOperator *NewStartVal =
2637 BinaryOperator::Create(Instruction::Sub, endVal, startVal,
2638 "tmp", PreInsertPt);
2639 phi->setIncomingValue(inBlock, NewStartVal);
2640 Cond->setOperand(1, Zero);
2645 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
2647 LI = &getAnalysis<LoopInfo>();
2648 DT = &getAnalysis<DominatorTree>();
2649 SE = &getAnalysis<ScalarEvolution>();
2652 // Find all uses of induction variables in this loop, and categorize
2653 // them by stride. Start by finding all of the PHI nodes in the header for
2654 // this loop. If they are induction variables, inspect their uses.
2655 SmallPtrSet<Instruction*,16> Processed; // Don't reprocess instructions.
2656 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
2657 AddUsersIfInteresting(I, L, Processed);
2659 if (!IVUsesByStride.empty()) {
2661 DOUT << "\nLSR on \"" << L->getHeader()->getParent()->getNameStart()
2666 // Sort the StrideOrder so we process larger strides first.
2667 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare(SE));
2669 // Optimize induction variables. Some indvar uses can be transformed to use
2670 // strides that will be needed for other purposes. A common example of this
2671 // is the exit test for the loop, which can often be rewritten to use the
2672 // computation of some other indvar to decide when to terminate the loop.
2675 // Change loop terminating condition to use the postinc iv when possible
2676 // and optimize loop terminating compare. FIXME: Move this after
2677 // StrengthReduceStridedIVUsers?
2678 OptimizeLoopTermCond(L);
2680 // FIXME: We can shrink overlarge IV's here. e.g. if the code has
2681 // computation in i64 values and the target doesn't support i64, demote
2682 // the computation to 32-bit if safe.
2684 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
2685 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2686 // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2687 // Need to be careful that IV's are all the same type. Only works for
2688 // intptr_t indvars.
2690 // IVsByStride keeps IVs for one particular loop.
2691 assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
2693 // Note: this processes each stride/type pair individually. All users
2694 // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2695 // Also, note that we iterate over IVUsesByStride indirectly by using
2696 // StrideOrder. This extra layer of indirection makes the ordering of
2697 // strides deterministic - not dependent on map order.
2698 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
2699 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2700 IVUsesByStride.find(StrideOrder[Stride]);
2701 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
2702 StrengthReduceStridedIVUsers(SI->first, SI->second, L);
2706 // After all sharing is done, see if we can adjust the loop to test against
2707 // zero instead of counting up to a maximum. This is usually faster.
2708 OptimizeLoopCountIV(L);
2710 // We're done analyzing this loop; release all the state we built up for it.
2711 IVUsesByStride.clear();
2712 IVsByStride.clear();
2713 StrideOrder.clear();
2714 StrideNoReuse.clear();
2716 // Clean up after ourselves
2717 if (!DeadInsts.empty())
2718 DeleteTriviallyDeadInstructions();
2720 // At this point, it is worth checking to see if any recurrence PHIs are also
2721 // dead, so that we can remove them as well.
2722 DeleteDeadPHIs(L->getHeader());