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/Target/TargetLowering.h"
39 STATISTIC(NumReduced , "Number of IV uses strength reduced");
40 STATISTIC(NumInserted, "Number of PHIs inserted");
41 STATISTIC(NumVariable, "Number of PHIs with variable strides");
42 STATISTIC(NumEliminated, "Number of strides eliminated");
43 STATISTIC(NumShadow, "Number of Shadow IVs optimized");
44 STATISTIC(NumImmSunk, "Number of common expr immediates sunk into uses");
46 static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
54 /// IVStrideUse - Keep track of one use of a strided induction variable, where
55 /// the stride is stored externally. The Offset member keeps track of the
56 /// offset from the IV, User is the actual user of the operand, and
57 /// 'OperandValToReplace' is the operand of the User that is the use.
58 struct VISIBILITY_HIDDEN IVStrideUse {
61 Value *OperandValToReplace;
63 // isUseOfPostIncrementedValue - True if this should use the
64 // post-incremented version of this IV, not the preincremented version.
65 // This can only be set in special cases, such as the terminating setcc
66 // instruction for a loop or uses dominated by the loop.
67 bool isUseOfPostIncrementedValue;
69 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
70 : Offset(Offs), User(U), OperandValToReplace(O),
71 isUseOfPostIncrementedValue(false) {}
74 /// IVUsersOfOneStride - This structure keeps track of all instructions that
75 /// have an operand that is based on the trip count multiplied by some stride.
76 /// The stride for all of these users is common and kept external to this
78 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
79 /// Users - Keep track of all of the users of this stride as well as the
80 /// initial value and the operand that uses the IV.
81 std::vector<IVStrideUse> Users;
83 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
84 Users.push_back(IVStrideUse(Offset, User, Operand));
88 /// IVInfo - This structure keeps track of one IV expression inserted during
89 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
90 /// well as the PHI node and increment value created for rewrite.
91 struct VISIBILITY_HIDDEN IVExpr {
96 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi)
97 : Stride(stride), Base(base), PHI(phi) {}
100 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
101 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
102 struct VISIBILITY_HIDDEN IVsOfOneStride {
103 std::vector<IVExpr> IVs;
105 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI) {
106 IVs.push_back(IVExpr(Stride, Base, PHI));
110 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
116 /// IVUsesByStride - Keep track of all uses of induction variables that we
117 /// are interested in. The key of the map is the stride of the access.
118 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
120 /// IVsByStride - Keep track of all IVs that have been inserted for a
121 /// particular stride.
122 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
124 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
125 /// We use this to iterate over the IVUsesByStride collection without being
126 /// dependent on random ordering of pointers in the process.
127 SmallVector<SCEVHandle, 16> StrideOrder;
129 /// DeadInsts - Keep track of instructions we may have made dead, so that
130 /// we can remove them after we are done working.
131 SmallVector<Instruction*, 16> DeadInsts;
133 /// TLI - Keep a pointer of a TargetLowering to consult for determining
134 /// transformation profitability.
135 const TargetLowering *TLI;
138 static char ID; // Pass ID, replacement for typeid
139 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
140 LoopPass(&ID), TLI(tli) {
143 bool runOnLoop(Loop *L, LPPassManager &LPM);
145 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
146 // We split critical edges, so we change the CFG. However, we do update
147 // many analyses if they are around.
148 AU.addPreservedID(LoopSimplifyID);
149 AU.addPreserved<LoopInfo>();
150 AU.addPreserved<DominanceFrontier>();
151 AU.addPreserved<DominatorTree>();
153 AU.addRequiredID(LoopSimplifyID);
154 AU.addRequired<LoopInfo>();
155 AU.addRequired<DominatorTree>();
156 AU.addRequired<ScalarEvolution>();
157 AU.addPreserved<ScalarEvolution>();
161 bool AddUsersIfInteresting(Instruction *I, Loop *L,
162 SmallPtrSet<Instruction*,16> &Processed);
163 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
164 IVStrideUse* &CondUse,
165 const SCEVHandle* &CondStride);
166 void OptimizeIndvars(Loop *L);
168 /// OptimizeShadowIV - If IV is used in a int-to-float cast
169 /// inside the loop then try to eliminate the cast opeation.
170 void OptimizeShadowIV(Loop *L);
172 /// OptimizeSMax - Rewrite the loop's terminating condition
173 /// if it uses an smax computation.
174 ICmpInst *OptimizeSMax(Loop *L, ICmpInst *Cond,
175 IVStrideUse* &CondUse);
177 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
178 const SCEVHandle *&CondStride);
179 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
180 SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
181 IVExpr&, const Type*,
182 const std::vector<BasedUser>& UsersToProcess);
183 bool ValidStride(bool, int64_t,
184 const std::vector<BasedUser>& UsersToProcess);
185 SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
186 IVUsersOfOneStride &Uses,
188 bool &AllUsesAreAddresses,
189 bool &AllUsesAreOutsideLoop,
190 std::vector<BasedUser> &UsersToProcess);
191 bool ShouldUseFullStrengthReductionMode(
192 const std::vector<BasedUser> &UsersToProcess,
194 bool AllUsesAreAddresses,
196 void PrepareToStrengthReduceFully(
197 std::vector<BasedUser> &UsersToProcess,
199 SCEVHandle CommonExprs,
201 SCEVExpander &PreheaderRewriter);
202 void PrepareToStrengthReduceFromSmallerStride(
203 std::vector<BasedUser> &UsersToProcess,
205 const IVExpr &ReuseIV,
206 Instruction *PreInsertPt);
207 void PrepareToStrengthReduceWithNewPhi(
208 std::vector<BasedUser> &UsersToProcess,
210 SCEVHandle CommonExprs,
213 SCEVExpander &PreheaderRewriter);
214 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
215 IVUsersOfOneStride &Uses,
217 void DeleteTriviallyDeadInstructions();
221 char LoopStrengthReduce::ID = 0;
222 static RegisterPass<LoopStrengthReduce>
223 X("loop-reduce", "Loop Strength Reduction");
225 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
226 return new LoopStrengthReduce(TLI);
229 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
230 /// specified set are trivially dead, delete them and see if this makes any of
231 /// their operands subsequently dead.
232 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
233 if (DeadInsts.empty()) return;
235 // Sort the deadinsts list so that we can trivially eliminate duplicates as we
236 // go. The code below never adds a non-dead instruction to the worklist, but
237 // callers may not be so careful.
238 array_pod_sort(DeadInsts.begin(), DeadInsts.end());
240 // Drop duplicate instructions and those with uses.
241 for (unsigned i = 0, e = DeadInsts.size()-1; i < e; ++i) {
242 Instruction *I = DeadInsts[i];
243 if (!I->use_empty()) DeadInsts[i] = 0;
244 while (i != e && DeadInsts[i+1] == I)
248 while (!DeadInsts.empty()) {
249 Instruction *I = DeadInsts.back();
250 DeadInsts.pop_back();
252 if (I == 0 || !isInstructionTriviallyDead(I))
255 SE->deleteValueFromRecords(I);
257 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
258 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
261 DeadInsts.push_back(U);
265 I->eraseFromParent();
270 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a
271 /// subexpression that is an AddRec from a loop other than L. An outer loop
272 /// of L is OK, but not an inner loop nor a disjoint loop.
273 static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
274 // This is very common, put it first.
275 if (isa<SCEVConstant>(S))
277 if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
278 for (unsigned int i=0; i< AE->getNumOperands(); i++)
279 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
283 if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
284 if (const Loop *newLoop = AE->getLoop()) {
287 // if newLoop is an outer loop of L, this is OK.
288 if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
293 if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
294 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
295 containsAddRecFromDifferentLoop(DE->getRHS(), L);
297 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
298 // need this when it is.
299 if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
300 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
301 containsAddRecFromDifferentLoop(DE->getRHS(), L);
303 if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
304 return containsAddRecFromDifferentLoop(CE->getOperand(), L);
308 /// getSCEVStartAndStride - Compute the start and stride of this expression,
309 /// returning false if the expression is not a start/stride pair, or true if it
310 /// is. The stride must be a loop invariant expression, but the start may be
311 /// a mix of loop invariant and loop variant expressions. The start cannot,
312 /// however, contain an AddRec from a different loop, unless that loop is an
313 /// outer loop of the current loop.
314 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
315 SCEVHandle &Start, SCEVHandle &Stride,
316 ScalarEvolution *SE, DominatorTree *DT) {
317 SCEVHandle TheAddRec = Start; // Initialize to zero.
319 // If the outer level is an AddExpr, the operands are all start values except
320 // for a nested AddRecExpr.
321 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
322 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
323 if (SCEVAddRecExpr *AddRec =
324 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
325 if (AddRec->getLoop() == L)
326 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
328 return false; // Nested IV of some sort?
330 Start = SE->getAddExpr(Start, AE->getOperand(i));
333 } else if (isa<SCEVAddRecExpr>(SH)) {
336 return false; // not analyzable.
339 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
340 if (!AddRec || AddRec->getLoop() != L) return false;
342 // FIXME: Generalize to non-affine IV's.
343 if (!AddRec->isAffine()) return false;
345 // If Start contains an SCEVAddRecExpr from a different loop, other than an
346 // outer loop of the current loop, reject it. SCEV has no concept of
347 // operating on more than one loop at a time so don't confuse it with such
349 if (containsAddRecFromDifferentLoop(AddRec->getOperand(0), L))
352 Start = SE->getAddExpr(Start, AddRec->getOperand(0));
354 if (!isa<SCEVConstant>(AddRec->getOperand(1))) {
355 // If stride is an instruction, make sure it dominates the loop preheader.
356 // Otherwise we could end up with a use before def situation.
357 BasicBlock *Preheader = L->getLoopPreheader();
358 if (!AddRec->getOperand(1)->dominates(Preheader, DT))
361 DOUT << "[" << L->getHeader()->getName()
362 << "] Variable stride: " << *AddRec << "\n";
365 Stride = AddRec->getOperand(1);
369 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
370 /// and now we need to decide whether the user should use the preinc or post-inc
371 /// value. If this user should use the post-inc version of the IV, return true.
373 /// Choosing wrong here can break dominance properties (if we choose to use the
374 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
375 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
376 /// should use the post-inc value).
377 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
378 Loop *L, DominatorTree *DT, Pass *P,
379 SmallVectorImpl<Instruction*> &DeadInsts){
380 // If the user is in the loop, use the preinc value.
381 if (L->contains(User->getParent())) return false;
383 BasicBlock *LatchBlock = L->getLoopLatch();
385 // Ok, the user is outside of the loop. If it is dominated by the latch
386 // block, use the post-inc value.
387 if (DT->dominates(LatchBlock, User->getParent()))
390 // There is one case we have to be careful of: PHI nodes. These little guys
391 // can live in blocks that do not dominate the latch block, but (since their
392 // uses occur in the predecessor block, not the block the PHI lives in) should
393 // still use the post-inc value. Check for this case now.
394 PHINode *PN = dyn_cast<PHINode>(User);
395 if (!PN) return false; // not a phi, not dominated by latch block.
397 // Look at all of the uses of IV by the PHI node. If any use corresponds to
398 // a block that is not dominated by the latch block, give up and use the
399 // preincremented value.
400 unsigned NumUses = 0;
401 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
402 if (PN->getIncomingValue(i) == IV) {
404 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
408 // Okay, all uses of IV by PN are in predecessor blocks that really are
409 // dominated by the latch block. Use the post-incremented value.
413 /// isAddressUse - Returns true if the specified instruction is using the
414 /// specified value as an address.
415 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
416 bool isAddress = isa<LoadInst>(Inst);
417 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
418 if (SI->getOperand(1) == OperandVal)
420 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
421 // Addressing modes can also be folded into prefetches and a variety
423 switch (II->getIntrinsicID()) {
425 case Intrinsic::prefetch:
426 case Intrinsic::x86_sse2_loadu_dq:
427 case Intrinsic::x86_sse2_loadu_pd:
428 case Intrinsic::x86_sse_loadu_ps:
429 case Intrinsic::x86_sse_storeu_ps:
430 case Intrinsic::x86_sse2_storeu_pd:
431 case Intrinsic::x86_sse2_storeu_dq:
432 case Intrinsic::x86_sse2_storel_dq:
433 if (II->getOperand(1) == OperandVal)
441 /// getAccessType - Return the type of the memory being accessed.
442 static const Type *getAccessType(const Instruction *Inst) {
443 const Type *UseTy = Inst->getType();
444 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
445 UseTy = SI->getOperand(0)->getType();
446 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
447 // Addressing modes can also be folded into prefetches and a variety
449 switch (II->getIntrinsicID()) {
451 case Intrinsic::x86_sse_storeu_ps:
452 case Intrinsic::x86_sse2_storeu_pd:
453 case Intrinsic::x86_sse2_storeu_dq:
454 case Intrinsic::x86_sse2_storel_dq:
455 UseTy = II->getOperand(1)->getType();
462 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
463 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
464 /// return true. Otherwise, return false.
465 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
466 SmallPtrSet<Instruction*,16> &Processed) {
467 if (!SE->isSCEVable(I->getType()))
468 return false; // Void and FP expressions cannot be reduced.
470 // LSR is not APInt clean, do not touch integers bigger than 64-bits.
471 if (SE->getTypeSizeInBits(I->getType()) > 64)
474 if (!Processed.insert(I))
475 return true; // Instruction already handled.
477 // Get the symbolic expression for this instruction.
478 SCEVHandle ISE = SE->getSCEV(I);
479 if (isa<SCEVCouldNotCompute>(ISE)) return false;
481 // Get the start and stride for this expression.
482 SCEVHandle Start = SE->getIntegerSCEV(0, ISE->getType());
483 SCEVHandle Stride = Start;
484 if (!getSCEVStartAndStride(ISE, L, Start, Stride, SE, DT))
485 return false; // Non-reducible symbolic expression, bail out.
487 std::vector<Instruction *> IUsers;
488 // Collect all I uses now because IVUseShouldUsePostIncValue may
489 // invalidate use_iterator.
490 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
491 IUsers.push_back(cast<Instruction>(*UI));
493 for (unsigned iused_index = 0, iused_size = IUsers.size();
494 iused_index != iused_size; ++iused_index) {
496 Instruction *User = IUsers[iused_index];
498 // Do not infinitely recurse on PHI nodes.
499 if (isa<PHINode>(User) && Processed.count(User))
502 // Descend recursively, but not into PHI nodes outside the current loop.
503 // It's important to see the entire expression outside the loop to get
504 // choices that depend on addressing mode use right, although we won't
505 // consider references ouside the loop in all cases.
506 // If User is already in Processed, we don't want to recurse into it again,
507 // but do want to record a second reference in the same instruction.
508 bool AddUserToIVUsers = false;
509 if (LI->getLoopFor(User->getParent()) != L) {
510 if (isa<PHINode>(User) || Processed.count(User) ||
511 !AddUsersIfInteresting(User, L, Processed)) {
512 DOUT << "FOUND USER in other loop: " << *User
513 << " OF SCEV: " << *ISE << "\n";
514 AddUserToIVUsers = true;
516 } else if (Processed.count(User) ||
517 !AddUsersIfInteresting(User, L, Processed)) {
518 DOUT << "FOUND USER: " << *User
519 << " OF SCEV: " << *ISE << "\n";
520 AddUserToIVUsers = true;
523 if (AddUserToIVUsers) {
524 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
525 if (StrideUses.Users.empty()) // First occurrence of this stride?
526 StrideOrder.push_back(Stride);
528 // Okay, we found a user that we cannot reduce. Analyze the instruction
529 // and decide what to do with it. If we are a use inside of the loop, use
530 // the value before incrementation, otherwise use it after incrementation.
531 if (IVUseShouldUsePostIncValue(User, I, L, DT, this, DeadInsts)) {
532 // The value used will be incremented by the stride more than we are
533 // expecting, so subtract this off.
534 SCEVHandle NewStart = SE->getMinusSCEV(Start, Stride);
535 StrideUses.addUser(NewStart, User, I);
536 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
537 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
539 StrideUses.addUser(Start, User, I);
547 /// BasedUser - For a particular base value, keep information about how we've
548 /// partitioned the expression so far.
550 /// SE - The current ScalarEvolution object.
553 /// Base - The Base value for the PHI node that needs to be inserted for
554 /// this use. As the use is processed, information gets moved from this
555 /// field to the Imm field (below). BasedUser values are sorted by this
559 /// Inst - The instruction using the induction variable.
562 /// OperandValToReplace - The operand value of Inst to replace with the
564 Value *OperandValToReplace;
566 /// Imm - The immediate value that should be added to the base immediately
567 /// before Inst, because it will be folded into the imm field of the
568 /// instruction. This is also sometimes used for loop-variant values that
569 /// must be added inside the loop.
572 /// Phi - The induction variable that performs the striding that
573 /// should be used for this user.
576 // isUseOfPostIncrementedValue - True if this should use the
577 // post-incremented version of this IV, not the preincremented version.
578 // This can only be set in special cases, such as the terminating setcc
579 // instruction for a loop and uses outside the loop that are dominated by
581 bool isUseOfPostIncrementedValue;
583 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
584 : SE(se), Base(IVSU.Offset), Inst(IVSU.User),
585 OperandValToReplace(IVSU.OperandValToReplace),
586 Imm(SE->getIntegerSCEV(0, Base->getType())),
587 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
589 // Once we rewrite the code to insert the new IVs we want, update the
590 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
592 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
593 Instruction *InsertPt,
594 SCEVExpander &Rewriter, Loop *L, Pass *P,
595 SmallVectorImpl<Instruction*> &DeadInsts);
597 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
599 SCEVExpander &Rewriter,
600 Instruction *IP, Loop *L);
605 void BasedUser::dump() const {
606 cerr << " Base=" << *Base;
607 cerr << " Imm=" << *Imm;
608 cerr << " Inst: " << *Inst;
611 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
613 SCEVExpander &Rewriter,
614 Instruction *IP, Loop *L) {
615 // Figure out where we *really* want to insert this code. In particular, if
616 // the user is inside of a loop that is nested inside of L, we really don't
617 // want to insert this expression before the user, we'd rather pull it out as
618 // many loops as possible.
619 LoopInfo &LI = Rewriter.getLoopInfo();
620 Instruction *BaseInsertPt = IP;
622 // Figure out the most-nested loop that IP is in.
623 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
625 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
626 // the preheader of the outer-most loop where NewBase is not loop invariant.
627 if (L->contains(IP->getParent()))
628 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
629 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
630 InsertLoop = InsertLoop->getParentLoop();
633 Value *Base = Rewriter.expandCodeFor(NewBase, Ty, BaseInsertPt);
635 // If there is no immediate value, skip the next part.
639 // If we are inserting the base and imm values in the same block, make sure to
640 // adjust the IP position if insertion reused a result.
641 if (IP == BaseInsertPt)
642 IP = Rewriter.getInsertionPoint();
644 // Always emit the immediate (if non-zero) into the same block as the user.
645 SCEVHandle NewValSCEV = SE->getAddExpr(SE->getUnknown(Base), Imm);
646 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
650 // Once we rewrite the code to insert the new IVs we want, update the
651 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
652 // to it. NewBasePt is the last instruction which contributes to the
653 // value of NewBase in the case that it's a diffferent instruction from
654 // the PHI that NewBase is computed from, or null otherwise.
656 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
657 Instruction *NewBasePt,
658 SCEVExpander &Rewriter, Loop *L, Pass *P,
659 SmallVectorImpl<Instruction*> &DeadInsts){
660 if (!isa<PHINode>(Inst)) {
661 // By default, insert code at the user instruction.
662 BasicBlock::iterator InsertPt = Inst;
664 // However, if the Operand is itself an instruction, the (potentially
665 // complex) inserted code may be shared by many users. Because of this, we
666 // want to emit code for the computation of the operand right before its old
667 // computation. This is usually safe, because we obviously used to use the
668 // computation when it was computed in its current block. However, in some
669 // cases (e.g. use of a post-incremented induction variable) the NewBase
670 // value will be pinned to live somewhere after the original computation.
671 // In this case, we have to back off.
673 // If this is a use outside the loop (which means after, since it is based
674 // on a loop indvar) we use the post-incremented value, so that we don't
675 // artificially make the preinc value live out the bottom of the loop.
676 if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
677 if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
678 InsertPt = NewBasePt;
680 } else if (Instruction *OpInst
681 = dyn_cast<Instruction>(OperandValToReplace)) {
683 while (isa<PHINode>(InsertPt)) ++InsertPt;
686 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
687 OperandValToReplace->getType(),
688 Rewriter, InsertPt, L);
689 // Replace the use of the operand Value with the new Phi we just created.
690 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
692 DOUT << " Replacing with ";
693 DEBUG(WriteAsOperand(*DOUT, NewVal, /*PrintType=*/false));
694 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
698 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
699 // expression into each operand block that uses it. Note that PHI nodes can
700 // have multiple entries for the same predecessor. We use a map to make sure
701 // that a PHI node only has a single Value* for each predecessor (which also
702 // prevents us from inserting duplicate code in some blocks).
703 DenseMap<BasicBlock*, Value*> InsertedCode;
704 PHINode *PN = cast<PHINode>(Inst);
705 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
706 if (PN->getIncomingValue(i) == OperandValToReplace) {
707 // If the original expression is outside the loop, put the replacement
708 // code in the same place as the original expression,
709 // which need not be an immediate predecessor of this PHI. This way we
710 // need only one copy of it even if it is referenced multiple times in
711 // the PHI. We don't do this when the original expression is inside the
712 // loop because multiple copies sometimes do useful sinking of code in
714 Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
715 if (L->contains(OldLoc->getParent())) {
716 // If this is a critical edge, split the edge so that we do not insert
717 // the code on all predecessor/successor paths. We do this unless this
718 // is the canonical backedge for this loop, as this can make some
719 // inserted code be in an illegal position.
720 BasicBlock *PHIPred = PN->getIncomingBlock(i);
721 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
722 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
724 // First step, split the critical edge.
725 SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
727 // Next step: move the basic block. In particular, if the PHI node
728 // is outside of the loop, and PredTI is in the loop, we want to
729 // move the block to be immediately before the PHI block, not
730 // immediately after PredTI.
731 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
732 BasicBlock *NewBB = PN->getIncomingBlock(i);
733 NewBB->moveBefore(PN->getParent());
736 // Splitting the edge can reduce the number of PHI entries we have.
737 e = PN->getNumIncomingValues();
740 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
742 // Insert the code into the end of the predecessor block.
743 Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
744 PN->getIncomingBlock(i)->getTerminator() :
745 OldLoc->getParent()->getTerminator();
746 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
747 Rewriter, InsertPt, L);
749 DOUT << " Changing PHI use to ";
750 DEBUG(WriteAsOperand(*DOUT, Code, /*PrintType=*/false));
751 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
754 // Replace the use of the operand Value with the new Phi we just created.
755 PN->setIncomingValue(i, Code);
760 // PHI node might have become a constant value after SplitCriticalEdge.
761 DeadInsts.push_back(Inst);
765 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
766 /// mode, and does not need to be put in a register first.
767 static bool fitsInAddressMode(const SCEVHandle &V, const Type *UseTy,
768 const TargetLowering *TLI, bool HasBaseReg) {
769 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
770 int64_t VC = SC->getValue()->getSExtValue();
772 TargetLowering::AddrMode AM;
774 AM.HasBaseReg = HasBaseReg;
775 return TLI->isLegalAddressingMode(AM, UseTy);
777 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
778 return (VC > -(1 << 16) && VC < (1 << 16)-1);
782 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
783 if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
785 TargetLowering::AddrMode AM;
787 AM.HasBaseReg = HasBaseReg;
788 return TLI->isLegalAddressingMode(AM, UseTy);
790 // Default: assume global addresses are not legal.
797 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
798 /// loop varying to the Imm operand.
799 static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
800 Loop *L, ScalarEvolution *SE) {
801 if (Val->isLoopInvariant(L)) return; // Nothing to do.
803 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
804 std::vector<SCEVHandle> NewOps;
805 NewOps.reserve(SAE->getNumOperands());
807 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
808 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
809 // If this is a loop-variant expression, it must stay in the immediate
810 // field of the expression.
811 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
813 NewOps.push_back(SAE->getOperand(i));
817 Val = SE->getIntegerSCEV(0, Val->getType());
819 Val = SE->getAddExpr(NewOps);
820 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
821 // Try to pull immediates out of the start value of nested addrec's.
822 SCEVHandle Start = SARE->getStart();
823 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
825 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
827 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
829 // Otherwise, all of Val is variant, move the whole thing over.
830 Imm = SE->getAddExpr(Imm, Val);
831 Val = SE->getIntegerSCEV(0, Val->getType());
836 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
837 /// that can fit into the immediate field of instructions in the target.
838 /// Accumulate these immediate values into the Imm value.
839 static void MoveImmediateValues(const TargetLowering *TLI,
841 SCEVHandle &Val, SCEVHandle &Imm,
842 bool isAddress, Loop *L,
843 ScalarEvolution *SE) {
844 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
845 std::vector<SCEVHandle> NewOps;
846 NewOps.reserve(SAE->getNumOperands());
848 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
849 SCEVHandle NewOp = SAE->getOperand(i);
850 MoveImmediateValues(TLI, UseTy, NewOp, Imm, isAddress, L, SE);
852 if (!NewOp->isLoopInvariant(L)) {
853 // If this is a loop-variant expression, it must stay in the immediate
854 // field of the expression.
855 Imm = SE->getAddExpr(Imm, NewOp);
857 NewOps.push_back(NewOp);
862 Val = SE->getIntegerSCEV(0, Val->getType());
864 Val = SE->getAddExpr(NewOps);
866 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
867 // Try to pull immediates out of the start value of nested addrec's.
868 SCEVHandle Start = SARE->getStart();
869 MoveImmediateValues(TLI, UseTy, Start, Imm, isAddress, L, SE);
871 if (Start != SARE->getStart()) {
872 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
874 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
877 } else if (const SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
878 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
879 if (isAddress && fitsInAddressMode(SME->getOperand(0), UseTy, TLI, false) &&
880 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
882 SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
883 SCEVHandle NewOp = SME->getOperand(1);
884 MoveImmediateValues(TLI, UseTy, NewOp, SubImm, isAddress, L, SE);
886 // If we extracted something out of the subexpressions, see if we can
888 if (NewOp != SME->getOperand(1)) {
889 // Scale SubImm up by "8". If the result is a target constant, we are
891 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
892 if (fitsInAddressMode(SubImm, UseTy, TLI, false)) {
893 // Accumulate the immediate.
894 Imm = SE->getAddExpr(Imm, SubImm);
896 // Update what is left of 'Val'.
897 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
904 // Loop-variant expressions must stay in the immediate field of the
906 if ((isAddress && fitsInAddressMode(Val, UseTy, TLI, false)) ||
907 !Val->isLoopInvariant(L)) {
908 Imm = SE->getAddExpr(Imm, Val);
909 Val = SE->getIntegerSCEV(0, Val->getType());
913 // Otherwise, no immediates to move.
916 static void MoveImmediateValues(const TargetLowering *TLI,
918 SCEVHandle &Val, SCEVHandle &Imm,
919 bool isAddress, Loop *L,
920 ScalarEvolution *SE) {
921 const Type *UseTy = getAccessType(User);
922 MoveImmediateValues(TLI, UseTy, Val, Imm, isAddress, L, SE);
925 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
926 /// added together. This is used to reassociate common addition subexprs
927 /// together for maximal sharing when rewriting bases.
928 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
930 ScalarEvolution *SE) {
931 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
932 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
933 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
934 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
935 SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
936 if (SARE->getOperand(0) == Zero) {
937 SubExprs.push_back(Expr);
939 // Compute the addrec with zero as its base.
940 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
941 Ops[0] = Zero; // Start with zero base.
942 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
945 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
947 } else if (!Expr->isZero()) {
949 SubExprs.push_back(Expr);
953 // This is logically local to the following function, but C++ says we have
954 // to make it file scope.
955 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
957 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
958 /// the Uses, removing any common subexpressions, except that if all such
959 /// subexpressions can be folded into an addressing mode for all uses inside
960 /// the loop (this case is referred to as "free" in comments herein) we do
961 /// not remove anything. This looks for things like (a+b+c) and
962 /// (a+c+d) and computes the common (a+c) subexpression. The common expression
963 /// is *removed* from the Bases and returned.
965 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
966 ScalarEvolution *SE, Loop *L,
967 const TargetLowering *TLI) {
968 unsigned NumUses = Uses.size();
970 // Only one use? This is a very common case, so we handle it specially and
972 SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
973 SCEVHandle Result = Zero;
974 SCEVHandle FreeResult = Zero;
976 // If the use is inside the loop, use its base, regardless of what it is:
977 // it is clearly shared across all the IV's. If the use is outside the loop
978 // (which means after it) we don't want to factor anything *into* the loop,
979 // so just use 0 as the base.
980 if (L->contains(Uses[0].Inst->getParent()))
981 std::swap(Result, Uses[0].Base);
985 // To find common subexpressions, count how many of Uses use each expression.
986 // If any subexpressions are used Uses.size() times, they are common.
987 // Also track whether all uses of each expression can be moved into an
988 // an addressing mode "for free"; such expressions are left within the loop.
989 // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
990 std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
992 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
993 // order we see them.
994 std::vector<SCEVHandle> UniqueSubExprs;
996 std::vector<SCEVHandle> SubExprs;
997 unsigned NumUsesInsideLoop = 0;
998 for (unsigned i = 0; i != NumUses; ++i) {
999 // If the user is outside the loop, just ignore it for base computation.
1000 // Since the user is outside the loop, it must be *after* the loop (if it
1001 // were before, it could not be based on the loop IV). We don't want users
1002 // after the loop to affect base computation of values *inside* the loop,
1003 // because we can always add their offsets to the result IV after the loop
1004 // is done, ensuring we get good code inside the loop.
1005 if (!L->contains(Uses[i].Inst->getParent()))
1007 NumUsesInsideLoop++;
1009 // If the base is zero (which is common), return zero now, there are no
1010 // CSEs we can find.
1011 if (Uses[i].Base == Zero) return Zero;
1013 // If this use is as an address we may be able to put CSEs in the addressing
1014 // mode rather than hoisting them.
1015 bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
1016 // We may need the UseTy below, but only when isAddrUse, so compute it
1017 // only in that case.
1018 const Type *UseTy = 0;
1020 UseTy = getAccessType(Uses[i].Inst);
1022 // Split the expression into subexprs.
1023 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
1024 // Add one to SubExpressionUseData.Count for each subexpr present, and
1025 // if the subexpr is not a valid immediate within an addressing mode use,
1026 // set SubExpressionUseData.notAllUsesAreFree. We definitely want to
1027 // hoist these out of the loop (if they are common to all uses).
1028 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1029 if (++SubExpressionUseData[SubExprs[j]].Count == 1)
1030 UniqueSubExprs.push_back(SubExprs[j]);
1031 if (!isAddrUse || !fitsInAddressMode(SubExprs[j], UseTy, TLI, false))
1032 SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
1037 // Now that we know how many times each is used, build Result. Iterate over
1038 // UniqueSubexprs so that we have a stable ordering.
1039 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
1040 std::map<SCEVHandle, SubExprUseData>::iterator I =
1041 SubExpressionUseData.find(UniqueSubExprs[i]);
1042 assert(I != SubExpressionUseData.end() && "Entry not found?");
1043 if (I->second.Count == NumUsesInsideLoop) { // Found CSE!
1044 if (I->second.notAllUsesAreFree)
1045 Result = SE->getAddExpr(Result, I->first);
1047 FreeResult = SE->getAddExpr(FreeResult, I->first);
1049 // Remove non-cse's from SubExpressionUseData.
1050 SubExpressionUseData.erase(I);
1053 if (FreeResult != Zero) {
1054 // We have some subexpressions that can be subsumed into addressing
1055 // modes in every use inside the loop. However, it's possible that
1056 // there are so many of them that the combined FreeResult cannot
1057 // be subsumed, or that the target cannot handle both a FreeResult
1058 // and a Result in the same instruction (for example because it would
1059 // require too many registers). Check this.
1060 for (unsigned i=0; i<NumUses; ++i) {
1061 if (!L->contains(Uses[i].Inst->getParent()))
1063 // We know this is an addressing mode use; if there are any uses that
1064 // are not, FreeResult would be Zero.
1065 const Type *UseTy = getAccessType(Uses[i].Inst);
1066 if (!fitsInAddressMode(FreeResult, UseTy, TLI, Result!=Zero)) {
1067 // FIXME: could split up FreeResult into pieces here, some hoisted
1068 // and some not. There is no obvious advantage to this.
1069 Result = SE->getAddExpr(Result, FreeResult);
1076 // If we found no CSE's, return now.
1077 if (Result == Zero) return Result;
1079 // If we still have a FreeResult, remove its subexpressions from
1080 // SubExpressionUseData. This means they will remain in the use Bases.
1081 if (FreeResult != Zero) {
1082 SeparateSubExprs(SubExprs, FreeResult, SE);
1083 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1084 std::map<SCEVHandle, SubExprUseData>::iterator I =
1085 SubExpressionUseData.find(SubExprs[j]);
1086 SubExpressionUseData.erase(I);
1091 // Otherwise, remove all of the CSE's we found from each of the base values.
1092 for (unsigned i = 0; i != NumUses; ++i) {
1093 // Uses outside the loop don't necessarily include the common base, but
1094 // the final IV value coming into those uses does. Instead of trying to
1095 // remove the pieces of the common base, which might not be there,
1096 // subtract off the base to compensate for this.
1097 if (!L->contains(Uses[i].Inst->getParent())) {
1098 Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
1102 // Split the expression into subexprs.
1103 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
1105 // Remove any common subexpressions.
1106 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
1107 if (SubExpressionUseData.count(SubExprs[j])) {
1108 SubExprs.erase(SubExprs.begin()+j);
1112 // Finally, add the non-shared expressions together.
1113 if (SubExprs.empty())
1114 Uses[i].Base = Zero;
1116 Uses[i].Base = SE->getAddExpr(SubExprs);
1123 /// ValidStride - Check whether the given Scale is valid for all loads and
1124 /// stores in UsersToProcess.
1126 bool LoopStrengthReduce::ValidStride(bool HasBaseReg,
1128 const std::vector<BasedUser>& UsersToProcess) {
1132 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
1133 // If this is a load or other access, pass the type of the access in.
1134 const Type *AccessTy = Type::VoidTy;
1135 if (isAddressUse(UsersToProcess[i].Inst,
1136 UsersToProcess[i].OperandValToReplace))
1137 AccessTy = getAccessType(UsersToProcess[i].Inst);
1138 else if (isa<PHINode>(UsersToProcess[i].Inst))
1141 TargetLowering::AddrMode AM;
1142 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
1143 AM.BaseOffs = SC->getValue()->getSExtValue();
1144 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
1147 // If load[imm+r*scale] is illegal, bail out.
1148 if (!TLI->isLegalAddressingMode(AM, AccessTy))
1154 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
1156 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
1160 Ty1 = SE->getEffectiveSCEVType(Ty1);
1161 Ty2 = SE->getEffectiveSCEVType(Ty2);
1164 if (Ty1->canLosslesslyBitCastTo(Ty2))
1166 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
1171 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
1172 /// of a previous stride and it is a legal value for the target addressing
1173 /// mode scale component and optional base reg. This allows the users of
1174 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
1175 /// reuse is possible. Factors can be negative on same targets, e.g. ARM.
1177 /// If all uses are outside the loop, we don't require that all multiplies
1178 /// be folded into the addressing mode, nor even that the factor be constant;
1179 /// a multiply (executed once) outside the loop is better than another IV
1180 /// within. Well, usually.
1181 SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
1182 bool AllUsesAreAddresses,
1183 bool AllUsesAreOutsideLoop,
1184 const SCEVHandle &Stride,
1185 IVExpr &IV, const Type *Ty,
1186 const std::vector<BasedUser>& UsersToProcess) {
1187 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
1188 int64_t SInt = SC->getValue()->getSExtValue();
1189 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1191 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1192 IVsByStride.find(StrideOrder[NewStride]);
1193 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1195 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1196 if (SI->first != Stride &&
1197 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
1199 int64_t Scale = SInt / SSInt;
1200 // Check that this stride is valid for all the types used for loads and
1201 // stores; if it can be used for some and not others, we might as well use
1202 // the original stride everywhere, since we have to create the IV for it
1203 // anyway. If the scale is 1, then we don't need to worry about folding
1206 (AllUsesAreAddresses &&
1207 ValidStride(HasBaseReg, Scale, UsersToProcess)))
1208 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1209 IE = SI->second.IVs.end(); II != IE; ++II)
1210 // FIXME: Only handle base == 0 for now.
1211 // Only reuse previous IV if it would not require a type conversion.
1212 if (II->Base->isZero() &&
1213 !RequiresTypeConversion(II->Base->getType(), Ty)) {
1215 return SE->getIntegerSCEV(Scale, Stride->getType());
1218 } else if (AllUsesAreOutsideLoop) {
1219 // Accept nonconstant strides here; it is really really right to substitute
1220 // an existing IV if we can.
1221 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1223 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1224 IVsByStride.find(StrideOrder[NewStride]);
1225 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1227 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1228 if (SI->first != Stride && SSInt != 1)
1230 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1231 IE = SI->second.IVs.end(); II != IE; ++II)
1232 // Accept nonzero base here.
1233 // Only reuse previous IV if it would not require a type conversion.
1234 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1239 // Special case, old IV is -1*x and this one is x. Can treat this one as
1241 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1243 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1244 IVsByStride.find(StrideOrder[NewStride]);
1245 if (SI == IVsByStride.end())
1247 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1248 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
1249 if (Stride == ME->getOperand(1) &&
1250 SC->getValue()->getSExtValue() == -1LL)
1251 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1252 IE = SI->second.IVs.end(); II != IE; ++II)
1253 // Accept nonzero base here.
1254 // Only reuse previous IV if it would not require type conversion.
1255 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1257 return SE->getIntegerSCEV(-1LL, Stride->getType());
1261 return SE->getIntegerSCEV(0, Stride->getType());
1264 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1265 /// returns true if Val's isUseOfPostIncrementedValue is true.
1266 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1267 return Val.isUseOfPostIncrementedValue;
1270 /// isNonConstantNegative - Return true if the specified scev is negated, but
1272 static bool isNonConstantNegative(const SCEVHandle &Expr) {
1273 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1274 if (!Mul) return false;
1276 // If there is a constant factor, it will be first.
1277 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1278 if (!SC) return false;
1280 // Return true if the value is negative, this matches things like (-42 * V).
1281 return SC->getValue()->getValue().isNegative();
1284 // CollectIVUsers - Transform our list of users and offsets to a bit more
1285 // complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1286 // of the strided accesses, as well as the old information from Uses. We
1287 // progressively move information from the Base field to the Imm field, until
1288 // we eventually have the full access expression to rewrite the use.
1289 SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1290 IVUsersOfOneStride &Uses,
1292 bool &AllUsesAreAddresses,
1293 bool &AllUsesAreOutsideLoop,
1294 std::vector<BasedUser> &UsersToProcess) {
1295 UsersToProcess.reserve(Uses.Users.size());
1296 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
1297 UsersToProcess.push_back(BasedUser(Uses.Users[i], SE));
1299 // Move any loop variant operands from the offset field to the immediate
1300 // field of the use, so that we don't try to use something before it is
1302 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1303 UsersToProcess.back().Imm, L, SE);
1304 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1305 "Base value is not loop invariant!");
1308 // We now have a whole bunch of uses of like-strided induction variables, but
1309 // they might all have different bases. We want to emit one PHI node for this
1310 // stride which we fold as many common expressions (between the IVs) into as
1311 // possible. Start by identifying the common expressions in the base values
1312 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1313 // "A+B"), emit it to the preheader, then remove the expression from the
1314 // UsersToProcess base values.
1315 SCEVHandle CommonExprs =
1316 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1318 // Next, figure out what we can represent in the immediate fields of
1319 // instructions. If we can represent anything there, move it to the imm
1320 // fields of the BasedUsers. We do this so that it increases the commonality
1321 // of the remaining uses.
1322 unsigned NumPHI = 0;
1323 bool HasAddress = false;
1324 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1325 // If the user is not in the current loop, this means it is using the exit
1326 // value of the IV. Do not put anything in the base, make sure it's all in
1327 // the immediate field to allow as much factoring as possible.
1328 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1329 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1330 UsersToProcess[i].Base);
1331 UsersToProcess[i].Base =
1332 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1334 // Not all uses are outside the loop.
1335 AllUsesAreOutsideLoop = false;
1337 // Addressing modes can be folded into loads and stores. Be careful that
1338 // the store is through the expression, not of the expression though.
1340 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1341 UsersToProcess[i].OperandValToReplace);
1342 if (isa<PHINode>(UsersToProcess[i].Inst)) {
1350 // If this use isn't an address, then not all uses are addresses.
1351 if (!isAddress && !isPHI)
1352 AllUsesAreAddresses = false;
1354 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1355 UsersToProcess[i].Imm, isAddress, L, SE);
1359 // If one of the use is a PHI node and all other uses are addresses, still
1360 // allow iv reuse. Essentially we are trading one constant multiplication
1361 // for one fewer iv.
1363 AllUsesAreAddresses = false;
1365 // There are no in-loop address uses.
1366 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1367 AllUsesAreAddresses = false;
1372 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1373 /// is valid and profitable for the given set of users of a stride. In
1374 /// full strength-reduction mode, all addresses at the current stride are
1375 /// strength-reduced all the way down to pointer arithmetic.
1377 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1378 const std::vector<BasedUser> &UsersToProcess,
1380 bool AllUsesAreAddresses,
1381 SCEVHandle Stride) {
1382 if (!EnableFullLSRMode)
1385 // The heuristics below aim to avoid increasing register pressure, but
1386 // fully strength-reducing all the addresses increases the number of
1387 // add instructions, so don't do this when optimizing for size.
1388 // TODO: If the loop is large, the savings due to simpler addresses
1389 // may oughtweight the costs of the extra increment instructions.
1390 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1393 // TODO: For now, don't do full strength reduction if there could
1394 // potentially be greater-stride multiples of the current stride
1395 // which could reuse the current stride IV.
1396 if (StrideOrder.back() != Stride)
1399 // Iterate through the uses to find conditions that automatically rule out
1401 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1402 SCEV *Base = UsersToProcess[i].Base;
1403 SCEV *Imm = UsersToProcess[i].Imm;
1404 // If any users have a loop-variant component, they can't be fully
1405 // strength-reduced.
1406 if (Imm && !Imm->isLoopInvariant(L))
1408 // If there are to users with the same base and the difference between
1409 // the two Imm values can't be folded into the address, full
1410 // strength reduction would increase register pressure.
1412 SCEV *CurImm = UsersToProcess[i].Imm;
1413 if ((CurImm || Imm) && CurImm != Imm) {
1414 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1415 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1416 const Instruction *Inst = UsersToProcess[i].Inst;
1417 const Type *UseTy = getAccessType(Inst);
1418 SCEVHandle Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1419 if (!Diff->isZero() &&
1420 (!AllUsesAreAddresses ||
1421 !fitsInAddressMode(Diff, UseTy, TLI, /*HasBaseReg=*/true)))
1424 } while (++i != e && Base == UsersToProcess[i].Base);
1427 // If there's exactly one user in this stride, fully strength-reducing it
1428 // won't increase register pressure. If it's starting from a non-zero base,
1429 // it'll be simpler this way.
1430 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1433 // Otherwise, if there are any users in this stride that don't require
1434 // a register for their base, full strength-reduction will increase
1435 // register pressure.
1436 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1437 if (UsersToProcess[i].Base->isZero())
1440 // Otherwise, go for it.
1444 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1445 /// with the specified start and step values in the specified loop.
1447 /// If NegateStride is true, the stride should be negated by using a
1448 /// subtract instead of an add.
1450 /// Return the created phi node.
1452 static PHINode *InsertAffinePhi(SCEVHandle Start, SCEVHandle Step,
1454 SCEVExpander &Rewriter) {
1455 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1456 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1458 BasicBlock *Header = L->getHeader();
1459 BasicBlock *Preheader = L->getLoopPreheader();
1460 BasicBlock *LatchBlock = L->getLoopLatch();
1461 const Type *Ty = Start->getType();
1462 Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
1464 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1465 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1468 // If the stride is negative, insert a sub instead of an add for the
1470 bool isNegative = isNonConstantNegative(Step);
1471 SCEVHandle IncAmount = Step;
1473 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1475 // Insert an add instruction right before the terminator corresponding
1476 // to the back-edge.
1477 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1478 Preheader->getTerminator());
1481 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1482 LatchBlock->getTerminator());
1484 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1485 LatchBlock->getTerminator());
1487 if (!isa<ConstantInt>(StepV)) ++NumVariable;
1489 PN->addIncoming(IncV, LatchBlock);
1495 static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1496 // We want to emit code for users inside the loop first. To do this, we
1497 // rearrange BasedUser so that the entries at the end have
1498 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1499 // vector (so we handle them first).
1500 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1501 PartitionByIsUseOfPostIncrementedValue);
1503 // Sort this by base, so that things with the same base are handled
1504 // together. By partitioning first and stable-sorting later, we are
1505 // guaranteed that within each base we will pop off users from within the
1506 // loop before users outside of the loop with a particular base.
1508 // We would like to use stable_sort here, but we can't. The problem is that
1509 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1510 // we don't have anything to do a '<' comparison on. Because we think the
1511 // number of uses is small, do a horrible bubble sort which just relies on
1513 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1514 // Get a base value.
1515 SCEVHandle Base = UsersToProcess[i].Base;
1517 // Compact everything with this base to be consecutive with this one.
1518 for (unsigned j = i+1; j != e; ++j) {
1519 if (UsersToProcess[j].Base == Base) {
1520 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1527 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1528 /// UsersToProcess, meaning lowering addresses all the way down to direct
1529 /// pointer arithmetic.
1532 LoopStrengthReduce::PrepareToStrengthReduceFully(
1533 std::vector<BasedUser> &UsersToProcess,
1535 SCEVHandle CommonExprs,
1537 SCEVExpander &PreheaderRewriter) {
1538 DOUT << " Fully reducing all users\n";
1540 // Rewrite the UsersToProcess records, creating a separate PHI for each
1541 // unique Base value.
1542 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1543 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1544 // pick the first Imm value here to start with, and adjust it for the
1546 SCEVHandle Imm = UsersToProcess[i].Imm;
1547 SCEVHandle Base = UsersToProcess[i].Base;
1548 SCEVHandle Start = SE->getAddExpr(CommonExprs, Base, Imm);
1549 PHINode *Phi = InsertAffinePhi(Start, Stride, L,
1551 // Loop over all the users with the same base.
1553 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1554 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1555 UsersToProcess[i].Phi = Phi;
1556 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1557 "ShouldUseFullStrengthReductionMode should reject this!");
1558 } while (++i != e && Base == UsersToProcess[i].Base);
1562 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1563 /// given users to share.
1566 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1567 std::vector<BasedUser> &UsersToProcess,
1569 SCEVHandle CommonExprs,
1572 SCEVExpander &PreheaderRewriter) {
1573 DOUT << " Inserting new PHI:\n";
1575 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1579 // Remember this in case a later stride is multiple of this.
1580 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1582 // All the users will share this new IV.
1583 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1584 UsersToProcess[i].Phi = Phi;
1587 DEBUG(WriteAsOperand(*DOUT, Phi, /*PrintType=*/false));
1591 /// PrepareToStrengthReduceWithNewPhi - Prepare for the given users to reuse
1592 /// an induction variable with a stride that is a factor of the current
1593 /// induction variable.
1596 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1597 std::vector<BasedUser> &UsersToProcess,
1599 const IVExpr &ReuseIV,
1600 Instruction *PreInsertPt) {
1601 DOUT << " Rewriting in terms of existing IV of STRIDE " << *ReuseIV.Stride
1602 << " and BASE " << *ReuseIV.Base << "\n";
1604 // All the users will share the reused IV.
1605 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1606 UsersToProcess[i].Phi = ReuseIV.PHI;
1608 Constant *C = dyn_cast<Constant>(CommonBaseV);
1610 (!C->isNullValue() &&
1611 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1613 // We want the common base emitted into the preheader! This is just
1614 // using cast as a copy so BitCast (no-op cast) is appropriate
1615 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1616 "commonbase", PreInsertPt);
1619 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1620 const Type *AccessTy,
1621 std::vector<BasedUser> &UsersToProcess,
1622 const TargetLowering *TLI) {
1623 SmallVector<Instruction*, 16> AddrModeInsts;
1624 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1625 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1627 ExtAddrMode AddrMode =
1628 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1629 AccessTy, UsersToProcess[i].Inst,
1630 AddrModeInsts, *TLI);
1631 if (GV && GV != AddrMode.BaseGV)
1633 if (Offset && !AddrMode.BaseOffs)
1634 // FIXME: How to accurate check it's immediate offset is folded.
1636 AddrModeInsts.clear();
1641 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1642 /// stride of IV. All of the users may have different starting values, and this
1643 /// may not be the only stride.
1644 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1645 IVUsersOfOneStride &Uses,
1647 // If all the users are moved to another stride, then there is nothing to do.
1648 if (Uses.Users.empty())
1651 // Keep track if every use in UsersToProcess is an address. If they all are,
1652 // we may be able to rewrite the entire collection of them in terms of a
1653 // smaller-stride IV.
1654 bool AllUsesAreAddresses = true;
1656 // Keep track if every use of a single stride is outside the loop. If so,
1657 // we want to be more aggressive about reusing a smaller-stride IV; a
1658 // multiply outside the loop is better than another IV inside. Well, usually.
1659 bool AllUsesAreOutsideLoop = true;
1661 // Transform our list of users and offsets to a bit more complex table. In
1662 // this new vector, each 'BasedUser' contains 'Base' the base of the
1663 // strided accessas well as the old information from Uses. We progressively
1664 // move information from the Base field to the Imm field, until we eventually
1665 // have the full access expression to rewrite the use.
1666 std::vector<BasedUser> UsersToProcess;
1667 SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1668 AllUsesAreOutsideLoop,
1671 // Sort the UsersToProcess array so that users with common bases are
1672 // next to each other.
1673 SortUsersToProcess(UsersToProcess);
1675 // If we managed to find some expressions in common, we'll need to carry
1676 // their value in a register and add it in for each use. This will take up
1677 // a register operand, which potentially restricts what stride values are
1679 bool HaveCommonExprs = !CommonExprs->isZero();
1680 const Type *ReplacedTy = CommonExprs->getType();
1682 // If all uses are addresses, consider sinking the immediate part of the
1683 // common expression back into uses if they can fit in the immediate fields.
1684 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1685 SCEVHandle NewCommon = CommonExprs;
1686 SCEVHandle Imm = SE->getIntegerSCEV(0, ReplacedTy);
1687 MoveImmediateValues(TLI, Type::VoidTy, NewCommon, Imm, true, L, SE);
1688 if (!Imm->isZero()) {
1691 // If the immediate part of the common expression is a GV, check if it's
1692 // possible to fold it into the target addressing mode.
1693 GlobalValue *GV = 0;
1694 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
1695 GV = dyn_cast<GlobalValue>(SU->getValue());
1697 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
1698 Offset = SC->getValue()->getSExtValue();
1700 // Pass VoidTy as the AccessTy to be conservative, because
1701 // there could be multiple access types among all the uses.
1702 DoSink = IsImmFoldedIntoAddrMode(GV, Offset, Type::VoidTy,
1703 UsersToProcess, TLI);
1706 DOUT << " Sinking " << *Imm << " back down into uses\n";
1707 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1708 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1709 CommonExprs = NewCommon;
1710 HaveCommonExprs = !CommonExprs->isZero();
1716 // Now that we know what we need to do, insert the PHI node itself.
1718 DOUT << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1720 << " Common base: " << *CommonExprs << "\n";
1722 SCEVExpander Rewriter(*SE, *LI);
1723 SCEVExpander PreheaderRewriter(*SE, *LI);
1725 BasicBlock *Preheader = L->getLoopPreheader();
1726 Instruction *PreInsertPt = Preheader->getTerminator();
1727 BasicBlock *LatchBlock = L->getLoopLatch();
1729 Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
1731 SCEVHandle RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1732 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1733 SE->getIntegerSCEV(0, Type::Int32Ty),
1736 /// Choose a strength-reduction strategy and prepare for it by creating
1737 /// the necessary PHIs and adjusting the bookkeeping.
1738 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1739 AllUsesAreAddresses, Stride)) {
1740 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1743 // Emit the initial base value into the loop preheader.
1744 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1747 // If all uses are addresses, check if it is possible to reuse an IV with a
1748 // stride that is a factor of this stride. And that the multiple is a number
1749 // that can be encoded in the scale field of the target addressing mode. And
1750 // that we will have a valid instruction after this substition, including
1751 // the immediate field, if any.
1752 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1753 AllUsesAreOutsideLoop,
1754 Stride, ReuseIV, ReplacedTy,
1756 if (isa<SCEVConstant>(RewriteFactor) &&
1757 cast<SCEVConstant>(RewriteFactor)->isZero())
1758 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1759 CommonBaseV, L, PreheaderRewriter);
1761 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1762 ReuseIV, PreInsertPt);
1765 // Process all the users now, replacing their strided uses with
1766 // strength-reduced forms. This outer loop handles all bases, the inner
1767 // loop handles all users of a particular base.
1768 while (!UsersToProcess.empty()) {
1769 SCEVHandle Base = UsersToProcess.back().Base;
1770 Instruction *Inst = UsersToProcess.back().Inst;
1772 // Emit the code for Base into the preheader.
1774 if (!Base->isZero()) {
1775 BaseV = PreheaderRewriter.expandCodeFor(Base, Base->getType(),
1778 DOUT << " INSERTING code for BASE = " << *Base << ":";
1779 if (BaseV->hasName())
1780 DOUT << " Result value name = %" << BaseV->getNameStr();
1783 // If BaseV is a non-zero constant, make sure that it gets inserted into
1784 // the preheader, instead of being forward substituted into the uses. We
1785 // do this by forcing a BitCast (noop cast) to be inserted into the
1786 // preheader in this case.
1787 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false)) {
1788 // We want this constant emitted into the preheader! This is just
1789 // using cast as a copy so BitCast (no-op cast) is appropriate
1790 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1795 // Emit the code to add the immediate offset to the Phi value, just before
1796 // the instructions that we identified as using this stride and base.
1798 // FIXME: Use emitted users to emit other users.
1799 BasedUser &User = UsersToProcess.back();
1801 DOUT << " Examining use ";
1802 DEBUG(WriteAsOperand(*DOUT, UsersToProcess.back().OperandValToReplace,
1803 /*PrintType=*/false));
1804 DOUT << " in Inst: " << *(User.Inst);
1806 // If this instruction wants to use the post-incremented value, move it
1807 // after the post-inc and use its value instead of the PHI.
1808 Value *RewriteOp = User.Phi;
1809 if (User.isUseOfPostIncrementedValue) {
1810 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1812 // If this user is in the loop, make sure it is the last thing in the
1813 // loop to ensure it is dominated by the increment.
1814 if (L->contains(User.Inst->getParent()))
1815 User.Inst->moveBefore(LatchBlock->getTerminator());
1818 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
1820 if (SE->getTypeSizeInBits(RewriteOp->getType()) !=
1821 SE->getTypeSizeInBits(ReplacedTy)) {
1822 assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1823 SE->getTypeSizeInBits(ReplacedTy) &&
1824 "Unexpected widening cast!");
1825 RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1828 // If we had to insert new instructions for RewriteOp, we have to
1829 // consider that they may not have been able to end up immediately
1830 // next to RewriteOp, because non-PHI instructions may never precede
1831 // PHI instructions in a block. In this case, remember where the last
1832 // instruction was inserted so that if we're replacing a different
1833 // PHI node, we can use the later point to expand the final
1835 Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
1836 if (RewriteOp == User.Phi) NewBasePt = 0;
1838 // Clear the SCEVExpander's expression map so that we are guaranteed
1839 // to have the code emitted where we expect it.
1842 // If we are reusing the iv, then it must be multiplied by a constant
1843 // factor to take advantage of the addressing mode scale component.
1844 if (!RewriteFactor->isZero()) {
1845 // If we're reusing an IV with a nonzero base (currently this happens
1846 // only when all reuses are outside the loop) subtract that base here.
1847 // The base has been used to initialize the PHI node but we don't want
1849 if (!ReuseIV.Base->isZero()) {
1850 SCEVHandle typedBase = ReuseIV.Base;
1851 if (SE->getTypeSizeInBits(RewriteExpr->getType()) !=
1852 SE->getTypeSizeInBits(ReuseIV.Base->getType())) {
1853 // It's possible the original IV is a larger type than the new IV,
1854 // in which case we have to truncate the Base. We checked in
1855 // RequiresTypeConversion that this is valid.
1856 assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1857 SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
1858 "Unexpected lengthening conversion!");
1859 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1860 RewriteExpr->getType());
1862 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1865 // Multiply old variable, with base removed, by new scale factor.
1866 RewriteExpr = SE->getMulExpr(RewriteFactor,
1869 // The common base is emitted in the loop preheader. But since we
1870 // are reusing an IV, it has not been used to initialize the PHI node.
1871 // Add it to the expression used to rewrite the uses.
1872 // When this use is outside the loop, we earlier subtracted the
1873 // common base, and are adding it back here. Use the same expression
1874 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1875 if (!CommonExprs->isZero()) {
1876 if (L->contains(User.Inst->getParent()))
1877 RewriteExpr = SE->getAddExpr(RewriteExpr,
1878 SE->getUnknown(CommonBaseV));
1880 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1884 // Now that we know what we need to do, insert code before User for the
1885 // immediate and any loop-variant expressions.
1887 // Add BaseV to the PHI value if needed.
1888 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1890 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1894 // Mark old value we replaced as possibly dead, so that it is eliminated
1895 // if we just replaced the last use of that value.
1896 DeadInsts.push_back(cast<Instruction>(User.OperandValToReplace));
1898 UsersToProcess.pop_back();
1901 // If there are any more users to process with the same base, process them
1902 // now. We sorted by base above, so we just have to check the last elt.
1903 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1904 // TODO: Next, find out which base index is the most common, pull it out.
1907 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1908 // different starting values, into different PHIs.
1911 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1912 /// set the IV user and stride information and return true, otherwise return
1914 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
1915 const SCEVHandle *&CondStride) {
1916 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1918 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1919 IVUsesByStride.find(StrideOrder[Stride]);
1920 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1922 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1923 E = SI->second.Users.end(); UI != E; ++UI)
1924 if (UI->User == Cond) {
1925 // NOTE: we could handle setcc instructions with multiple uses here, but
1926 // InstCombine does it as well for simple uses, it's not clear that it
1927 // occurs enough in real life to handle.
1929 CondStride = &SI->first;
1937 // Constant strides come first which in turns are sorted by their absolute
1938 // values. If absolute values are the same, then positive strides comes first.
1940 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1941 struct StrideCompare {
1942 const ScalarEvolution *SE;
1943 explicit StrideCompare(const ScalarEvolution *se) : SE(se) {}
1945 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1946 const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1947 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1949 int64_t LV = LHSC->getValue()->getSExtValue();
1950 int64_t RV = RHSC->getValue()->getSExtValue();
1951 uint64_t ALV = (LV < 0) ? -LV : LV;
1952 uint64_t ARV = (RV < 0) ? -RV : RV;
1960 // If it's the same value but different type, sort by bit width so
1961 // that we emit larger induction variables before smaller
1962 // ones, letting the smaller be re-written in terms of larger ones.
1963 return SE->getTypeSizeInBits(RHS->getType()) <
1964 SE->getTypeSizeInBits(LHS->getType());
1966 return LHSC && !RHSC;
1971 /// ChangeCompareStride - If a loop termination compare instruction is the
1972 /// only use of its stride, and the compaison is against a constant value,
1973 /// try eliminate the stride by moving the compare instruction to another
1974 /// stride and change its constant operand accordingly. e.g.
1980 /// if (v2 < 10) goto loop
1985 /// if (v1 < 30) goto loop
1986 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
1987 IVStrideUse* &CondUse,
1988 const SCEVHandle* &CondStride) {
1989 if (StrideOrder.size() < 2 ||
1990 IVUsesByStride[*CondStride].Users.size() != 1)
1992 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
1993 if (!SC) return Cond;
1995 ICmpInst::Predicate Predicate = Cond->getPredicate();
1996 int64_t CmpSSInt = SC->getValue()->getSExtValue();
1997 unsigned BitWidth = SE->getTypeSizeInBits((*CondStride)->getType());
1998 uint64_t SignBit = 1ULL << (BitWidth-1);
1999 const Type *CmpTy = Cond->getOperand(0)->getType();
2000 const Type *NewCmpTy = NULL;
2001 unsigned TyBits = SE->getTypeSizeInBits(CmpTy);
2002 unsigned NewTyBits = 0;
2003 SCEVHandle *NewStride = NULL;
2004 Value *NewCmpLHS = NULL;
2005 Value *NewCmpRHS = NULL;
2007 SCEVHandle NewOffset = SE->getIntegerSCEV(0, CmpTy);
2009 if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
2010 int64_t CmpVal = C->getValue().getSExtValue();
2012 // Check stride constant and the comparision constant signs to detect
2014 if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
2017 // Look for a suitable stride / iv as replacement.
2018 for (unsigned i = 0, e = StrideOrder.size(); i != e; ++i) {
2019 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2020 IVUsesByStride.find(StrideOrder[i]);
2021 if (!isa<SCEVConstant>(SI->first))
2023 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2024 if (SSInt == CmpSSInt ||
2025 abs(SSInt) < abs(CmpSSInt) ||
2026 (SSInt % CmpSSInt) != 0)
2029 Scale = SSInt / CmpSSInt;
2030 int64_t NewCmpVal = CmpVal * Scale;
2031 APInt Mul = APInt(BitWidth, NewCmpVal);
2032 // Check for overflow.
2033 if (Mul.getSExtValue() != NewCmpVal)
2036 // Watch out for overflow.
2037 if (ICmpInst::isSignedPredicate(Predicate) &&
2038 (CmpVal & SignBit) != (NewCmpVal & SignBit))
2041 if (NewCmpVal == CmpVal)
2043 // Pick the best iv to use trying to avoid a cast.
2045 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2046 E = SI->second.Users.end(); UI != E; ++UI) {
2047 NewCmpLHS = UI->OperandValToReplace;
2048 if (NewCmpLHS->getType() == CmpTy)
2054 NewCmpTy = NewCmpLHS->getType();
2055 NewTyBits = SE->getTypeSizeInBits(NewCmpTy);
2056 const Type *NewCmpIntTy = IntegerType::get(NewTyBits);
2057 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
2058 // Check if it is possible to rewrite it using
2059 // an iv / stride of a smaller integer type.
2060 unsigned Bits = NewTyBits;
2061 if (ICmpInst::isSignedPredicate(Predicate))
2063 uint64_t Mask = (1ULL << Bits) - 1;
2064 if (((uint64_t)NewCmpVal & Mask) != (uint64_t)NewCmpVal)
2068 // Don't rewrite if use offset is non-constant and the new type is
2069 // of a different type.
2070 // FIXME: too conservative?
2071 if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->Offset))
2074 bool AllUsesAreAddresses = true;
2075 bool AllUsesAreOutsideLoop = true;
2076 std::vector<BasedUser> UsersToProcess;
2077 SCEVHandle CommonExprs = CollectIVUsers(SI->first, SI->second, L,
2078 AllUsesAreAddresses,
2079 AllUsesAreOutsideLoop,
2081 // Avoid rewriting the compare instruction with an iv of new stride
2082 // if it's likely the new stride uses will be rewritten using the
2083 // stride of the compare instruction.
2084 if (AllUsesAreAddresses &&
2085 ValidStride(!CommonExprs->isZero(), Scale, UsersToProcess))
2088 // If scale is negative, use swapped predicate unless it's testing
2090 if (Scale < 0 && !Cond->isEquality())
2091 Predicate = ICmpInst::getSwappedPredicate(Predicate);
2093 NewStride = &StrideOrder[i];
2094 if (!isa<PointerType>(NewCmpTy))
2095 NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
2097 ConstantInt *CI = ConstantInt::get(NewCmpIntTy, NewCmpVal);
2098 NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
2100 NewOffset = TyBits == NewTyBits
2101 ? SE->getMulExpr(CondUse->Offset,
2102 SE->getConstant(ConstantInt::get(CmpTy, Scale)))
2103 : SE->getConstant(ConstantInt::get(NewCmpIntTy,
2104 cast<SCEVConstant>(CondUse->Offset)->getValue()->getSExtValue()*Scale));
2109 // Forgo this transformation if it the increment happens to be
2110 // unfortunately positioned after the condition, and the condition
2111 // has multiple uses which prevent it from being moved immediately
2112 // before the branch. See
2113 // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2114 // for an example of this situation.
2115 if (!Cond->hasOneUse()) {
2116 for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2123 // Create a new compare instruction using new stride / iv.
2124 ICmpInst *OldCond = Cond;
2125 // Insert new compare instruction.
2126 Cond = new ICmpInst(Predicate, NewCmpLHS, NewCmpRHS,
2127 L->getHeader()->getName() + ".termcond",
2130 // Remove the old compare instruction. The old indvar is probably dead too.
2131 DeadInsts.push_back(cast<Instruction>(CondUse->OperandValToReplace));
2132 SE->deleteValueFromRecords(OldCond);
2133 OldCond->replaceAllUsesWith(Cond);
2134 OldCond->eraseFromParent();
2136 IVUsesByStride[*CondStride].Users.pop_back();
2137 IVUsesByStride[*NewStride].addUser(NewOffset, Cond, NewCmpLHS);
2138 CondUse = &IVUsesByStride[*NewStride].Users.back();
2139 CondStride = NewStride;
2146 /// OptimizeSMax - Rewrite the loop's terminating condition if it uses
2147 /// an smax computation.
2149 /// This is a narrow solution to a specific, but acute, problem. For loops
2155 /// } while (++i < n);
2157 /// where the comparison is signed, the trip count isn't just 'n', because
2158 /// 'n' could be negative. And unfortunately this can come up even for loops
2159 /// where the user didn't use a C do-while loop. For example, seemingly
2160 /// well-behaved top-test loops will commonly be lowered like this:
2166 /// } while (++i < n);
2169 /// and then it's possible for subsequent optimization to obscure the if
2170 /// test in such a way that indvars can't find it.
2172 /// When indvars can't find the if test in loops like this, it creates a
2173 /// signed-max expression, which allows it to give the loop a canonical
2174 /// induction variable:
2177 /// smax = n < 1 ? 1 : n;
2180 /// } while (++i != smax);
2182 /// Canonical induction variables are necessary because the loop passes
2183 /// are designed around them. The most obvious example of this is the
2184 /// LoopInfo analysis, which doesn't remember trip count values. It
2185 /// expects to be able to rediscover the trip count each time it is
2186 /// needed, and it does this using a simple analyis that only succeeds if
2187 /// the loop has a canonical induction variable.
2189 /// However, when it comes time to generate code, the maximum operation
2190 /// can be quite costly, especially if it's inside of an outer loop.
2192 /// This function solves this problem by detecting this type of loop and
2193 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2194 /// the instructions for the maximum computation.
2196 ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
2197 IVStrideUse* &CondUse) {
2198 // Check that the loop matches the pattern we're looking for.
2199 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2200 Cond->getPredicate() != CmpInst::ICMP_NE)
2203 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2204 if (!Sel || !Sel->hasOneUse()) return Cond;
2206 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2207 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2209 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2211 // Add one to the backedge-taken count to get the trip count.
2212 SCEVHandle IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
2214 // Check for a max calculation that matches the pattern.
2215 SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
2216 if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
2218 SCEVHandle SMaxLHS = SMax->getOperand(0);
2219 SCEVHandle SMaxRHS = SMax->getOperand(1);
2220 if (!SMaxLHS || SMaxLHS != One) return Cond;
2222 // Check the relevant induction variable for conformance to
2224 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2225 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2226 if (!AR || !AR->isAffine() ||
2227 AR->getStart() != One ||
2228 AR->getStepRecurrence(*SE) != One)
2231 assert(AR->getLoop() == L &&
2232 "Loop condition operand is an addrec in a different loop!");
2234 // Check the right operand of the select, and remember it, as it will
2235 // be used in the new comparison instruction.
2237 if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
2238 NewRHS = Sel->getOperand(1);
2239 else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
2240 NewRHS = Sel->getOperand(2);
2241 if (!NewRHS) return Cond;
2243 // Ok, everything looks ok to change the condition into an SLT or SGE and
2244 // delete the max calculation.
2246 new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
2249 Cond->getOperand(0), NewRHS, "scmp", Cond);
2251 // Delete the max calculation instructions.
2252 SE->deleteValueFromRecords(Cond);
2253 Cond->replaceAllUsesWith(NewCond);
2254 Cond->eraseFromParent();
2255 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2256 SE->deleteValueFromRecords(Sel);
2257 Sel->eraseFromParent();
2258 if (Cmp->use_empty()) {
2259 SE->deleteValueFromRecords(Cmp);
2260 Cmp->eraseFromParent();
2262 CondUse->User = NewCond;
2266 /// OptimizeShadowIV - If IV is used in a int-to-float cast
2267 /// inside the loop then try to eliminate the cast opeation.
2268 void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2270 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2271 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2274 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e;
2276 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2277 IVUsesByStride.find(StrideOrder[Stride]);
2278 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
2279 if (!isa<SCEVConstant>(SI->first))
2282 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2283 E = SI->second.Users.end(); UI != E; /* empty */) {
2284 std::vector<IVStrideUse>::iterator CandidateUI = UI;
2286 Instruction *ShadowUse = CandidateUI->User;
2287 const Type *DestTy = NULL;
2289 /* If shadow use is a int->float cast then insert a second IV
2290 to eliminate this cast.
2292 for (unsigned i = 0; i < n; ++i)
2298 for (unsigned i = 0; i < n; ++i, ++d)
2301 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->User))
2302 DestTy = UCast->getDestTy();
2303 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->User))
2304 DestTy = SCast->getDestTy();
2305 if (!DestTy) continue;
2308 /* If target does not support DestTy natively then do not apply
2309 this transformation. */
2310 MVT DVT = TLI->getValueType(DestTy);
2311 if (!TLI->isTypeLegal(DVT)) continue;
2314 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2316 if (PH->getNumIncomingValues() != 2) continue;
2318 const Type *SrcTy = PH->getType();
2319 int Mantissa = DestTy->getFPMantissaWidth();
2320 if (Mantissa == -1) continue;
2321 if ((int)SE->getTypeSizeInBits(SrcTy) > Mantissa)
2324 unsigned Entry, Latch;
2325 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2333 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2334 if (!Init) continue;
2335 ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2337 BinaryOperator *Incr =
2338 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2339 if (!Incr) continue;
2340 if (Incr->getOpcode() != Instruction::Add
2341 && Incr->getOpcode() != Instruction::Sub)
2344 /* Initialize new IV, double d = 0.0 in above example. */
2345 ConstantInt *C = NULL;
2346 if (Incr->getOperand(0) == PH)
2347 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2348 else if (Incr->getOperand(1) == PH)
2349 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2355 /* Add new PHINode. */
2356 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2358 /* create new increment. '++d' in above example. */
2359 ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2360 BinaryOperator *NewIncr =
2361 BinaryOperator::Create(Incr->getOpcode(),
2362 NewPH, CFP, "IV.S.next.", Incr);
2364 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2365 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2367 /* Remove cast operation */
2368 SE->deleteValueFromRecords(ShadowUse);
2369 ShadowUse->replaceAllUsesWith(NewPH);
2370 ShadowUse->eraseFromParent();
2371 SI->second.Users.erase(CandidateUI);
2378 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2379 // uses in the loop, look to see if we can eliminate some, in favor of using
2380 // common indvars for the different uses.
2381 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2382 // TODO: implement optzns here.
2384 OptimizeShadowIV(L);
2386 // Finally, get the terminating condition for the loop if possible. If we
2387 // can, we want to change it to use a post-incremented version of its
2388 // induction variable, to allow coalescing the live ranges for the IV into
2389 // one register value.
2390 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
2391 BasicBlock *Preheader = L->getLoopPreheader();
2392 BasicBlock *LatchBlock =
2393 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
2394 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
2395 if (!TermBr || TermBr->isUnconditional() ||
2396 !isa<ICmpInst>(TermBr->getCondition()))
2398 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2400 // Search IVUsesByStride to find Cond's IVUse if there is one.
2401 IVStrideUse *CondUse = 0;
2402 const SCEVHandle *CondStride = 0;
2404 if (!FindIVUserForCond(Cond, CondUse, CondStride))
2405 return; // setcc doesn't use the IV.
2407 // If the trip count is computed in terms of an smax (due to ScalarEvolution
2408 // being unable to find a sufficient guard, for example), change the loop
2409 // comparison to use SLT instead of NE.
2410 Cond = OptimizeSMax(L, Cond, CondUse);
2412 // If possible, change stride and operands of the compare instruction to
2413 // eliminate one stride.
2414 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
2416 // It's possible for the setcc instruction to be anywhere in the loop, and
2417 // possible for it to have multiple users. If it is not immediately before
2418 // the latch block branch, move it.
2419 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2420 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
2421 Cond->moveBefore(TermBr);
2423 // Otherwise, clone the terminating condition and insert into the loopend.
2424 Cond = cast<ICmpInst>(Cond->clone());
2425 Cond->setName(L->getHeader()->getName() + ".termcond");
2426 LatchBlock->getInstList().insert(TermBr, Cond);
2428 // Clone the IVUse, as the old use still exists!
2429 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
2430 CondUse->OperandValToReplace);
2431 CondUse = &IVUsesByStride[*CondStride].Users.back();
2435 // If we get to here, we know that we can transform the setcc instruction to
2436 // use the post-incremented version of the IV, allowing us to coalesce the
2437 // live ranges for the IV correctly.
2438 CondUse->Offset = SE->getMinusSCEV(CondUse->Offset, *CondStride);
2439 CondUse->isUseOfPostIncrementedValue = true;
2443 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
2445 LI = &getAnalysis<LoopInfo>();
2446 DT = &getAnalysis<DominatorTree>();
2447 SE = &getAnalysis<ScalarEvolution>();
2450 // Find all uses of induction variables in this loop, and categorize
2451 // them by stride. Start by finding all of the PHI nodes in the header for
2452 // this loop. If they are induction variables, inspect their uses.
2453 SmallPtrSet<Instruction*,16> Processed; // Don't reprocess instructions.
2454 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
2455 AddUsersIfInteresting(I, L, Processed);
2457 if (!IVUsesByStride.empty()) {
2459 DOUT << "\nLSR on \"" << L->getHeader()->getParent()->getNameStart()
2464 // Sort the StrideOrder so we process larger strides first.
2465 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare(SE));
2467 // Optimize induction variables. Some indvar uses can be transformed to use
2468 // strides that will be needed for other purposes. A common example of this
2469 // is the exit test for the loop, which can often be rewritten to use the
2470 // computation of some other indvar to decide when to terminate the loop.
2473 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
2474 // doing computation in byte values, promote to 32-bit values if safe.
2476 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
2477 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2478 // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2479 // Need to be careful that IV's are all the same type. Only works for
2480 // intptr_t indvars.
2482 // IVsByStride keeps IVs for one particular loop.
2483 assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
2485 // Note: this processes each stride/type pair individually. All users
2486 // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2487 // Also, note that we iterate over IVUsesByStride indirectly by using
2488 // StrideOrder. This extra layer of indirection makes the ordering of
2489 // strides deterministic - not dependent on map order.
2490 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
2491 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2492 IVUsesByStride.find(StrideOrder[Stride]);
2493 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
2494 StrengthReduceStridedIVUsers(SI->first, SI->second, L);
2498 // We're done analyzing this loop; release all the state we built up for it.
2499 IVUsesByStride.clear();
2500 IVsByStride.clear();
2501 StrideOrder.clear();
2503 // Clean up after ourselves
2504 if (!DeadInsts.empty()) {
2505 DeleteTriviallyDeadInstructions();
2507 BasicBlock::iterator I = L->getHeader()->begin();
2508 while (PHINode *PN = dyn_cast<PHINode>(I++)) {
2509 // At this point, we know that we have killed one or more IV users.
2510 // It is worth checking to see if the cannonical indvar is also
2511 // dead, so that we can remove it as well.
2513 // We can remove a PHI if it is on a cycle in the def-use graph
2514 // where each node in the cycle has degree one, i.e. only one use,
2515 // and is an instruction with no side effects.
2517 // FIXME: this needs to eliminate an induction variable even if it's being
2518 // compared against some value to decide loop termination.
2519 if (!PN->hasOneUse())
2522 SmallPtrSet<PHINode *, 4> PHIs;
2523 for (Instruction *J = dyn_cast<Instruction>(*PN->use_begin());
2524 J && J->hasOneUse() && !J->mayWriteToMemory();
2525 J = dyn_cast<Instruction>(*J->use_begin())) {
2526 // If we find the original PHI, we've discovered a cycle.
2528 // Break the cycle and mark the PHI for deletion.
2529 SE->deleteValueFromRecords(PN);
2530 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
2531 DeadInsts.push_back(PN);
2535 // If we find a PHI more than once, we're on a cycle that
2536 // won't prove fruitful.
2537 if (isa<PHINode>(J) && !PHIs.insert(cast<PHINode>(J)))
2541 DeleteTriviallyDeadInstructions();