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 transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into forms suitable for efficient execution
14 // This pass performs a strength reduction on array references inside loops that
15 // have as one or more of their components the loop induction variable, it
16 // rewrites expressions to take advantage of scaled-index addressing modes
17 // available on the target, and it performs a variety of other optimizations
18 // related to loop induction variables.
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "loop-reduce"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Constants.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Type.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/IVUsers.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/LoopPass.h"
33 #include "llvm/Analysis/ScalarEvolutionExpander.h"
34 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Support/CFG.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/ValueHandle.h"
43 #include "llvm/Target/TargetLowering.h"
47 STATISTIC(NumReduced , "Number of IV uses strength reduced");
48 STATISTIC(NumInserted, "Number of PHIs inserted");
49 STATISTIC(NumVariable, "Number of PHIs with variable strides");
50 STATISTIC(NumEliminated, "Number of strides eliminated");
51 STATISTIC(NumShadow, "Number of Shadow IVs optimized");
52 STATISTIC(NumImmSunk, "Number of common expr immediates sunk into uses");
53 STATISTIC(NumLoopCond, "Number of loop terminating conds optimized");
55 static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
63 /// IVInfo - This structure keeps track of one IV expression inserted during
64 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
65 /// well as the PHI node and increment value created for rewrite.
66 struct VISIBILITY_HIDDEN IVExpr {
71 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi)
72 : Stride(stride), Base(base), PHI(phi) {}
75 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
76 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
77 struct VISIBILITY_HIDDEN IVsOfOneStride {
78 std::vector<IVExpr> IVs;
80 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI) {
81 IVs.push_back(IVExpr(Stride, Base, PHI));
85 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
92 /// IVsByStride - Keep track of all IVs that have been inserted for a
93 /// particular stride.
94 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
96 /// StrideNoReuse - Keep track of all the strides whose ivs cannot be
97 /// reused (nor should they be rewritten to reuse other strides).
98 SmallSet<SCEVHandle, 4> StrideNoReuse;
100 /// DeadInsts - Keep track of instructions we may have made dead, so that
101 /// we can remove them after we are done working.
102 SmallVector<WeakVH, 16> DeadInsts;
104 /// TLI - Keep a pointer of a TargetLowering to consult for determining
105 /// transformation profitability.
106 const TargetLowering *TLI;
109 static char ID; // Pass ID, replacement for typeid
110 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
111 LoopPass(&ID), TLI(tli) {
114 bool runOnLoop(Loop *L, LPPassManager &LPM);
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117 // We split critical edges, so we change the CFG. However, we do update
118 // many analyses if they are around.
119 AU.addPreservedID(LoopSimplifyID);
120 AU.addPreserved<LoopInfo>();
121 AU.addPreserved<DominanceFrontier>();
122 AU.addPreserved<DominatorTree>();
124 AU.addRequiredID(LoopSimplifyID);
125 AU.addRequired<LoopInfo>();
126 AU.addRequired<DominatorTree>();
127 AU.addRequired<ScalarEvolution>();
128 AU.addPreserved<ScalarEvolution>();
129 AU.addRequired<IVUsers>();
130 AU.addPreserved<IVUsers>();
134 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
135 IVStrideUse* &CondUse,
136 const SCEVHandle* &CondStride);
138 void OptimizeIndvars(Loop *L);
139 void OptimizeLoopCountIV(Loop *L);
140 void OptimizeLoopTermCond(Loop *L);
142 /// OptimizeShadowIV - If IV is used in a int-to-float cast
143 /// inside the loop then try to eliminate the cast opeation.
144 void OptimizeShadowIV(Loop *L);
146 /// OptimizeSMax - Rewrite the loop's terminating condition
147 /// if it uses an smax computation.
148 ICmpInst *OptimizeSMax(Loop *L, ICmpInst *Cond,
149 IVStrideUse* &CondUse);
151 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
152 const SCEVHandle *&CondStride);
153 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
154 SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
155 IVExpr&, const Type*,
156 const std::vector<BasedUser>& UsersToProcess);
157 bool ValidScale(bool, int64_t,
158 const std::vector<BasedUser>& UsersToProcess);
159 bool ValidOffset(bool, int64_t, int64_t,
160 const std::vector<BasedUser>& UsersToProcess);
161 SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
162 IVUsersOfOneStride &Uses,
164 bool &AllUsesAreAddresses,
165 bool &AllUsesAreOutsideLoop,
166 std::vector<BasedUser> &UsersToProcess);
167 bool ShouldUseFullStrengthReductionMode(
168 const std::vector<BasedUser> &UsersToProcess,
170 bool AllUsesAreAddresses,
172 void PrepareToStrengthReduceFully(
173 std::vector<BasedUser> &UsersToProcess,
175 SCEVHandle CommonExprs,
177 SCEVExpander &PreheaderRewriter);
178 void PrepareToStrengthReduceFromSmallerStride(
179 std::vector<BasedUser> &UsersToProcess,
181 const IVExpr &ReuseIV,
182 Instruction *PreInsertPt);
183 void PrepareToStrengthReduceWithNewPhi(
184 std::vector<BasedUser> &UsersToProcess,
186 SCEVHandle CommonExprs,
188 Instruction *IVIncInsertPt,
190 SCEVExpander &PreheaderRewriter);
191 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
192 IVUsersOfOneStride &Uses,
194 void DeleteTriviallyDeadInstructions();
198 char LoopStrengthReduce::ID = 0;
199 static RegisterPass<LoopStrengthReduce>
200 X("loop-reduce", "Loop Strength Reduction");
202 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
203 return new LoopStrengthReduce(TLI);
206 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
207 /// specified set are trivially dead, delete them and see if this makes any of
208 /// their operands subsequently dead.
209 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
210 if (DeadInsts.empty()) return;
212 while (!DeadInsts.empty()) {
213 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.back());
214 DeadInsts.pop_back();
216 if (I == 0 || !isInstructionTriviallyDead(I))
219 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
220 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
223 DeadInsts.push_back(U);
227 I->eraseFromParent();
232 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a
233 /// subexpression that is an AddRec from a loop other than L. An outer loop
234 /// of L is OK, but not an inner loop nor a disjoint loop.
235 static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
236 // This is very common, put it first.
237 if (isa<SCEVConstant>(S))
239 if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
240 for (unsigned int i=0; i< AE->getNumOperands(); i++)
241 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
245 if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
246 if (const Loop *newLoop = AE->getLoop()) {
249 // if newLoop is an outer loop of L, this is OK.
250 if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
255 if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
256 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
257 containsAddRecFromDifferentLoop(DE->getRHS(), L);
259 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
260 // need this when it is.
261 if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
262 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
263 containsAddRecFromDifferentLoop(DE->getRHS(), L);
265 if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
266 return containsAddRecFromDifferentLoop(CE->getOperand(), L);
270 /// isAddressUse - Returns true if the specified instruction is using the
271 /// specified value as an address.
272 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
273 bool isAddress = isa<LoadInst>(Inst);
274 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
275 if (SI->getOperand(1) == OperandVal)
277 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
278 // Addressing modes can also be folded into prefetches and a variety
280 switch (II->getIntrinsicID()) {
282 case Intrinsic::prefetch:
283 case Intrinsic::x86_sse2_loadu_dq:
284 case Intrinsic::x86_sse2_loadu_pd:
285 case Intrinsic::x86_sse_loadu_ps:
286 case Intrinsic::x86_sse_storeu_ps:
287 case Intrinsic::x86_sse2_storeu_pd:
288 case Intrinsic::x86_sse2_storeu_dq:
289 case Intrinsic::x86_sse2_storel_dq:
290 if (II->getOperand(1) == OperandVal)
298 /// getAccessType - Return the type of the memory being accessed.
299 static const Type *getAccessType(const Instruction *Inst) {
300 const Type *AccessTy = Inst->getType();
301 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
302 AccessTy = SI->getOperand(0)->getType();
303 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
304 // Addressing modes can also be folded into prefetches and a variety
306 switch (II->getIntrinsicID()) {
308 case Intrinsic::x86_sse_storeu_ps:
309 case Intrinsic::x86_sse2_storeu_pd:
310 case Intrinsic::x86_sse2_storeu_dq:
311 case Intrinsic::x86_sse2_storel_dq:
312 AccessTy = II->getOperand(1)->getType();
320 /// BasedUser - For a particular base value, keep information about how we've
321 /// partitioned the expression so far.
323 /// SE - The current ScalarEvolution object.
326 /// Base - The Base value for the PHI node that needs to be inserted for
327 /// this use. As the use is processed, information gets moved from this
328 /// field to the Imm field (below). BasedUser values are sorted by this
332 /// Inst - The instruction using the induction variable.
335 /// OperandValToReplace - The operand value of Inst to replace with the
337 Value *OperandValToReplace;
339 /// isSigned - The stride (and thus also the Base) of this use may be in
340 /// a narrower type than the use itself (OperandValToReplace->getType()).
341 /// When this is the case, the isSigned field indicates whether the
342 /// IV expression should be signed-extended instead of zero-extended to
343 /// fit the type of the use.
346 /// Imm - The immediate value that should be added to the base immediately
347 /// before Inst, because it will be folded into the imm field of the
348 /// instruction. This is also sometimes used for loop-variant values that
349 /// must be added inside the loop.
352 /// Phi - The induction variable that performs the striding that
353 /// should be used for this user.
356 // isUseOfPostIncrementedValue - True if this should use the
357 // post-incremented version of this IV, not the preincremented version.
358 // This can only be set in special cases, such as the terminating setcc
359 // instruction for a loop and uses outside the loop that are dominated by
361 bool isUseOfPostIncrementedValue;
363 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
364 : SE(se), Base(IVSU.getOffset()), Inst(IVSU.getUser()),
365 OperandValToReplace(IVSU.getOperandValToReplace()),
366 isSigned(IVSU.isSigned()),
367 Imm(SE->getIntegerSCEV(0, Base->getType())),
368 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue()) {}
370 // Once we rewrite the code to insert the new IVs we want, update the
371 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
373 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
374 Instruction *InsertPt,
375 SCEVExpander &Rewriter, Loop *L, Pass *P,
377 SmallVectorImpl<WeakVH> &DeadInsts);
379 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
381 SCEVExpander &Rewriter,
382 Instruction *IP, Loop *L,
388 void BasedUser::dump() const {
389 cerr << " Base=" << *Base;
390 cerr << " Imm=" << *Imm;
391 cerr << " Inst: " << *Inst;
394 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
396 SCEVExpander &Rewriter,
397 Instruction *IP, Loop *L,
399 // Figure out where we *really* want to insert this code. In particular, if
400 // the user is inside of a loop that is nested inside of L, we really don't
401 // want to insert this expression before the user, we'd rather pull it out as
402 // many loops as possible.
403 Instruction *BaseInsertPt = IP;
405 // Figure out the most-nested loop that IP is in.
406 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
408 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
409 // the preheader of the outer-most loop where NewBase is not loop invariant.
410 if (L->contains(IP->getParent()))
411 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
412 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
413 InsertLoop = InsertLoop->getParentLoop();
416 Value *Base = Rewriter.expandCodeFor(NewBase, 0, BaseInsertPt);
418 SCEVHandle NewValSCEV = SE->getUnknown(Base);
420 // If there is no immediate value, skip the next part.
421 if (!Imm->isZero()) {
422 // If we are inserting the base and imm values in the same block, make sure
423 // to adjust the IP position if insertion reused a result.
424 if (IP == BaseInsertPt)
425 IP = Rewriter.getInsertionPoint();
427 // Always emit the immediate (if non-zero) into the same block as the user.
428 NewValSCEV = SE->getAddExpr(NewValSCEV, Imm);
432 NewValSCEV = SE->getTruncateOrSignExtend(NewValSCEV, Ty);
434 NewValSCEV = SE->getTruncateOrZeroExtend(NewValSCEV, Ty);
436 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
440 // Once we rewrite the code to insert the new IVs we want, update the
441 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
442 // to it. NewBasePt is the last instruction which contributes to the
443 // value of NewBase in the case that it's a diffferent instruction from
444 // the PHI that NewBase is computed from, or null otherwise.
446 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
447 Instruction *NewBasePt,
448 SCEVExpander &Rewriter, Loop *L, Pass *P,
450 SmallVectorImpl<WeakVH> &DeadInsts) {
451 if (!isa<PHINode>(Inst)) {
452 // By default, insert code at the user instruction.
453 BasicBlock::iterator InsertPt = Inst;
455 // However, if the Operand is itself an instruction, the (potentially
456 // complex) inserted code may be shared by many users. Because of this, we
457 // want to emit code for the computation of the operand right before its old
458 // computation. This is usually safe, because we obviously used to use the
459 // computation when it was computed in its current block. However, in some
460 // cases (e.g. use of a post-incremented induction variable) the NewBase
461 // value will be pinned to live somewhere after the original computation.
462 // In this case, we have to back off.
464 // If this is a use outside the loop (which means after, since it is based
465 // on a loop indvar) we use the post-incremented value, so that we don't
466 // artificially make the preinc value live out the bottom of the loop.
467 if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
468 if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
469 InsertPt = NewBasePt;
471 } else if (Instruction *OpInst
472 = dyn_cast<Instruction>(OperandValToReplace)) {
474 while (isa<PHINode>(InsertPt)) ++InsertPt;
477 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
478 OperandValToReplace->getType(),
479 Rewriter, InsertPt, L, LI);
480 // Replace the use of the operand Value with the new Phi we just created.
481 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
483 DOUT << " Replacing with ";
484 DEBUG(WriteAsOperand(*DOUT, NewVal, /*PrintType=*/false));
485 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
489 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
490 // expression into each operand block that uses it. Note that PHI nodes can
491 // have multiple entries for the same predecessor. We use a map to make sure
492 // that a PHI node only has a single Value* for each predecessor (which also
493 // prevents us from inserting duplicate code in some blocks).
494 DenseMap<BasicBlock*, Value*> InsertedCode;
495 PHINode *PN = cast<PHINode>(Inst);
496 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
497 if (PN->getIncomingValue(i) == OperandValToReplace) {
498 // If the original expression is outside the loop, put the replacement
499 // code in the same place as the original expression,
500 // which need not be an immediate predecessor of this PHI. This way we
501 // need only one copy of it even if it is referenced multiple times in
502 // the PHI. We don't do this when the original expression is inside the
503 // loop because multiple copies sometimes do useful sinking of code in
505 Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
506 if (L->contains(OldLoc->getParent())) {
507 // If this is a critical edge, split the edge so that we do not insert
508 // the code on all predecessor/successor paths. We do this unless this
509 // is the canonical backedge for this loop, as this can make some
510 // inserted code be in an illegal position.
511 BasicBlock *PHIPred = PN->getIncomingBlock(i);
512 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
513 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
515 // First step, split the critical edge.
516 SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
518 // Next step: move the basic block. In particular, if the PHI node
519 // is outside of the loop, and PredTI is in the loop, we want to
520 // move the block to be immediately before the PHI block, not
521 // immediately after PredTI.
522 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
523 BasicBlock *NewBB = PN->getIncomingBlock(i);
524 NewBB->moveBefore(PN->getParent());
527 // Splitting the edge can reduce the number of PHI entries we have.
528 e = PN->getNumIncomingValues();
531 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
533 // Insert the code into the end of the predecessor block.
534 Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
535 PN->getIncomingBlock(i)->getTerminator() :
536 OldLoc->getParent()->getTerminator();
537 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
538 Rewriter, InsertPt, L, LI);
540 DOUT << " Changing PHI use to ";
541 DEBUG(WriteAsOperand(*DOUT, Code, /*PrintType=*/false));
542 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
545 // Replace the use of the operand Value with the new Phi we just created.
546 PN->setIncomingValue(i, Code);
551 // PHI node might have become a constant value after SplitCriticalEdge.
552 DeadInsts.push_back(Inst);
556 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
557 /// mode, and does not need to be put in a register first.
558 static bool fitsInAddressMode(const SCEVHandle &V, const Type *AccessTy,
559 const TargetLowering *TLI, bool HasBaseReg) {
560 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
561 int64_t VC = SC->getValue()->getSExtValue();
563 TargetLowering::AddrMode AM;
565 AM.HasBaseReg = HasBaseReg;
566 return TLI->isLegalAddressingMode(AM, AccessTy);
568 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
569 return (VC > -(1 << 16) && VC < (1 << 16)-1);
573 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
574 if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
576 TargetLowering::AddrMode AM;
578 AM.HasBaseReg = HasBaseReg;
579 return TLI->isLegalAddressingMode(AM, AccessTy);
581 // Default: assume global addresses are not legal.
588 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
589 /// loop varying to the Imm operand.
590 static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
591 Loop *L, ScalarEvolution *SE) {
592 if (Val->isLoopInvariant(L)) return; // Nothing to do.
594 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
595 std::vector<SCEVHandle> NewOps;
596 NewOps.reserve(SAE->getNumOperands());
598 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
599 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
600 // If this is a loop-variant expression, it must stay in the immediate
601 // field of the expression.
602 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
604 NewOps.push_back(SAE->getOperand(i));
608 Val = SE->getIntegerSCEV(0, Val->getType());
610 Val = SE->getAddExpr(NewOps);
611 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
612 // Try to pull immediates out of the start value of nested addrec's.
613 SCEVHandle Start = SARE->getStart();
614 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
616 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
618 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
620 // Otherwise, all of Val is variant, move the whole thing over.
621 Imm = SE->getAddExpr(Imm, Val);
622 Val = SE->getIntegerSCEV(0, Val->getType());
627 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
628 /// that can fit into the immediate field of instructions in the target.
629 /// Accumulate these immediate values into the Imm value.
630 static void MoveImmediateValues(const TargetLowering *TLI,
631 const Type *AccessTy,
632 SCEVHandle &Val, SCEVHandle &Imm,
633 bool isAddress, Loop *L,
634 ScalarEvolution *SE) {
635 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
636 std::vector<SCEVHandle> NewOps;
637 NewOps.reserve(SAE->getNumOperands());
639 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
640 SCEVHandle NewOp = SAE->getOperand(i);
641 MoveImmediateValues(TLI, AccessTy, NewOp, Imm, isAddress, L, SE);
643 if (!NewOp->isLoopInvariant(L)) {
644 // If this is a loop-variant expression, it must stay in the immediate
645 // field of the expression.
646 Imm = SE->getAddExpr(Imm, NewOp);
648 NewOps.push_back(NewOp);
653 Val = SE->getIntegerSCEV(0, Val->getType());
655 Val = SE->getAddExpr(NewOps);
657 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
658 // Try to pull immediates out of the start value of nested addrec's.
659 SCEVHandle Start = SARE->getStart();
660 MoveImmediateValues(TLI, AccessTy, Start, Imm, isAddress, L, SE);
662 if (Start != SARE->getStart()) {
663 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
665 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
668 } else if (const SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
669 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
671 fitsInAddressMode(SME->getOperand(0), AccessTy, TLI, false) &&
672 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
674 SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
675 SCEVHandle NewOp = SME->getOperand(1);
676 MoveImmediateValues(TLI, AccessTy, NewOp, SubImm, isAddress, L, SE);
678 // If we extracted something out of the subexpressions, see if we can
680 if (NewOp != SME->getOperand(1)) {
681 // Scale SubImm up by "8". If the result is a target constant, we are
683 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
684 if (fitsInAddressMode(SubImm, AccessTy, TLI, false)) {
685 // Accumulate the immediate.
686 Imm = SE->getAddExpr(Imm, SubImm);
688 // Update what is left of 'Val'.
689 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
696 // Loop-variant expressions must stay in the immediate field of the
698 if ((isAddress && fitsInAddressMode(Val, AccessTy, TLI, false)) ||
699 !Val->isLoopInvariant(L)) {
700 Imm = SE->getAddExpr(Imm, Val);
701 Val = SE->getIntegerSCEV(0, Val->getType());
705 // Otherwise, no immediates to move.
708 static void MoveImmediateValues(const TargetLowering *TLI,
710 SCEVHandle &Val, SCEVHandle &Imm,
711 bool isAddress, Loop *L,
712 ScalarEvolution *SE) {
713 const Type *AccessTy = getAccessType(User);
714 MoveImmediateValues(TLI, AccessTy, Val, Imm, isAddress, L, SE);
717 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
718 /// added together. This is used to reassociate common addition subexprs
719 /// together for maximal sharing when rewriting bases.
720 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
722 ScalarEvolution *SE) {
723 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
724 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
725 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
726 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
727 SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
728 if (SARE->getOperand(0) == Zero) {
729 SubExprs.push_back(Expr);
731 // Compute the addrec with zero as its base.
732 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
733 Ops[0] = Zero; // Start with zero base.
734 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
737 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
739 } else if (!Expr->isZero()) {
741 SubExprs.push_back(Expr);
745 // This is logically local to the following function, but C++ says we have
746 // to make it file scope.
747 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
749 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
750 /// the Uses, removing any common subexpressions, except that if all such
751 /// subexpressions can be folded into an addressing mode for all uses inside
752 /// the loop (this case is referred to as "free" in comments herein) we do
753 /// not remove anything. This looks for things like (a+b+c) and
754 /// (a+c+d) and computes the common (a+c) subexpression. The common expression
755 /// is *removed* from the Bases and returned.
757 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
758 ScalarEvolution *SE, Loop *L,
759 const TargetLowering *TLI) {
760 unsigned NumUses = Uses.size();
762 // Only one use? This is a very common case, so we handle it specially and
764 SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
765 SCEVHandle Result = Zero;
766 SCEVHandle FreeResult = Zero;
768 // If the use is inside the loop, use its base, regardless of what it is:
769 // it is clearly shared across all the IV's. If the use is outside the loop
770 // (which means after it) we don't want to factor anything *into* the loop,
771 // so just use 0 as the base.
772 if (L->contains(Uses[0].Inst->getParent()))
773 std::swap(Result, Uses[0].Base);
777 // To find common subexpressions, count how many of Uses use each expression.
778 // If any subexpressions are used Uses.size() times, they are common.
779 // Also track whether all uses of each expression can be moved into an
780 // an addressing mode "for free"; such expressions are left within the loop.
781 // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
782 std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
784 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
785 // order we see them.
786 std::vector<SCEVHandle> UniqueSubExprs;
788 std::vector<SCEVHandle> SubExprs;
789 unsigned NumUsesInsideLoop = 0;
790 for (unsigned i = 0; i != NumUses; ++i) {
791 // If the user is outside the loop, just ignore it for base computation.
792 // Since the user is outside the loop, it must be *after* the loop (if it
793 // were before, it could not be based on the loop IV). We don't want users
794 // after the loop to affect base computation of values *inside* the loop,
795 // because we can always add their offsets to the result IV after the loop
796 // is done, ensuring we get good code inside the loop.
797 if (!L->contains(Uses[i].Inst->getParent()))
801 // If the base is zero (which is common), return zero now, there are no
803 if (Uses[i].Base == Zero) return Zero;
805 // If this use is as an address we may be able to put CSEs in the addressing
806 // mode rather than hoisting them.
807 bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
808 // We may need the AccessTy below, but only when isAddrUse, so compute it
809 // only in that case.
810 const Type *AccessTy = 0;
812 AccessTy = getAccessType(Uses[i].Inst);
814 // Split the expression into subexprs.
815 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
816 // Add one to SubExpressionUseData.Count for each subexpr present, and
817 // if the subexpr is not a valid immediate within an addressing mode use,
818 // set SubExpressionUseData.notAllUsesAreFree. We definitely want to
819 // hoist these out of the loop (if they are common to all uses).
820 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
821 if (++SubExpressionUseData[SubExprs[j]].Count == 1)
822 UniqueSubExprs.push_back(SubExprs[j]);
823 if (!isAddrUse || !fitsInAddressMode(SubExprs[j], AccessTy, TLI, false))
824 SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
829 // Now that we know how many times each is used, build Result. Iterate over
830 // UniqueSubexprs so that we have a stable ordering.
831 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
832 std::map<SCEVHandle, SubExprUseData>::iterator I =
833 SubExpressionUseData.find(UniqueSubExprs[i]);
834 assert(I != SubExpressionUseData.end() && "Entry not found?");
835 if (I->second.Count == NumUsesInsideLoop) { // Found CSE!
836 if (I->second.notAllUsesAreFree)
837 Result = SE->getAddExpr(Result, I->first);
839 FreeResult = SE->getAddExpr(FreeResult, I->first);
841 // Remove non-cse's from SubExpressionUseData.
842 SubExpressionUseData.erase(I);
845 if (FreeResult != Zero) {
846 // We have some subexpressions that can be subsumed into addressing
847 // modes in every use inside the loop. However, it's possible that
848 // there are so many of them that the combined FreeResult cannot
849 // be subsumed, or that the target cannot handle both a FreeResult
850 // and a Result in the same instruction (for example because it would
851 // require too many registers). Check this.
852 for (unsigned i=0; i<NumUses; ++i) {
853 if (!L->contains(Uses[i].Inst->getParent()))
855 // We know this is an addressing mode use; if there are any uses that
856 // are not, FreeResult would be Zero.
857 const Type *AccessTy = getAccessType(Uses[i].Inst);
858 if (!fitsInAddressMode(FreeResult, AccessTy, TLI, Result!=Zero)) {
859 // FIXME: could split up FreeResult into pieces here, some hoisted
860 // and some not. There is no obvious advantage to this.
861 Result = SE->getAddExpr(Result, FreeResult);
868 // If we found no CSE's, return now.
869 if (Result == Zero) return Result;
871 // If we still have a FreeResult, remove its subexpressions from
872 // SubExpressionUseData. This means they will remain in the use Bases.
873 if (FreeResult != Zero) {
874 SeparateSubExprs(SubExprs, FreeResult, SE);
875 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
876 std::map<SCEVHandle, SubExprUseData>::iterator I =
877 SubExpressionUseData.find(SubExprs[j]);
878 SubExpressionUseData.erase(I);
883 // Otherwise, remove all of the CSE's we found from each of the base values.
884 for (unsigned i = 0; i != NumUses; ++i) {
885 // Uses outside the loop don't necessarily include the common base, but
886 // the final IV value coming into those uses does. Instead of trying to
887 // remove the pieces of the common base, which might not be there,
888 // subtract off the base to compensate for this.
889 if (!L->contains(Uses[i].Inst->getParent())) {
890 Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
894 // Split the expression into subexprs.
895 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
897 // Remove any common subexpressions.
898 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
899 if (SubExpressionUseData.count(SubExprs[j])) {
900 SubExprs.erase(SubExprs.begin()+j);
904 // Finally, add the non-shared expressions together.
905 if (SubExprs.empty())
908 Uses[i].Base = SE->getAddExpr(SubExprs);
915 /// ValidScale - Check whether the given Scale is valid for all loads and
916 /// stores in UsersToProcess.
918 bool LoopStrengthReduce::ValidScale(bool HasBaseReg, int64_t Scale,
919 const std::vector<BasedUser>& UsersToProcess) {
923 for (unsigned i = 0, e = UsersToProcess.size(); i!=e; ++i) {
924 // If this is a load or other access, pass the type of the access in.
925 const Type *AccessTy = Type::VoidTy;
926 if (isAddressUse(UsersToProcess[i].Inst,
927 UsersToProcess[i].OperandValToReplace))
928 AccessTy = getAccessType(UsersToProcess[i].Inst);
929 else if (isa<PHINode>(UsersToProcess[i].Inst))
932 TargetLowering::AddrMode AM;
933 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
934 AM.BaseOffs = SC->getValue()->getSExtValue();
935 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
938 // If load[imm+r*scale] is illegal, bail out.
939 if (!TLI->isLegalAddressingMode(AM, AccessTy))
945 /// ValidOffset - Check whether the given Offset is valid for all loads and
946 /// stores in UsersToProcess.
948 bool LoopStrengthReduce::ValidOffset(bool HasBaseReg,
951 const std::vector<BasedUser>& UsersToProcess) {
955 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
956 // If this is a load or other access, pass the type of the access in.
957 const Type *AccessTy = Type::VoidTy;
958 if (isAddressUse(UsersToProcess[i].Inst,
959 UsersToProcess[i].OperandValToReplace))
960 AccessTy = getAccessType(UsersToProcess[i].Inst);
961 else if (isa<PHINode>(UsersToProcess[i].Inst))
964 TargetLowering::AddrMode AM;
965 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
966 AM.BaseOffs = SC->getValue()->getSExtValue();
967 AM.BaseOffs = (uint64_t)AM.BaseOffs + (uint64_t)Offset;
968 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
971 // If load[imm+r*scale] is illegal, bail out.
972 if (!TLI->isLegalAddressingMode(AM, AccessTy))
978 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
980 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
984 Ty1 = SE->getEffectiveSCEVType(Ty1);
985 Ty2 = SE->getEffectiveSCEVType(Ty2);
988 if (Ty1->canLosslesslyBitCastTo(Ty2))
990 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
995 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
996 /// of a previous stride and it is a legal value for the target addressing
997 /// mode scale component and optional base reg. This allows the users of
998 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
999 /// reuse is possible. Factors can be negative on same targets, e.g. ARM.
1001 /// If all uses are outside the loop, we don't require that all multiplies
1002 /// be folded into the addressing mode, nor even that the factor be constant;
1003 /// a multiply (executed once) outside the loop is better than another IV
1004 /// within. Well, usually.
1005 SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
1006 bool AllUsesAreAddresses,
1007 bool AllUsesAreOutsideLoop,
1008 const SCEVHandle &Stride,
1009 IVExpr &IV, const Type *Ty,
1010 const std::vector<BasedUser>& UsersToProcess) {
1011 if (StrideNoReuse.count(Stride))
1012 return SE->getIntegerSCEV(0, Stride->getType());
1014 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
1015 int64_t SInt = SC->getValue()->getSExtValue();
1016 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1017 NewStride != e; ++NewStride) {
1018 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1019 IVsByStride.find(IU->StrideOrder[NewStride]);
1020 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first) ||
1021 StrideNoReuse.count(SI->first))
1023 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1024 if (SI->first != Stride &&
1025 (unsigned(abs64(SInt)) < SSInt || (SInt % SSInt) != 0))
1027 int64_t Scale = SInt / SSInt;
1028 // Check that this stride is valid for all the types used for loads and
1029 // stores; if it can be used for some and not others, we might as well use
1030 // the original stride everywhere, since we have to create the IV for it
1031 // anyway. If the scale is 1, then we don't need to worry about folding
1034 (AllUsesAreAddresses &&
1035 ValidScale(HasBaseReg, Scale, UsersToProcess))) {
1036 // Prefer to reuse an IV with a base of zero.
1037 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1038 IE = SI->second.IVs.end(); II != IE; ++II)
1039 // Only reuse previous IV if it would not require a type conversion
1040 // and if the base difference can be folded.
1041 if (II->Base->isZero() &&
1042 !RequiresTypeConversion(II->Base->getType(), Ty)) {
1044 return SE->getIntegerSCEV(Scale, Stride->getType());
1046 // Otherwise, settle for an IV with a foldable base.
1047 if (AllUsesAreAddresses)
1048 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1049 IE = SI->second.IVs.end(); II != IE; ++II)
1050 // Only reuse previous IV if it would not require a type conversion
1051 // and if the base difference can be folded.
1052 if (SE->getEffectiveSCEVType(II->Base->getType()) ==
1053 SE->getEffectiveSCEVType(Ty) &&
1054 isa<SCEVConstant>(II->Base)) {
1056 cast<SCEVConstant>(II->Base)->getValue()->getSExtValue();
1057 if (Base > INT32_MIN && Base <= INT32_MAX &&
1058 ValidOffset(HasBaseReg, -Base * Scale,
1059 Scale, UsersToProcess)) {
1061 return SE->getIntegerSCEV(Scale, Stride->getType());
1066 } else if (AllUsesAreOutsideLoop) {
1067 // Accept nonconstant strides here; it is really really right to substitute
1068 // an existing IV if we can.
1069 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1070 NewStride != e; ++NewStride) {
1071 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1072 IVsByStride.find(IU->StrideOrder[NewStride]);
1073 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1075 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1076 if (SI->first != Stride && SSInt != 1)
1078 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1079 IE = SI->second.IVs.end(); II != IE; ++II)
1080 // Accept nonzero base here.
1081 // Only reuse previous IV if it would not require a type conversion.
1082 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1087 // Special case, old IV is -1*x and this one is x. Can treat this one as
1089 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1090 NewStride != e; ++NewStride) {
1091 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1092 IVsByStride.find(IU->StrideOrder[NewStride]);
1093 if (SI == IVsByStride.end())
1095 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1096 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
1097 if (Stride == ME->getOperand(1) &&
1098 SC->getValue()->getSExtValue() == -1LL)
1099 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1100 IE = SI->second.IVs.end(); II != IE; ++II)
1101 // Accept nonzero base here.
1102 // Only reuse previous IV if it would not require type conversion.
1103 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1105 return SE->getIntegerSCEV(-1LL, Stride->getType());
1109 return SE->getIntegerSCEV(0, Stride->getType());
1112 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1113 /// returns true if Val's isUseOfPostIncrementedValue is true.
1114 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1115 return Val.isUseOfPostIncrementedValue;
1118 /// isNonConstantNegative - Return true if the specified scev is negated, but
1120 static bool isNonConstantNegative(const SCEVHandle &Expr) {
1121 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1122 if (!Mul) return false;
1124 // If there is a constant factor, it will be first.
1125 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1126 if (!SC) return false;
1128 // Return true if the value is negative, this matches things like (-42 * V).
1129 return SC->getValue()->getValue().isNegative();
1132 // CollectIVUsers - Transform our list of users and offsets to a bit more
1133 // complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1134 // of the strided accesses, as well as the old information from Uses. We
1135 // progressively move information from the Base field to the Imm field, until
1136 // we eventually have the full access expression to rewrite the use.
1137 SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1138 IVUsersOfOneStride &Uses,
1140 bool &AllUsesAreAddresses,
1141 bool &AllUsesAreOutsideLoop,
1142 std::vector<BasedUser> &UsersToProcess) {
1143 // FIXME: Generalize to non-affine IV's.
1144 if (!Stride->isLoopInvariant(L))
1145 return SE->getIntegerSCEV(0, Stride->getType());
1147 UsersToProcess.reserve(Uses.Users.size());
1148 for (ilist<IVStrideUse>::iterator I = Uses.Users.begin(),
1149 E = Uses.Users.end(); I != E; ++I) {
1150 UsersToProcess.push_back(BasedUser(*I, SE));
1152 // Move any loop variant operands from the offset field to the immediate
1153 // field of the use, so that we don't try to use something before it is
1155 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1156 UsersToProcess.back().Imm, L, SE);
1157 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1158 "Base value is not loop invariant!");
1161 // We now have a whole bunch of uses of like-strided induction variables, but
1162 // they might all have different bases. We want to emit one PHI node for this
1163 // stride which we fold as many common expressions (between the IVs) into as
1164 // possible. Start by identifying the common expressions in the base values
1165 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1166 // "A+B"), emit it to the preheader, then remove the expression from the
1167 // UsersToProcess base values.
1168 SCEVHandle CommonExprs =
1169 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1171 // Next, figure out what we can represent in the immediate fields of
1172 // instructions. If we can represent anything there, move it to the imm
1173 // fields of the BasedUsers. We do this so that it increases the commonality
1174 // of the remaining uses.
1175 unsigned NumPHI = 0;
1176 bool HasAddress = false;
1177 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1178 // If the user is not in the current loop, this means it is using the exit
1179 // value of the IV. Do not put anything in the base, make sure it's all in
1180 // the immediate field to allow as much factoring as possible.
1181 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1182 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1183 UsersToProcess[i].Base);
1184 UsersToProcess[i].Base =
1185 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1187 // Not all uses are outside the loop.
1188 AllUsesAreOutsideLoop = false;
1190 // Addressing modes can be folded into loads and stores. Be careful that
1191 // the store is through the expression, not of the expression though.
1193 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1194 UsersToProcess[i].OperandValToReplace);
1195 if (isa<PHINode>(UsersToProcess[i].Inst)) {
1203 // If this use isn't an address, then not all uses are addresses.
1204 if (!isAddress && !isPHI)
1205 AllUsesAreAddresses = false;
1207 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1208 UsersToProcess[i].Imm, isAddress, L, SE);
1212 // If one of the use is a PHI node and all other uses are addresses, still
1213 // allow iv reuse. Essentially we are trading one constant multiplication
1214 // for one fewer iv.
1216 AllUsesAreAddresses = false;
1218 // There are no in-loop address uses.
1219 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1220 AllUsesAreAddresses = false;
1225 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1226 /// is valid and profitable for the given set of users of a stride. In
1227 /// full strength-reduction mode, all addresses at the current stride are
1228 /// strength-reduced all the way down to pointer arithmetic.
1230 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1231 const std::vector<BasedUser> &UsersToProcess,
1233 bool AllUsesAreAddresses,
1234 SCEVHandle Stride) {
1235 if (!EnableFullLSRMode)
1238 // The heuristics below aim to avoid increasing register pressure, but
1239 // fully strength-reducing all the addresses increases the number of
1240 // add instructions, so don't do this when optimizing for size.
1241 // TODO: If the loop is large, the savings due to simpler addresses
1242 // may oughtweight the costs of the extra increment instructions.
1243 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1246 // TODO: For now, don't do full strength reduction if there could
1247 // potentially be greater-stride multiples of the current stride
1248 // which could reuse the current stride IV.
1249 if (IU->StrideOrder.back() != Stride)
1252 // Iterate through the uses to find conditions that automatically rule out
1254 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1255 const SCEV *Base = UsersToProcess[i].Base;
1256 const SCEV *Imm = UsersToProcess[i].Imm;
1257 // If any users have a loop-variant component, they can't be fully
1258 // strength-reduced.
1259 if (Imm && !Imm->isLoopInvariant(L))
1261 // If there are to users with the same base and the difference between
1262 // the two Imm values can't be folded into the address, full
1263 // strength reduction would increase register pressure.
1265 const SCEV *CurImm = UsersToProcess[i].Imm;
1266 if ((CurImm || Imm) && CurImm != Imm) {
1267 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1268 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1269 const Instruction *Inst = UsersToProcess[i].Inst;
1270 const Type *AccessTy = getAccessType(Inst);
1271 SCEVHandle Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1272 if (!Diff->isZero() &&
1273 (!AllUsesAreAddresses ||
1274 !fitsInAddressMode(Diff, AccessTy, TLI, /*HasBaseReg=*/true)))
1277 } while (++i != e && Base == UsersToProcess[i].Base);
1280 // If there's exactly one user in this stride, fully strength-reducing it
1281 // won't increase register pressure. If it's starting from a non-zero base,
1282 // it'll be simpler this way.
1283 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1286 // Otherwise, if there are any users in this stride that don't require
1287 // a register for their base, full strength-reduction will increase
1288 // register pressure.
1289 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1290 if (UsersToProcess[i].Base->isZero())
1293 // Otherwise, go for it.
1297 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1298 /// with the specified start and step values in the specified loop.
1300 /// If NegateStride is true, the stride should be negated by using a
1301 /// subtract instead of an add.
1303 /// Return the created phi node.
1305 static PHINode *InsertAffinePhi(SCEVHandle Start, SCEVHandle Step,
1306 Instruction *IVIncInsertPt,
1308 SCEVExpander &Rewriter) {
1309 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1310 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1312 BasicBlock *Header = L->getHeader();
1313 BasicBlock *Preheader = L->getLoopPreheader();
1314 BasicBlock *LatchBlock = L->getLoopLatch();
1315 const Type *Ty = Start->getType();
1316 Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
1318 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1319 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1322 // If the stride is negative, insert a sub instead of an add for the
1324 bool isNegative = isNonConstantNegative(Step);
1325 SCEVHandle IncAmount = Step;
1327 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1329 // Insert an add instruction right before the terminator corresponding
1330 // to the back-edge or just before the only use. The location is determined
1331 // by the caller and passed in as IVIncInsertPt.
1332 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1333 Preheader->getTerminator());
1336 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1339 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1342 if (!isa<ConstantInt>(StepV)) ++NumVariable;
1344 PN->addIncoming(IncV, LatchBlock);
1350 static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1351 // We want to emit code for users inside the loop first. To do this, we
1352 // rearrange BasedUser so that the entries at the end have
1353 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1354 // vector (so we handle them first).
1355 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1356 PartitionByIsUseOfPostIncrementedValue);
1358 // Sort this by base, so that things with the same base are handled
1359 // together. By partitioning first and stable-sorting later, we are
1360 // guaranteed that within each base we will pop off users from within the
1361 // loop before users outside of the loop with a particular base.
1363 // We would like to use stable_sort here, but we can't. The problem is that
1364 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1365 // we don't have anything to do a '<' comparison on. Because we think the
1366 // number of uses is small, do a horrible bubble sort which just relies on
1368 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1369 // Get a base value.
1370 SCEVHandle Base = UsersToProcess[i].Base;
1372 // Compact everything with this base to be consecutive with this one.
1373 for (unsigned j = i+1; j != e; ++j) {
1374 if (UsersToProcess[j].Base == Base) {
1375 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1382 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1383 /// UsersToProcess, meaning lowering addresses all the way down to direct
1384 /// pointer arithmetic.
1387 LoopStrengthReduce::PrepareToStrengthReduceFully(
1388 std::vector<BasedUser> &UsersToProcess,
1390 SCEVHandle CommonExprs,
1392 SCEVExpander &PreheaderRewriter) {
1393 DOUT << " Fully reducing all users\n";
1395 // Rewrite the UsersToProcess records, creating a separate PHI for each
1396 // unique Base value.
1397 Instruction *IVIncInsertPt = L->getLoopLatch()->getTerminator();
1398 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1399 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1400 // pick the first Imm value here to start with, and adjust it for the
1402 SCEVHandle Imm = UsersToProcess[i].Imm;
1403 SCEVHandle Base = UsersToProcess[i].Base;
1404 SCEVHandle Start = SE->getAddExpr(CommonExprs, Base, Imm);
1405 PHINode *Phi = InsertAffinePhi(Start, Stride, IVIncInsertPt, L,
1407 // Loop over all the users with the same base.
1409 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1410 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1411 UsersToProcess[i].Phi = Phi;
1412 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1413 "ShouldUseFullStrengthReductionMode should reject this!");
1414 } while (++i != e && Base == UsersToProcess[i].Base);
1418 /// FindIVIncInsertPt - Return the location to insert the increment instruction.
1419 /// If the only use if a use of postinc value, (must be the loop termination
1420 /// condition), then insert it just before the use.
1421 static Instruction *FindIVIncInsertPt(std::vector<BasedUser> &UsersToProcess,
1423 if (UsersToProcess.size() == 1 &&
1424 UsersToProcess[0].isUseOfPostIncrementedValue &&
1425 L->contains(UsersToProcess[0].Inst->getParent()))
1426 return UsersToProcess[0].Inst;
1427 return L->getLoopLatch()->getTerminator();
1430 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1431 /// given users to share.
1434 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1435 std::vector<BasedUser> &UsersToProcess,
1437 SCEVHandle CommonExprs,
1439 Instruction *IVIncInsertPt,
1441 SCEVExpander &PreheaderRewriter) {
1442 DOUT << " Inserting new PHI:\n";
1444 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1445 Stride, IVIncInsertPt, L,
1448 // Remember this in case a later stride is multiple of this.
1449 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1451 // All the users will share this new IV.
1452 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1453 UsersToProcess[i].Phi = Phi;
1456 DEBUG(WriteAsOperand(*DOUT, Phi, /*PrintType=*/false));
1460 /// PrepareToStrengthReduceFromSmallerStride - Prepare for the given users to
1461 /// reuse an induction variable with a stride that is a factor of the current
1462 /// induction variable.
1465 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1466 std::vector<BasedUser> &UsersToProcess,
1468 const IVExpr &ReuseIV,
1469 Instruction *PreInsertPt) {
1470 DOUT << " Rewriting in terms of existing IV of STRIDE " << *ReuseIV.Stride
1471 << " and BASE " << *ReuseIV.Base << "\n";
1473 // All the users will share the reused IV.
1474 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1475 UsersToProcess[i].Phi = ReuseIV.PHI;
1477 Constant *C = dyn_cast<Constant>(CommonBaseV);
1479 (!C->isNullValue() &&
1480 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1482 // We want the common base emitted into the preheader! This is just
1483 // using cast as a copy so BitCast (no-op cast) is appropriate
1484 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1485 "commonbase", PreInsertPt);
1488 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1489 const Type *AccessTy,
1490 std::vector<BasedUser> &UsersToProcess,
1491 const TargetLowering *TLI) {
1492 SmallVector<Instruction*, 16> AddrModeInsts;
1493 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1494 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1496 ExtAddrMode AddrMode =
1497 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1498 AccessTy, UsersToProcess[i].Inst,
1499 AddrModeInsts, *TLI);
1500 if (GV && GV != AddrMode.BaseGV)
1502 if (Offset && !AddrMode.BaseOffs)
1503 // FIXME: How to accurate check it's immediate offset is folded.
1505 AddrModeInsts.clear();
1510 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1511 /// stride of IV. All of the users may have different starting values, and this
1512 /// may not be the only stride.
1513 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1514 IVUsersOfOneStride &Uses,
1516 // If all the users are moved to another stride, then there is nothing to do.
1517 if (Uses.Users.empty())
1520 // Keep track if every use in UsersToProcess is an address. If they all are,
1521 // we may be able to rewrite the entire collection of them in terms of a
1522 // smaller-stride IV.
1523 bool AllUsesAreAddresses = true;
1525 // Keep track if every use of a single stride is outside the loop. If so,
1526 // we want to be more aggressive about reusing a smaller-stride IV; a
1527 // multiply outside the loop is better than another IV inside. Well, usually.
1528 bool AllUsesAreOutsideLoop = true;
1530 // Transform our list of users and offsets to a bit more complex table. In
1531 // this new vector, each 'BasedUser' contains 'Base' the base of the
1532 // strided accessas well as the old information from Uses. We progressively
1533 // move information from the Base field to the Imm field, until we eventually
1534 // have the full access expression to rewrite the use.
1535 std::vector<BasedUser> UsersToProcess;
1536 SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1537 AllUsesAreOutsideLoop,
1540 // Sort the UsersToProcess array so that users with common bases are
1541 // next to each other.
1542 SortUsersToProcess(UsersToProcess);
1544 // If we managed to find some expressions in common, we'll need to carry
1545 // their value in a register and add it in for each use. This will take up
1546 // a register operand, which potentially restricts what stride values are
1548 bool HaveCommonExprs = !CommonExprs->isZero();
1549 const Type *ReplacedTy = CommonExprs->getType();
1551 // If all uses are addresses, consider sinking the immediate part of the
1552 // common expression back into uses if they can fit in the immediate fields.
1553 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1554 SCEVHandle NewCommon = CommonExprs;
1555 SCEVHandle Imm = SE->getIntegerSCEV(0, ReplacedTy);
1556 MoveImmediateValues(TLI, Type::VoidTy, NewCommon, Imm, true, L, SE);
1557 if (!Imm->isZero()) {
1560 // If the immediate part of the common expression is a GV, check if it's
1561 // possible to fold it into the target addressing mode.
1562 GlobalValue *GV = 0;
1563 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
1564 GV = dyn_cast<GlobalValue>(SU->getValue());
1566 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
1567 Offset = SC->getValue()->getSExtValue();
1569 // Pass VoidTy as the AccessTy to be conservative, because
1570 // there could be multiple access types among all the uses.
1571 DoSink = IsImmFoldedIntoAddrMode(GV, Offset, Type::VoidTy,
1572 UsersToProcess, TLI);
1575 DOUT << " Sinking " << *Imm << " back down into uses\n";
1576 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1577 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1578 CommonExprs = NewCommon;
1579 HaveCommonExprs = !CommonExprs->isZero();
1585 // Now that we know what we need to do, insert the PHI node itself.
1587 DOUT << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1589 << " Common base: " << *CommonExprs << "\n";
1591 SCEVExpander Rewriter(*SE);
1592 SCEVExpander PreheaderRewriter(*SE);
1594 BasicBlock *Preheader = L->getLoopPreheader();
1595 Instruction *PreInsertPt = Preheader->getTerminator();
1596 BasicBlock *LatchBlock = L->getLoopLatch();
1597 Instruction *IVIncInsertPt = LatchBlock->getTerminator();
1599 Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
1601 SCEVHandle RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1602 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1603 SE->getIntegerSCEV(0, Type::Int32Ty),
1606 /// Choose a strength-reduction strategy and prepare for it by creating
1607 /// the necessary PHIs and adjusting the bookkeeping.
1608 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1609 AllUsesAreAddresses, Stride)) {
1610 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1613 // Emit the initial base value into the loop preheader.
1614 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1617 // If all uses are addresses, check if it is possible to reuse an IV. The
1618 // new IV must have a stride that is a multiple of the old stride; the
1619 // multiple must be a number that can be encoded in the scale field of the
1620 // target addressing mode; and we must have a valid instruction after this
1621 // substitution, including the immediate field, if any.
1622 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1623 AllUsesAreOutsideLoop,
1624 Stride, ReuseIV, ReplacedTy,
1626 if (!RewriteFactor->isZero())
1627 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1628 ReuseIV, PreInsertPt);
1630 IVIncInsertPt = FindIVIncInsertPt(UsersToProcess, L);
1631 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1632 CommonBaseV, IVIncInsertPt,
1633 L, PreheaderRewriter);
1637 // Process all the users now, replacing their strided uses with
1638 // strength-reduced forms. This outer loop handles all bases, the inner
1639 // loop handles all users of a particular base.
1640 while (!UsersToProcess.empty()) {
1641 SCEVHandle Base = UsersToProcess.back().Base;
1642 Instruction *Inst = UsersToProcess.back().Inst;
1644 // Emit the code for Base into the preheader.
1646 if (!Base->isZero()) {
1647 BaseV = PreheaderRewriter.expandCodeFor(Base, 0, PreInsertPt);
1649 DOUT << " INSERTING code for BASE = " << *Base << ":";
1650 if (BaseV->hasName())
1651 DOUT << " Result value name = %" << BaseV->getNameStr();
1654 // If BaseV is a non-zero constant, make sure that it gets inserted into
1655 // the preheader, instead of being forward substituted into the uses. We
1656 // do this by forcing a BitCast (noop cast) to be inserted into the
1657 // preheader in this case.
1658 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false)) {
1659 // We want this constant emitted into the preheader! This is just
1660 // using cast as a copy so BitCast (no-op cast) is appropriate
1661 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1666 // Emit the code to add the immediate offset to the Phi value, just before
1667 // the instructions that we identified as using this stride and base.
1669 // FIXME: Use emitted users to emit other users.
1670 BasedUser &User = UsersToProcess.back();
1672 DOUT << " Examining ";
1673 if (User.isUseOfPostIncrementedValue)
1678 DEBUG(WriteAsOperand(*DOUT, UsersToProcess.back().OperandValToReplace,
1679 /*PrintType=*/false));
1680 DOUT << " in Inst: " << *(User.Inst);
1682 // If this instruction wants to use the post-incremented value, move it
1683 // after the post-inc and use its value instead of the PHI.
1684 Value *RewriteOp = User.Phi;
1685 if (User.isUseOfPostIncrementedValue) {
1686 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1687 // If this user is in the loop, make sure it is the last thing in the
1688 // loop to ensure it is dominated by the increment. In case it's the
1689 // only use of the iv, the increment instruction is already before the
1691 if (L->contains(User.Inst->getParent()) && User.Inst != IVIncInsertPt)
1692 User.Inst->moveBefore(IVIncInsertPt);
1695 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
1697 if (SE->getEffectiveSCEVType(RewriteOp->getType()) !=
1698 SE->getEffectiveSCEVType(ReplacedTy)) {
1699 assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1700 SE->getTypeSizeInBits(ReplacedTy) &&
1701 "Unexpected widening cast!");
1702 RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1705 // If we had to insert new instructions for RewriteOp, we have to
1706 // consider that they may not have been able to end up immediately
1707 // next to RewriteOp, because non-PHI instructions may never precede
1708 // PHI instructions in a block. In this case, remember where the last
1709 // instruction was inserted so that if we're replacing a different
1710 // PHI node, we can use the later point to expand the final
1712 Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
1713 if (RewriteOp == User.Phi) NewBasePt = 0;
1715 // Clear the SCEVExpander's expression map so that we are guaranteed
1716 // to have the code emitted where we expect it.
1719 // If we are reusing the iv, then it must be multiplied by a constant
1720 // factor to take advantage of the addressing mode scale component.
1721 if (!RewriteFactor->isZero()) {
1722 // If we're reusing an IV with a nonzero base (currently this happens
1723 // only when all reuses are outside the loop) subtract that base here.
1724 // The base has been used to initialize the PHI node but we don't want
1726 if (!ReuseIV.Base->isZero()) {
1727 SCEVHandle typedBase = ReuseIV.Base;
1728 if (SE->getEffectiveSCEVType(RewriteExpr->getType()) !=
1729 SE->getEffectiveSCEVType(ReuseIV.Base->getType())) {
1730 // It's possible the original IV is a larger type than the new IV,
1731 // in which case we have to truncate the Base. We checked in
1732 // RequiresTypeConversion that this is valid.
1733 assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1734 SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
1735 "Unexpected lengthening conversion!");
1736 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1737 RewriteExpr->getType());
1739 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1742 // Multiply old variable, with base removed, by new scale factor.
1743 RewriteExpr = SE->getMulExpr(RewriteFactor,
1746 // The common base is emitted in the loop preheader. But since we
1747 // are reusing an IV, it has not been used to initialize the PHI node.
1748 // Add it to the expression used to rewrite the uses.
1749 // When this use is outside the loop, we earlier subtracted the
1750 // common base, and are adding it back here. Use the same expression
1751 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1752 if (!CommonExprs->isZero()) {
1753 if (L->contains(User.Inst->getParent()))
1754 RewriteExpr = SE->getAddExpr(RewriteExpr,
1755 SE->getUnknown(CommonBaseV));
1757 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1761 // Now that we know what we need to do, insert code before User for the
1762 // immediate and any loop-variant expressions.
1764 // Add BaseV to the PHI value if needed.
1765 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1767 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1768 Rewriter, L, this, *LI,
1771 // Mark old value we replaced as possibly dead, so that it is eliminated
1772 // if we just replaced the last use of that value.
1773 DeadInsts.push_back(User.OperandValToReplace);
1775 UsersToProcess.pop_back();
1778 // If there are any more users to process with the same base, process them
1779 // now. We sorted by base above, so we just have to check the last elt.
1780 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1781 // TODO: Next, find out which base index is the most common, pull it out.
1784 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1785 // different starting values, into different PHIs.
1788 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1789 /// set the IV user and stride information and return true, otherwise return
1791 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
1792 const SCEVHandle *&CondStride) {
1793 for (unsigned Stride = 0, e = IU->StrideOrder.size();
1794 Stride != e && !CondUse; ++Stride) {
1795 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
1796 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
1797 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
1799 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1800 E = SI->second->Users.end(); UI != E; ++UI)
1801 if (UI->getUser() == Cond) {
1802 // NOTE: we could handle setcc instructions with multiple uses here, but
1803 // InstCombine does it as well for simple uses, it's not clear that it
1804 // occurs enough in real life to handle.
1806 CondStride = &SI->first;
1814 // Constant strides come first which in turns are sorted by their absolute
1815 // values. If absolute values are the same, then positive strides comes first.
1817 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1818 struct StrideCompare {
1819 const ScalarEvolution *SE;
1820 explicit StrideCompare(const ScalarEvolution *se) : SE(se) {}
1822 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1823 const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1824 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1826 int64_t LV = LHSC->getValue()->getSExtValue();
1827 int64_t RV = RHSC->getValue()->getSExtValue();
1828 uint64_t ALV = (LV < 0) ? -LV : LV;
1829 uint64_t ARV = (RV < 0) ? -RV : RV;
1837 // If it's the same value but different type, sort by bit width so
1838 // that we emit larger induction variables before smaller
1839 // ones, letting the smaller be re-written in terms of larger ones.
1840 return SE->getTypeSizeInBits(RHS->getType()) <
1841 SE->getTypeSizeInBits(LHS->getType());
1843 return LHSC && !RHSC;
1848 /// ChangeCompareStride - If a loop termination compare instruction is the
1849 /// only use of its stride, and the compaison is against a constant value,
1850 /// try eliminate the stride by moving the compare instruction to another
1851 /// stride and change its constant operand accordingly. e.g.
1857 /// if (v2 < 10) goto loop
1862 /// if (v1 < 30) goto loop
1863 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
1864 IVStrideUse* &CondUse,
1865 const SCEVHandle* &CondStride) {
1866 // If there's only one stride in the loop, there's nothing to do here.
1867 if (IU->StrideOrder.size() < 2)
1869 // If there are other users of the condition's stride, don't bother
1870 // trying to change the condition because the stride will still
1872 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator I =
1873 IU->IVUsesByStride.find(*CondStride);
1874 if (I == IU->IVUsesByStride.end() ||
1875 I->second->Users.size() != 1)
1877 // Only handle constant strides for now.
1878 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
1879 if (!SC) return Cond;
1881 ICmpInst::Predicate Predicate = Cond->getPredicate();
1882 int64_t CmpSSInt = SC->getValue()->getSExtValue();
1883 unsigned BitWidth = SE->getTypeSizeInBits((*CondStride)->getType());
1884 uint64_t SignBit = 1ULL << (BitWidth-1);
1885 const Type *CmpTy = Cond->getOperand(0)->getType();
1886 const Type *NewCmpTy = NULL;
1887 unsigned TyBits = SE->getTypeSizeInBits(CmpTy);
1888 unsigned NewTyBits = 0;
1889 SCEVHandle *NewStride = NULL;
1890 Value *NewCmpLHS = NULL;
1891 Value *NewCmpRHS = NULL;
1893 SCEVHandle NewOffset = SE->getIntegerSCEV(0, CmpTy);
1895 if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
1896 int64_t CmpVal = C->getValue().getSExtValue();
1898 // Check stride constant and the comparision constant signs to detect
1900 if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
1903 // Look for a suitable stride / iv as replacement.
1904 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
1905 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
1906 IU->IVUsesByStride.find(IU->StrideOrder[i]);
1907 if (!isa<SCEVConstant>(SI->first))
1909 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1910 if (SSInt == CmpSSInt ||
1911 abs64(SSInt) < abs64(CmpSSInt) ||
1912 (SSInt % CmpSSInt) != 0)
1915 Scale = SSInt / CmpSSInt;
1916 int64_t NewCmpVal = CmpVal * Scale;
1917 APInt Mul = APInt(BitWidth*2, CmpVal, true);
1918 Mul = Mul * APInt(BitWidth*2, Scale, true);
1919 // Check for overflow.
1920 if (!Mul.isSignedIntN(BitWidth))
1922 // Check for overflow in the stride's type too.
1923 if (!Mul.isSignedIntN(SE->getTypeSizeInBits(SI->first->getType())))
1926 // Watch out for overflow.
1927 if (ICmpInst::isSignedPredicate(Predicate) &&
1928 (CmpVal & SignBit) != (NewCmpVal & SignBit))
1931 if (NewCmpVal == CmpVal)
1933 // Pick the best iv to use trying to avoid a cast.
1935 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1936 E = SI->second->Users.end(); UI != E; ++UI) {
1937 Value *Op = UI->getOperandValToReplace();
1939 // If the IVStrideUse implies a cast, check for an actual cast which
1940 // can be used to find the original IV expression.
1941 if (SE->getEffectiveSCEVType(Op->getType()) !=
1942 SE->getEffectiveSCEVType(SI->first->getType())) {
1943 CastInst *CI = dyn_cast<CastInst>(Op);
1944 // If it's not a simple cast, it's complicated.
1947 // If it's a cast from a type other than the stride type,
1948 // it's complicated.
1949 if (CI->getOperand(0)->getType() != SI->first->getType())
1951 // Ok, we found the IV expression in the stride's type.
1952 Op = CI->getOperand(0);
1956 if (NewCmpLHS->getType() == CmpTy)
1962 NewCmpTy = NewCmpLHS->getType();
1963 NewTyBits = SE->getTypeSizeInBits(NewCmpTy);
1964 const Type *NewCmpIntTy = IntegerType::get(NewTyBits);
1965 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
1966 // Check if it is possible to rewrite it using
1967 // an iv / stride of a smaller integer type.
1968 unsigned Bits = NewTyBits;
1969 if (ICmpInst::isSignedPredicate(Predicate))
1971 uint64_t Mask = (1ULL << Bits) - 1;
1972 if (((uint64_t)NewCmpVal & Mask) != (uint64_t)NewCmpVal)
1976 // Don't rewrite if use offset is non-constant and the new type is
1977 // of a different type.
1978 // FIXME: too conservative?
1979 if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->getOffset()))
1982 bool AllUsesAreAddresses = true;
1983 bool AllUsesAreOutsideLoop = true;
1984 std::vector<BasedUser> UsersToProcess;
1985 SCEVHandle CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
1986 AllUsesAreAddresses,
1987 AllUsesAreOutsideLoop,
1989 // Avoid rewriting the compare instruction with an iv of new stride
1990 // if it's likely the new stride uses will be rewritten using the
1991 // stride of the compare instruction.
1992 if (AllUsesAreAddresses &&
1993 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
1996 // Avoid rewriting the compare instruction with an iv which has
1997 // implicit extension or truncation built into it.
1998 // TODO: This is over-conservative.
1999 if (SE->getTypeSizeInBits(CondUse->getOffset()->getType()) != TyBits)
2002 // If scale is negative, use swapped predicate unless it's testing
2004 if (Scale < 0 && !Cond->isEquality())
2005 Predicate = ICmpInst::getSwappedPredicate(Predicate);
2007 NewStride = &IU->StrideOrder[i];
2008 if (!isa<PointerType>(NewCmpTy))
2009 NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
2011 ConstantInt *CI = ConstantInt::get(NewCmpIntTy, NewCmpVal);
2012 NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
2014 NewOffset = TyBits == NewTyBits
2015 ? SE->getMulExpr(CondUse->getOffset(),
2016 SE->getConstant(ConstantInt::get(CmpTy, Scale)))
2017 : SE->getConstant(ConstantInt::get(NewCmpIntTy,
2018 cast<SCEVConstant>(CondUse->getOffset())->getValue()
2019 ->getSExtValue()*Scale));
2024 // Forgo this transformation if it the increment happens to be
2025 // unfortunately positioned after the condition, and the condition
2026 // has multiple uses which prevent it from being moved immediately
2027 // before the branch. See
2028 // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2029 // for an example of this situation.
2030 if (!Cond->hasOneUse()) {
2031 for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2038 // Create a new compare instruction using new stride / iv.
2039 ICmpInst *OldCond = Cond;
2040 // Insert new compare instruction.
2041 Cond = new ICmpInst(Predicate, NewCmpLHS, NewCmpRHS,
2042 L->getHeader()->getName() + ".termcond",
2045 // Remove the old compare instruction. The old indvar is probably dead too.
2046 DeadInsts.push_back(CondUse->getOperandValToReplace());
2047 OldCond->replaceAllUsesWith(Cond);
2048 OldCond->eraseFromParent();
2050 IU->IVUsesByStride[*NewStride]->addUser(NewOffset, Cond, NewCmpLHS, false);
2051 CondUse = &IU->IVUsesByStride[*NewStride]->Users.back();
2052 CondStride = NewStride;
2060 /// OptimizeSMax - Rewrite the loop's terminating condition if it uses
2061 /// an smax computation.
2063 /// This is a narrow solution to a specific, but acute, problem. For loops
2069 /// } while (++i < n);
2071 /// where the comparison is signed, the trip count isn't just 'n', because
2072 /// 'n' could be negative. And unfortunately this can come up even for loops
2073 /// where the user didn't use a C do-while loop. For example, seemingly
2074 /// well-behaved top-test loops will commonly be lowered like this:
2080 /// } while (++i < n);
2083 /// and then it's possible for subsequent optimization to obscure the if
2084 /// test in such a way that indvars can't find it.
2086 /// When indvars can't find the if test in loops like this, it creates a
2087 /// signed-max expression, which allows it to give the loop a canonical
2088 /// induction variable:
2091 /// smax = n < 1 ? 1 : n;
2094 /// } while (++i != smax);
2096 /// Canonical induction variables are necessary because the loop passes
2097 /// are designed around them. The most obvious example of this is the
2098 /// LoopInfo analysis, which doesn't remember trip count values. It
2099 /// expects to be able to rediscover the trip count each time it is
2100 /// needed, and it does this using a simple analyis that only succeeds if
2101 /// the loop has a canonical induction variable.
2103 /// However, when it comes time to generate code, the maximum operation
2104 /// can be quite costly, especially if it's inside of an outer loop.
2106 /// This function solves this problem by detecting this type of loop and
2107 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2108 /// the instructions for the maximum computation.
2110 ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
2111 IVStrideUse* &CondUse) {
2112 // Check that the loop matches the pattern we're looking for.
2113 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2114 Cond->getPredicate() != CmpInst::ICMP_NE)
2117 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2118 if (!Sel || !Sel->hasOneUse()) return Cond;
2120 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2121 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2123 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2125 // Add one to the backedge-taken count to get the trip count.
2126 SCEVHandle IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
2128 // Check for a max calculation that matches the pattern.
2129 const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
2130 if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
2132 SCEVHandle SMaxLHS = SMax->getOperand(0);
2133 SCEVHandle SMaxRHS = SMax->getOperand(1);
2134 if (!SMaxLHS || SMaxLHS != One) return Cond;
2136 // Check the relevant induction variable for conformance to
2138 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2139 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2140 if (!AR || !AR->isAffine() ||
2141 AR->getStart() != One ||
2142 AR->getStepRecurrence(*SE) != One)
2145 assert(AR->getLoop() == L &&
2146 "Loop condition operand is an addrec in a different loop!");
2148 // Check the right operand of the select, and remember it, as it will
2149 // be used in the new comparison instruction.
2151 if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
2152 NewRHS = Sel->getOperand(1);
2153 else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
2154 NewRHS = Sel->getOperand(2);
2155 if (!NewRHS) return Cond;
2157 // Ok, everything looks ok to change the condition into an SLT or SGE and
2158 // delete the max calculation.
2160 new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
2163 Cond->getOperand(0), NewRHS, "scmp", Cond);
2165 // Delete the max calculation instructions.
2166 Cond->replaceAllUsesWith(NewCond);
2167 CondUse->setUser(NewCond);
2168 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2169 Cond->eraseFromParent();
2170 Sel->eraseFromParent();
2171 if (Cmp->use_empty())
2172 Cmp->eraseFromParent();
2176 /// OptimizeShadowIV - If IV is used in a int-to-float cast
2177 /// inside the loop then try to eliminate the cast opeation.
2178 void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2180 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2181 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2184 for (unsigned Stride = 0, e = IU->StrideOrder.size(); Stride != e;
2186 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2187 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2188 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2189 if (!isa<SCEVConstant>(SI->first))
2192 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
2193 E = SI->second->Users.end(); UI != E; /* empty */) {
2194 ilist<IVStrideUse>::iterator CandidateUI = UI;
2196 Instruction *ShadowUse = CandidateUI->getUser();
2197 const Type *DestTy = NULL;
2199 /* If shadow use is a int->float cast then insert a second IV
2200 to eliminate this cast.
2202 for (unsigned i = 0; i < n; ++i)
2208 for (unsigned i = 0; i < n; ++i, ++d)
2211 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
2212 DestTy = UCast->getDestTy();
2213 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
2214 DestTy = SCast->getDestTy();
2215 if (!DestTy) continue;
2218 // If target does not support DestTy natively then do not apply
2219 // this transformation.
2220 MVT DVT = TLI->getValueType(DestTy);
2221 if (!TLI->isTypeLegal(DVT)) continue;
2224 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2226 if (PH->getNumIncomingValues() != 2) continue;
2228 const Type *SrcTy = PH->getType();
2229 int Mantissa = DestTy->getFPMantissaWidth();
2230 if (Mantissa == -1) continue;
2231 if ((int)SE->getTypeSizeInBits(SrcTy) > Mantissa)
2234 unsigned Entry, Latch;
2235 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2243 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2244 if (!Init) continue;
2245 ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2247 BinaryOperator *Incr =
2248 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2249 if (!Incr) continue;
2250 if (Incr->getOpcode() != Instruction::Add
2251 && Incr->getOpcode() != Instruction::Sub)
2254 /* Initialize new IV, double d = 0.0 in above example. */
2255 ConstantInt *C = NULL;
2256 if (Incr->getOperand(0) == PH)
2257 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2258 else if (Incr->getOperand(1) == PH)
2259 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2265 /* Add new PHINode. */
2266 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2268 /* create new increment. '++d' in above example. */
2269 ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2270 BinaryOperator *NewIncr =
2271 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
2272 Instruction::FAdd : Instruction::FSub,
2273 NewPH, CFP, "IV.S.next.", Incr);
2275 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2276 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2278 /* Remove cast operation */
2279 ShadowUse->replaceAllUsesWith(NewPH);
2280 ShadowUse->eraseFromParent();
2287 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2288 // uses in the loop, look to see if we can eliminate some, in favor of using
2289 // common indvars for the different uses.
2290 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2291 // TODO: implement optzns here.
2293 OptimizeShadowIV(L);
2296 /// OptimizeLoopTermCond - Change loop terminating condition to use the
2297 /// postinc iv when possible.
2298 void LoopStrengthReduce::OptimizeLoopTermCond(Loop *L) {
2299 // Finally, get the terminating condition for the loop if possible. If we
2300 // can, we want to change it to use a post-incremented version of its
2301 // induction variable, to allow coalescing the live ranges for the IV into
2302 // one register value.
2303 BasicBlock *LatchBlock = L->getLoopLatch();
2304 BasicBlock *ExitBlock = L->getExitingBlock();
2306 // Multiple exits, just look at the exit in the latch block if there is one.
2307 ExitBlock = LatchBlock;
2308 BranchInst *TermBr = dyn_cast<BranchInst>(ExitBlock->getTerminator());
2311 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2314 // Search IVUsesByStride to find Cond's IVUse if there is one.
2315 IVStrideUse *CondUse = 0;
2316 const SCEVHandle *CondStride = 0;
2317 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2318 if (!FindIVUserForCond(Cond, CondUse, CondStride))
2319 return; // setcc doesn't use the IV.
2321 if (ExitBlock != LatchBlock) {
2322 if (!Cond->hasOneUse())
2323 // See below, we don't want the condition to be cloned.
2326 // If exiting block is the latch block, we know it's safe and profitable to
2327 // transform the icmp to use post-inc iv. Otherwise do so only if it would
2328 // not reuse another iv and its iv would be reused by other uses. We are
2329 // optimizing for the case where the icmp is the only use of the iv.
2330 IVUsersOfOneStride &StrideUses = *IU->IVUsesByStride[*CondStride];
2331 for (ilist<IVStrideUse>::iterator I = StrideUses.Users.begin(),
2332 E = StrideUses.Users.end(); I != E; ++I) {
2333 if (I->getUser() == Cond)
2335 if (!I->isUseOfPostIncrementedValue())
2339 // FIXME: This is expensive, and worse still ChangeCompareStride does a
2340 // similar check. Can we perform all the icmp related transformations after
2341 // StrengthReduceStridedIVUsers?
2342 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride)) {
2343 int64_t SInt = SC->getValue()->getSExtValue();
2344 for (unsigned NewStride = 0, ee = IU->StrideOrder.size(); NewStride != ee;
2346 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2347 IU->IVUsesByStride.find(IU->StrideOrder[NewStride]);
2348 if (!isa<SCEVConstant>(SI->first) || SI->first == *CondStride)
2351 cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2353 return; // This can definitely be reused.
2354 if (unsigned(abs64(SSInt)) < SInt || (SSInt % SInt) != 0)
2356 int64_t Scale = SSInt / SInt;
2357 bool AllUsesAreAddresses = true;
2358 bool AllUsesAreOutsideLoop = true;
2359 std::vector<BasedUser> UsersToProcess;
2360 SCEVHandle CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
2361 AllUsesAreAddresses,
2362 AllUsesAreOutsideLoop,
2364 // Avoid rewriting the compare instruction with an iv of new stride
2365 // if it's likely the new stride uses will be rewritten using the
2366 // stride of the compare instruction.
2367 if (AllUsesAreAddresses &&
2368 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
2373 StrideNoReuse.insert(*CondStride);
2376 // If the trip count is computed in terms of an smax (due to ScalarEvolution
2377 // being unable to find a sufficient guard, for example), change the loop
2378 // comparison to use SLT instead of NE.
2379 Cond = OptimizeSMax(L, Cond, CondUse);
2381 // If possible, change stride and operands of the compare instruction to
2382 // eliminate one stride.
2383 if (ExitBlock == LatchBlock)
2384 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
2386 // It's possible for the setcc instruction to be anywhere in the loop, and
2387 // possible for it to have multiple users. If it is not immediately before
2388 // the latch block branch, move it.
2389 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2390 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
2391 Cond->moveBefore(TermBr);
2393 // Otherwise, clone the terminating condition and insert into the loopend.
2394 Cond = cast<ICmpInst>(Cond->clone());
2395 Cond->setName(L->getHeader()->getName() + ".termcond");
2396 LatchBlock->getInstList().insert(TermBr, Cond);
2398 // Clone the IVUse, as the old use still exists!
2399 IU->IVUsesByStride[*CondStride]->addUser(CondUse->getOffset(), Cond,
2400 CondUse->getOperandValToReplace(),
2402 CondUse = &IU->IVUsesByStride[*CondStride]->Users.back();
2406 // If we get to here, we know that we can transform the setcc instruction to
2407 // use the post-incremented version of the IV, allowing us to coalesce the
2408 // live ranges for the IV correctly.
2409 CondUse->setOffset(SE->getMinusSCEV(CondUse->getOffset(), *CondStride));
2410 CondUse->setIsUseOfPostIncrementedValue(true);
2416 // OptimizeLoopCountIV - If, after all sharing of IVs, the IV used for deciding
2417 // when to exit the loop is used only for that purpose, try to rearrange things
2418 // so it counts down to a test against zero.
2419 void LoopStrengthReduce::OptimizeLoopCountIV(Loop *L) {
2421 // If the number of times the loop is executed isn't computable, give up.
2422 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2423 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2426 // Get the terminating condition for the loop if possible (this isn't
2427 // necessarily in the latch, or a block that's a predecessor of the header).
2428 if (!L->getExitBlock())
2429 return; // More than one loop exit blocks.
2431 // Okay, there is one exit block. Try to find the condition that causes the
2432 // loop to be exited.
2433 BasicBlock *ExitingBlock = L->getExitingBlock();
2435 return; // More than one block exiting!
2437 // Okay, we've computed the exiting block. See what condition causes us to
2440 // FIXME: we should be able to handle switch instructions (with a single exit)
2441 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2442 if (TermBr == 0) return;
2443 assert(TermBr->isConditional() && "If unconditional, it can't be in loop!");
2444 if (!isa<ICmpInst>(TermBr->getCondition()))
2446 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2448 // Handle only tests for equality for the moment, and only stride 1.
2449 if (Cond->getPredicate() != CmpInst::ICMP_EQ)
2451 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2452 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2453 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2454 if (!AR || !AR->isAffine() || AR->getStepRecurrence(*SE) != One)
2456 // If the RHS of the comparison is defined inside the loop, the rewrite
2458 if (Instruction *CR = dyn_cast<Instruction>(Cond->getOperand(1)))
2459 if (L->contains(CR->getParent()))
2462 // Make sure the IV is only used for counting. Value may be preinc or
2463 // postinc; 2 uses in either case.
2464 if (!Cond->getOperand(0)->hasNUses(2))
2466 PHINode *phi = dyn_cast<PHINode>(Cond->getOperand(0));
2468 if (phi && phi->getParent()==L->getHeader()) {
2469 // value tested is preinc. Find the increment.
2470 // A CmpInst is not a BinaryOperator; we depend on this.
2471 Instruction::use_iterator UI = phi->use_begin();
2472 incr = dyn_cast<BinaryOperator>(UI);
2474 incr = dyn_cast<BinaryOperator>(++UI);
2475 // 1 use for postinc value, the phi. Unnecessarily conservative?
2476 if (!incr || !incr->hasOneUse() || incr->getOpcode()!=Instruction::Add)
2479 // Value tested is postinc. Find the phi node.
2480 incr = dyn_cast<BinaryOperator>(Cond->getOperand(0));
2481 if (!incr || incr->getOpcode()!=Instruction::Add)
2484 Instruction::use_iterator UI = Cond->getOperand(0)->use_begin();
2485 phi = dyn_cast<PHINode>(UI);
2487 phi = dyn_cast<PHINode>(++UI);
2488 // 1 use for preinc value, the increment.
2489 if (!phi || phi->getParent()!=L->getHeader() || !phi->hasOneUse())
2493 // Replace the increment with a decrement.
2494 BinaryOperator *decr =
2495 BinaryOperator::Create(Instruction::Sub, incr->getOperand(0),
2496 incr->getOperand(1), "tmp", incr);
2497 incr->replaceAllUsesWith(decr);
2498 incr->eraseFromParent();
2500 // Substitute endval-startval for the original startval, and 0 for the
2501 // original endval. Since we're only testing for equality this is OK even
2502 // if the computation wraps around.
2503 BasicBlock *Preheader = L->getLoopPreheader();
2504 Instruction *PreInsertPt = Preheader->getTerminator();
2505 int inBlock = L->contains(phi->getIncomingBlock(0)) ? 1 : 0;
2506 Value *startVal = phi->getIncomingValue(inBlock);
2507 Value *endVal = Cond->getOperand(1);
2508 // FIXME check for case where both are constant
2509 ConstantInt* Zero = ConstantInt::get(Cond->getOperand(1)->getType(), 0);
2510 BinaryOperator *NewStartVal =
2511 BinaryOperator::Create(Instruction::Sub, endVal, startVal,
2512 "tmp", PreInsertPt);
2513 phi->setIncomingValue(inBlock, NewStartVal);
2514 Cond->setOperand(1, Zero);
2519 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
2521 IU = &getAnalysis<IVUsers>();
2522 LI = &getAnalysis<LoopInfo>();
2523 DT = &getAnalysis<DominatorTree>();
2524 SE = &getAnalysis<ScalarEvolution>();
2527 if (!IU->IVUsesByStride.empty()) {
2529 DOUT << "\nLSR on \"" << L->getHeader()->getParent()->getNameStart()
2534 // Sort the StrideOrder so we process larger strides first.
2535 std::stable_sort(IU->StrideOrder.begin(), IU->StrideOrder.end(),
2538 // Optimize induction variables. Some indvar uses can be transformed to use
2539 // strides that will be needed for other purposes. A common example of this
2540 // is the exit test for the loop, which can often be rewritten to use the
2541 // computation of some other indvar to decide when to terminate the loop.
2544 // Change loop terminating condition to use the postinc iv when possible
2545 // and optimize loop terminating compare. FIXME: Move this after
2546 // StrengthReduceStridedIVUsers?
2547 OptimizeLoopTermCond(L);
2549 // FIXME: We can shrink overlarge IV's here. e.g. if the code has
2550 // computation in i64 values and the target doesn't support i64, demote
2551 // the computation to 32-bit if safe.
2553 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
2554 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2555 // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2556 // Need to be careful that IV's are all the same type. Only works for
2557 // intptr_t indvars.
2559 // IVsByStride keeps IVs for one particular loop.
2560 assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
2562 // Note: this processes each stride/type pair individually. All users
2563 // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2564 // Also, note that we iterate over IVUsesByStride indirectly by using
2565 // StrideOrder. This extra layer of indirection makes the ordering of
2566 // strides deterministic - not dependent on map order.
2567 for (unsigned Stride = 0, e = IU->StrideOrder.size();
2568 Stride != e; ++Stride) {
2569 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2570 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2571 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2572 // FIXME: Generalize to non-affine IV's.
2573 if (!SI->first->isLoopInvariant(L))
2575 StrengthReduceStridedIVUsers(SI->first, *SI->second, L);
2579 // After all sharing is done, see if we can adjust the loop to test against
2580 // zero instead of counting up to a maximum. This is usually faster.
2581 OptimizeLoopCountIV(L);
2583 // We're done analyzing this loop; release all the state we built up for it.
2584 IVsByStride.clear();
2585 StrideNoReuse.clear();
2587 // Clean up after ourselves
2588 if (!DeadInsts.empty())
2589 DeleteTriviallyDeadInstructions();
2591 // At this point, it is worth checking to see if any recurrence PHIs are also
2592 // dead, so that we can remove them as well.
2593 DeleteDeadPHIs(L->getHeader());