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/CommandLine.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Support/raw_ostream.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");
54 STATISTIC(NumCountZero, "Number of count iv optimized to count toward zero");
56 static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
64 /// IVInfo - This structure keeps track of one IV expression inserted during
65 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
66 /// well as the PHI node and increment value created for rewrite.
72 IVExpr(const SCEV *const stride, const SCEV *const base, PHINode *phi)
73 : Stride(stride), Base(base), PHI(phi) {}
76 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
77 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
78 struct IVsOfOneStride {
79 std::vector<IVExpr> IVs;
81 void addIV(const SCEV *const Stride, const SCEV *const Base, PHINode *PHI) {
82 IVs.push_back(IVExpr(Stride, Base, PHI));
86 class LoopStrengthReduce : public LoopPass {
93 /// IVsByStride - Keep track of all IVs that have been inserted for a
94 /// particular stride.
95 std::map<const SCEV *, IVsOfOneStride> IVsByStride;
97 /// StrideNoReuse - Keep track of all the strides whose ivs cannot be
98 /// reused (nor should they be rewritten to reuse other strides).
99 SmallSet<const SCEV *, 4> StrideNoReuse;
101 /// DeadInsts - Keep track of instructions we may have made dead, so that
102 /// we can remove them after we are done working.
103 SmallVector<WeakVH, 16> DeadInsts;
105 /// TLI - Keep a pointer of a TargetLowering to consult for determining
106 /// transformation profitability.
107 const TargetLowering *TLI;
110 static char ID; // Pass ID, replacement for typeid
111 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
112 LoopPass(&ID), TLI(tli) {
115 bool runOnLoop(Loop *L, LPPassManager &LPM);
117 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
118 // We split critical edges, so we change the CFG. However, we do update
119 // many analyses if they are around.
120 AU.addPreservedID(LoopSimplifyID);
121 AU.addPreserved<LoopInfo>();
122 AU.addPreserved<DominanceFrontier>();
123 AU.addPreserved<DominatorTree>();
125 AU.addRequiredID(LoopSimplifyID);
126 AU.addRequired<LoopInfo>();
127 AU.addRequired<DominatorTree>();
128 AU.addRequired<ScalarEvolution>();
129 AU.addPreserved<ScalarEvolution>();
130 AU.addRequired<IVUsers>();
131 AU.addPreserved<IVUsers>();
135 void OptimizeIndvars(Loop *L);
137 /// OptimizeLoopTermCond - Change loop terminating condition to use the
138 /// postinc iv when possible.
139 void OptimizeLoopTermCond(Loop *L);
141 /// OptimizeShadowIV - If IV is used in a int-to-float cast
142 /// inside the loop then try to eliminate the cast opeation.
143 void OptimizeShadowIV(Loop *L);
145 /// OptimizeMax - Rewrite the loop's terminating condition
146 /// if it uses a max computation.
147 ICmpInst *OptimizeMax(Loop *L, ICmpInst *Cond,
148 IVStrideUse* &CondUse);
150 /// OptimizeLoopCountIV - If, after all sharing of IVs, the IV used for
151 /// deciding when to exit the loop is used only for that purpose, try to
152 /// rearrange things so it counts down to a test against zero.
153 bool OptimizeLoopCountIV(Loop *L);
154 bool OptimizeLoopCountIVOfStride(const SCEV* &Stride,
155 IVStrideUse* &CondUse, Loop *L);
157 /// StrengthReduceIVUsersOfStride - Strength reduce all of the users of a
158 /// single stride of IV. All of the users may have different starting
159 /// values, and this may not be the only stride.
160 void StrengthReduceIVUsersOfStride(const SCEV *const &Stride,
161 IVUsersOfOneStride &Uses,
163 void StrengthReduceIVUsers(Loop *L);
165 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
166 IVStrideUse* &CondUse, const SCEV* &CondStride,
167 bool PostPass = false);
169 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
170 const SCEV* &CondStride);
171 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
172 const SCEV *CheckForIVReuse(bool, bool, bool, const SCEV *const&,
173 IVExpr&, const Type*,
174 const std::vector<BasedUser>& UsersToProcess);
175 bool ValidScale(bool, int64_t,
176 const std::vector<BasedUser>& UsersToProcess);
177 bool ValidOffset(bool, int64_t, int64_t,
178 const std::vector<BasedUser>& UsersToProcess);
179 const SCEV *CollectIVUsers(const SCEV *const &Stride,
180 IVUsersOfOneStride &Uses,
182 bool &AllUsesAreAddresses,
183 bool &AllUsesAreOutsideLoop,
184 std::vector<BasedUser> &UsersToProcess);
185 bool StrideMightBeShared(const SCEV *Stride, Loop *L, bool CheckPreInc);
186 bool ShouldUseFullStrengthReductionMode(
187 const std::vector<BasedUser> &UsersToProcess,
189 bool AllUsesAreAddresses,
191 void PrepareToStrengthReduceFully(
192 std::vector<BasedUser> &UsersToProcess,
194 const SCEV *CommonExprs,
196 SCEVExpander &PreheaderRewriter);
197 void PrepareToStrengthReduceFromSmallerStride(
198 std::vector<BasedUser> &UsersToProcess,
200 const IVExpr &ReuseIV,
201 Instruction *PreInsertPt);
202 void PrepareToStrengthReduceWithNewPhi(
203 std::vector<BasedUser> &UsersToProcess,
205 const SCEV *CommonExprs,
207 Instruction *IVIncInsertPt,
209 SCEVExpander &PreheaderRewriter);
211 void DeleteTriviallyDeadInstructions();
215 char LoopStrengthReduce::ID = 0;
216 static RegisterPass<LoopStrengthReduce>
217 X("loop-reduce", "Loop Strength Reduction");
219 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
220 return new LoopStrengthReduce(TLI);
223 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
224 /// specified set are trivially dead, delete them and see if this makes any of
225 /// their operands subsequently dead.
226 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
227 if (DeadInsts.empty()) return;
229 while (!DeadInsts.empty()) {
230 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.back());
231 DeadInsts.pop_back();
233 if (I == 0 || !isInstructionTriviallyDead(I))
236 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
237 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
240 DeadInsts.push_back(U);
244 I->eraseFromParent();
249 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a
250 /// subexpression that is an AddRec from a loop other than L. An outer loop
251 /// of L is OK, but not an inner loop nor a disjoint loop.
252 static bool containsAddRecFromDifferentLoop(const SCEV *S, Loop *L) {
253 // This is very common, put it first.
254 if (isa<SCEVConstant>(S))
256 if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
257 for (unsigned int i=0; i< AE->getNumOperands(); i++)
258 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
262 if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
263 if (const Loop *newLoop = AE->getLoop()) {
266 // if newLoop is an outer loop of L, this is OK.
267 if (!LoopInfo::isNotAlreadyContainedIn(L, newLoop))
272 if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
273 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
274 containsAddRecFromDifferentLoop(DE->getRHS(), L);
276 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
277 // need this when it is.
278 if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
279 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
280 containsAddRecFromDifferentLoop(DE->getRHS(), L);
282 if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
283 return containsAddRecFromDifferentLoop(CE->getOperand(), L);
287 /// isAddressUse - Returns true if the specified instruction is using the
288 /// specified value as an address.
289 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
290 bool isAddress = isa<LoadInst>(Inst);
291 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
292 if (SI->getOperand(1) == OperandVal)
294 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
295 // Addressing modes can also be folded into prefetches and a variety
297 switch (II->getIntrinsicID()) {
299 case Intrinsic::prefetch:
300 case Intrinsic::x86_sse2_loadu_dq:
301 case Intrinsic::x86_sse2_loadu_pd:
302 case Intrinsic::x86_sse_loadu_ps:
303 case Intrinsic::x86_sse_storeu_ps:
304 case Intrinsic::x86_sse2_storeu_pd:
305 case Intrinsic::x86_sse2_storeu_dq:
306 case Intrinsic::x86_sse2_storel_dq:
307 if (II->getOperand(1) == OperandVal)
315 /// getAccessType - Return the type of the memory being accessed.
316 static const Type *getAccessType(const Instruction *Inst) {
317 const Type *AccessTy = Inst->getType();
318 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
319 AccessTy = SI->getOperand(0)->getType();
320 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
321 // Addressing modes can also be folded into prefetches and a variety
323 switch (II->getIntrinsicID()) {
325 case Intrinsic::x86_sse_storeu_ps:
326 case Intrinsic::x86_sse2_storeu_pd:
327 case Intrinsic::x86_sse2_storeu_dq:
328 case Intrinsic::x86_sse2_storel_dq:
329 AccessTy = II->getOperand(1)->getType();
337 /// BasedUser - For a particular base value, keep information about how we've
338 /// partitioned the expression so far.
340 /// SE - The current ScalarEvolution object.
343 /// Base - The Base value for the PHI node that needs to be inserted for
344 /// this use. As the use is processed, information gets moved from this
345 /// field to the Imm field (below). BasedUser values are sorted by this
349 /// Inst - The instruction using the induction variable.
352 /// OperandValToReplace - The operand value of Inst to replace with the
354 Value *OperandValToReplace;
356 /// Imm - The immediate value that should be added to the base immediately
357 /// before Inst, because it will be folded into the imm field of the
358 /// instruction. This is also sometimes used for loop-variant values that
359 /// must be added inside the loop.
362 /// Phi - The induction variable that performs the striding that
363 /// should be used for this user.
366 // isUseOfPostIncrementedValue - True if this should use the
367 // post-incremented version of this IV, not the preincremented version.
368 // This can only be set in special cases, such as the terminating setcc
369 // instruction for a loop and uses outside the loop that are dominated by
371 bool isUseOfPostIncrementedValue;
373 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
374 : SE(se), Base(IVSU.getOffset()), Inst(IVSU.getUser()),
375 OperandValToReplace(IVSU.getOperandValToReplace()),
376 Imm(SE->getIntegerSCEV(0, Base->getType())),
377 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue()) {}
379 // Once we rewrite the code to insert the new IVs we want, update the
380 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
382 void RewriteInstructionToUseNewBase(const SCEV *const &NewBase,
383 Instruction *InsertPt,
384 SCEVExpander &Rewriter, Loop *L, Pass *P,
386 SmallVectorImpl<WeakVH> &DeadInsts);
388 Value *InsertCodeForBaseAtPosition(const SCEV *const &NewBase,
390 SCEVExpander &Rewriter,
391 Instruction *IP, Loop *L,
397 void BasedUser::dump() const {
398 errs() << " Base=" << *Base;
399 errs() << " Imm=" << *Imm;
400 errs() << " Inst: " << *Inst;
403 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEV *const &NewBase,
405 SCEVExpander &Rewriter,
406 Instruction *IP, Loop *L,
408 // Figure out where we *really* want to insert this code. In particular, if
409 // the user is inside of a loop that is nested inside of L, we really don't
410 // want to insert this expression before the user, we'd rather pull it out as
411 // many loops as possible.
412 Instruction *BaseInsertPt = IP;
414 // Figure out the most-nested loop that IP is in.
415 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
417 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
418 // the preheader of the outer-most loop where NewBase is not loop invariant.
419 if (L->contains(IP->getParent()))
420 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
421 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
422 InsertLoop = InsertLoop->getParentLoop();
425 Value *Base = Rewriter.expandCodeFor(NewBase, 0, BaseInsertPt);
427 const SCEV *NewValSCEV = SE->getUnknown(Base);
429 // Always emit the immediate into the same block as the user.
430 NewValSCEV = SE->getAddExpr(NewValSCEV, Imm);
432 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
436 // Once we rewrite the code to insert the new IVs we want, update the
437 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
438 // to it. NewBasePt is the last instruction which contributes to the
439 // value of NewBase in the case that it's a diffferent instruction from
440 // the PHI that NewBase is computed from, or null otherwise.
442 void BasedUser::RewriteInstructionToUseNewBase(const SCEV *const &NewBase,
443 Instruction *NewBasePt,
444 SCEVExpander &Rewriter, Loop *L, Pass *P,
446 SmallVectorImpl<WeakVH> &DeadInsts) {
447 if (!isa<PHINode>(Inst)) {
448 // By default, insert code at the user instruction.
449 BasicBlock::iterator InsertPt = Inst;
451 // However, if the Operand is itself an instruction, the (potentially
452 // complex) inserted code may be shared by many users. Because of this, we
453 // want to emit code for the computation of the operand right before its old
454 // computation. This is usually safe, because we obviously used to use the
455 // computation when it was computed in its current block. However, in some
456 // cases (e.g. use of a post-incremented induction variable) the NewBase
457 // value will be pinned to live somewhere after the original computation.
458 // In this case, we have to back off.
460 // If this is a use outside the loop (which means after, since it is based
461 // on a loop indvar) we use the post-incremented value, so that we don't
462 // artificially make the preinc value live out the bottom of the loop.
463 if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
464 if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
465 InsertPt = NewBasePt;
467 } else if (Instruction *OpInst
468 = dyn_cast<Instruction>(OperandValToReplace)) {
470 while (isa<PHINode>(InsertPt)) ++InsertPt;
473 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
474 OperandValToReplace->getType(),
475 Rewriter, InsertPt, L, LI);
476 // Replace the use of the operand Value with the new Phi we just created.
477 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
479 DEBUG(errs() << " Replacing with ");
480 DEBUG(WriteAsOperand(errs(), NewVal, /*PrintType=*/false));
481 DEBUG(errs() << ", which has value " << *NewBase << " plus IMM "
486 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
487 // expression into each operand block that uses it. Note that PHI nodes can
488 // have multiple entries for the same predecessor. We use a map to make sure
489 // that a PHI node only has a single Value* for each predecessor (which also
490 // prevents us from inserting duplicate code in some blocks).
491 DenseMap<BasicBlock*, Value*> InsertedCode;
492 PHINode *PN = cast<PHINode>(Inst);
493 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
494 if (PN->getIncomingValue(i) == OperandValToReplace) {
495 // If the original expression is outside the loop, put the replacement
496 // code in the same place as the original expression,
497 // which need not be an immediate predecessor of this PHI. This way we
498 // need only one copy of it even if it is referenced multiple times in
499 // the PHI. We don't do this when the original expression is inside the
500 // loop because multiple copies sometimes do useful sinking of code in
502 Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
503 BasicBlock *PHIPred = PN->getIncomingBlock(i);
504 if (L->contains(OldLoc->getParent())) {
505 // If this is a critical edge, split the edge so that we do not insert
506 // the code on all predecessor/successor paths. We do this unless this
507 // is the canonical backedge for this loop, as this can make some
508 // inserted code be in an illegal position.
509 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
510 !isa<IndirectBrInst>(PHIPred->getTerminator()) &&
511 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
513 // First step, split the critical edge.
514 BasicBlock *NewBB = SplitCriticalEdge(PHIPred, PN->getParent(),
517 // Next step: move the basic block. In particular, if the PHI node
518 // is outside of the loop, and PredTI is in the loop, we want to
519 // move the block to be immediately before the PHI block, not
520 // immediately after PredTI.
521 if (L->contains(PHIPred) && !L->contains(PN->getParent()))
522 NewBB->moveBefore(PN->getParent());
524 // Splitting the edge can reduce the number of PHI entries we have.
525 e = PN->getNumIncomingValues();
527 i = PN->getBasicBlockIndex(PHIPred);
530 Value *&Code = InsertedCode[PHIPred];
532 // Insert the code into the end of the predecessor block.
533 Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
534 PHIPred->getTerminator() :
535 OldLoc->getParent()->getTerminator();
536 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
537 Rewriter, InsertPt, L, LI);
539 DEBUG(errs() << " Changing PHI use to ");
540 DEBUG(WriteAsOperand(errs(), Code, /*PrintType=*/false));
541 DEBUG(errs() << ", which has value " << *NewBase << " plus IMM "
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 SCEV *const &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(const SCEV *&Val, const SCEV *&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 SmallVector<const SCEV *, 4> 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 const SCEV *Start = SARE->getStart();
614 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
616 SmallVector<const SCEV *, 4> 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 const SCEV *&Val, const SCEV *&Imm,
633 bool isAddress, Loop *L,
634 ScalarEvolution *SE) {
635 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
636 SmallVector<const SCEV *, 4> NewOps;
637 NewOps.reserve(SAE->getNumOperands());
639 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
640 const SCEV *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 const SCEV *Start = SARE->getStart();
660 MoveImmediateValues(TLI, AccessTy, Start, Imm, isAddress, L, SE);
662 if (Start != SARE->getStart()) {
663 SmallVector<const SCEV *, 4> 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 const SCEV *SubImm = SE->getIntegerSCEV(0, Val->getType());
675 const SCEV *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 const SCEV *&Val, const SCEV *&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(SmallVector<const SCEV *, 16> &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 const SCEV *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 SmallVector<const SCEV *, 4> 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 const SCEV *Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
765 const SCEV *Result = Zero;
766 const SCEV *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<const SCEV *, SubExprUseData> SubExpressionUseData;
784 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
785 // order we see them.
786 SmallVector<const SCEV *, 16> UniqueSubExprs;
788 SmallVector<const SCEV *, 16> 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<const SCEV *, 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<const SCEV *, 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 =
926 Type::getVoidTy(UsersToProcess[i].Inst->getContext());
927 if (isAddressUse(UsersToProcess[i].Inst,
928 UsersToProcess[i].OperandValToReplace))
929 AccessTy = getAccessType(UsersToProcess[i].Inst);
930 else if (isa<PHINode>(UsersToProcess[i].Inst))
933 TargetLowering::AddrMode AM;
934 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
935 AM.BaseOffs = SC->getValue()->getSExtValue();
936 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
939 // If load[imm+r*scale] is illegal, bail out.
940 if (!TLI->isLegalAddressingMode(AM, AccessTy))
946 /// ValidOffset - Check whether the given Offset is valid for all loads and
947 /// stores in UsersToProcess.
949 bool LoopStrengthReduce::ValidOffset(bool HasBaseReg,
952 const std::vector<BasedUser>& UsersToProcess) {
956 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
957 // If this is a load or other access, pass the type of the access in.
958 const Type *AccessTy =
959 Type::getVoidTy(UsersToProcess[i].Inst->getContext());
960 if (isAddressUse(UsersToProcess[i].Inst,
961 UsersToProcess[i].OperandValToReplace))
962 AccessTy = getAccessType(UsersToProcess[i].Inst);
963 else if (isa<PHINode>(UsersToProcess[i].Inst))
966 TargetLowering::AddrMode AM;
967 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
968 AM.BaseOffs = SC->getValue()->getSExtValue();
969 AM.BaseOffs = (uint64_t)AM.BaseOffs + (uint64_t)Offset;
970 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
973 // If load[imm+r*scale] is illegal, bail out.
974 if (!TLI->isLegalAddressingMode(AM, AccessTy))
980 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
982 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
986 Ty1 = SE->getEffectiveSCEVType(Ty1);
987 Ty2 = SE->getEffectiveSCEVType(Ty2);
990 if (Ty1->canLosslesslyBitCastTo(Ty2))
992 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
997 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
998 /// of a previous stride and it is a legal value for the target addressing
999 /// mode scale component and optional base reg. This allows the users of
1000 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
1001 /// reuse is possible. Factors can be negative on same targets, e.g. ARM.
1003 /// If all uses are outside the loop, we don't require that all multiplies
1004 /// be folded into the addressing mode, nor even that the factor be constant;
1005 /// a multiply (executed once) outside the loop is better than another IV
1006 /// within. Well, usually.
1007 const SCEV *LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
1008 bool AllUsesAreAddresses,
1009 bool AllUsesAreOutsideLoop,
1010 const SCEV *const &Stride,
1011 IVExpr &IV, const Type *Ty,
1012 const std::vector<BasedUser>& UsersToProcess) {
1013 if (StrideNoReuse.count(Stride))
1014 return SE->getIntegerSCEV(0, Stride->getType());
1016 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
1017 int64_t SInt = SC->getValue()->getSExtValue();
1018 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1019 NewStride != e; ++NewStride) {
1020 std::map<const SCEV *, IVsOfOneStride>::iterator SI =
1021 IVsByStride.find(IU->StrideOrder[NewStride]);
1022 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first) ||
1023 StrideNoReuse.count(SI->first))
1025 // The other stride has no uses, don't reuse it.
1026 std::map<const SCEV *, IVUsersOfOneStride *>::iterator UI =
1027 IU->IVUsesByStride.find(IU->StrideOrder[NewStride]);
1028 if (UI->second->Users.empty())
1030 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1031 if (SI->first != Stride &&
1032 (unsigned(abs64(SInt)) < SSInt || (SInt % SSInt) != 0))
1034 int64_t Scale = SInt / SSInt;
1035 // Check that this stride is valid for all the types used for loads and
1036 // stores; if it can be used for some and not others, we might as well use
1037 // the original stride everywhere, since we have to create the IV for it
1038 // anyway. If the scale is 1, then we don't need to worry about folding
1041 (AllUsesAreAddresses &&
1042 ValidScale(HasBaseReg, Scale, UsersToProcess))) {
1043 // Prefer to reuse an IV with a base of zero.
1044 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1045 IE = SI->second.IVs.end(); II != IE; ++II)
1046 // Only reuse previous IV if it would not require a type conversion
1047 // and if the base difference can be folded.
1048 if (II->Base->isZero() &&
1049 !RequiresTypeConversion(II->Base->getType(), Ty)) {
1051 return SE->getIntegerSCEV(Scale, Stride->getType());
1053 // Otherwise, settle for an IV with a foldable base.
1054 if (AllUsesAreAddresses)
1055 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1056 IE = SI->second.IVs.end(); II != IE; ++II)
1057 // Only reuse previous IV if it would not require a type conversion
1058 // and if the base difference can be folded.
1059 if (SE->getEffectiveSCEVType(II->Base->getType()) ==
1060 SE->getEffectiveSCEVType(Ty) &&
1061 isa<SCEVConstant>(II->Base)) {
1063 cast<SCEVConstant>(II->Base)->getValue()->getSExtValue();
1064 if (Base > INT32_MIN && Base <= INT32_MAX &&
1065 ValidOffset(HasBaseReg, -Base * Scale,
1066 Scale, UsersToProcess)) {
1068 return SE->getIntegerSCEV(Scale, Stride->getType());
1073 } else if (AllUsesAreOutsideLoop) {
1074 // Accept nonconstant strides here; it is really really right to substitute
1075 // an existing IV if we can.
1076 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1077 NewStride != e; ++NewStride) {
1078 std::map<const SCEV *, IVsOfOneStride>::iterator SI =
1079 IVsByStride.find(IU->StrideOrder[NewStride]);
1080 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1082 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1083 if (SI->first != Stride && SSInt != 1)
1085 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1086 IE = SI->second.IVs.end(); II != IE; ++II)
1087 // Accept nonzero base here.
1088 // Only reuse previous IV if it would not require a type conversion.
1089 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1094 // Special case, old IV is -1*x and this one is x. Can treat this one as
1096 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1097 NewStride != e; ++NewStride) {
1098 std::map<const SCEV *, IVsOfOneStride>::iterator SI =
1099 IVsByStride.find(IU->StrideOrder[NewStride]);
1100 if (SI == IVsByStride.end())
1102 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1103 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
1104 if (Stride == ME->getOperand(1) &&
1105 SC->getValue()->getSExtValue() == -1LL)
1106 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1107 IE = SI->second.IVs.end(); II != IE; ++II)
1108 // Accept nonzero base here.
1109 // Only reuse previous IV if it would not require type conversion.
1110 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1112 return SE->getIntegerSCEV(-1LL, Stride->getType());
1116 return SE->getIntegerSCEV(0, Stride->getType());
1119 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1120 /// returns true if Val's isUseOfPostIncrementedValue is true.
1121 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1122 return Val.isUseOfPostIncrementedValue;
1125 /// isNonConstantNegative - Return true if the specified scev is negated, but
1127 static bool isNonConstantNegative(const SCEV *const &Expr) {
1128 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1129 if (!Mul) return false;
1131 // If there is a constant factor, it will be first.
1132 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1133 if (!SC) return false;
1135 // Return true if the value is negative, this matches things like (-42 * V).
1136 return SC->getValue()->getValue().isNegative();
1139 /// CollectIVUsers - Transform our list of users and offsets to a bit more
1140 /// complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1141 /// of the strided accesses, as well as the old information from Uses. We
1142 /// progressively move information from the Base field to the Imm field, until
1143 /// we eventually have the full access expression to rewrite the use.
1144 const SCEV *LoopStrengthReduce::CollectIVUsers(const SCEV *const &Stride,
1145 IVUsersOfOneStride &Uses,
1147 bool &AllUsesAreAddresses,
1148 bool &AllUsesAreOutsideLoop,
1149 std::vector<BasedUser> &UsersToProcess) {
1150 // FIXME: Generalize to non-affine IV's.
1151 if (!Stride->isLoopInvariant(L))
1152 return SE->getIntegerSCEV(0, Stride->getType());
1154 UsersToProcess.reserve(Uses.Users.size());
1155 for (ilist<IVStrideUse>::iterator I = Uses.Users.begin(),
1156 E = Uses.Users.end(); I != E; ++I) {
1157 UsersToProcess.push_back(BasedUser(*I, SE));
1159 // Move any loop variant operands from the offset field to the immediate
1160 // field of the use, so that we don't try to use something before it is
1162 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1163 UsersToProcess.back().Imm, L, SE);
1164 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1165 "Base value is not loop invariant!");
1168 // We now have a whole bunch of uses of like-strided induction variables, but
1169 // they might all have different bases. We want to emit one PHI node for this
1170 // stride which we fold as many common expressions (between the IVs) into as
1171 // possible. Start by identifying the common expressions in the base values
1172 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1173 // "A+B"), emit it to the preheader, then remove the expression from the
1174 // UsersToProcess base values.
1175 const SCEV *CommonExprs =
1176 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1178 // Next, figure out what we can represent in the immediate fields of
1179 // instructions. If we can represent anything there, move it to the imm
1180 // fields of the BasedUsers. We do this so that it increases the commonality
1181 // of the remaining uses.
1182 unsigned NumPHI = 0;
1183 bool HasAddress = false;
1184 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1185 // If the user is not in the current loop, this means it is using the exit
1186 // value of the IV. Do not put anything in the base, make sure it's all in
1187 // the immediate field to allow as much factoring as possible.
1188 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1189 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1190 UsersToProcess[i].Base);
1191 UsersToProcess[i].Base =
1192 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1194 // Not all uses are outside the loop.
1195 AllUsesAreOutsideLoop = false;
1197 // Addressing modes can be folded into loads and stores. Be careful that
1198 // the store is through the expression, not of the expression though.
1200 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1201 UsersToProcess[i].OperandValToReplace);
1202 if (isa<PHINode>(UsersToProcess[i].Inst)) {
1210 // If this use isn't an address, then not all uses are addresses.
1211 if (!isAddress && !isPHI)
1212 AllUsesAreAddresses = false;
1214 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1215 UsersToProcess[i].Imm, isAddress, L, SE);
1219 // If one of the use is a PHI node and all other uses are addresses, still
1220 // allow iv reuse. Essentially we are trading one constant multiplication
1221 // for one fewer iv.
1223 AllUsesAreAddresses = false;
1225 // There are no in-loop address uses.
1226 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1227 AllUsesAreAddresses = false;
1232 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1233 /// is valid and profitable for the given set of users of a stride. In
1234 /// full strength-reduction mode, all addresses at the current stride are
1235 /// strength-reduced all the way down to pointer arithmetic.
1237 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1238 const std::vector<BasedUser> &UsersToProcess,
1240 bool AllUsesAreAddresses,
1241 const SCEV *Stride) {
1242 if (!EnableFullLSRMode)
1245 // The heuristics below aim to avoid increasing register pressure, but
1246 // fully strength-reducing all the addresses increases the number of
1247 // add instructions, so don't do this when optimizing for size.
1248 // TODO: If the loop is large, the savings due to simpler addresses
1249 // may oughtweight the costs of the extra increment instructions.
1250 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1253 // TODO: For now, don't do full strength reduction if there could
1254 // potentially be greater-stride multiples of the current stride
1255 // which could reuse the current stride IV.
1256 if (IU->StrideOrder.back() != Stride)
1259 // Iterate through the uses to find conditions that automatically rule out
1261 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1262 const SCEV *Base = UsersToProcess[i].Base;
1263 const SCEV *Imm = UsersToProcess[i].Imm;
1264 // If any users have a loop-variant component, they can't be fully
1265 // strength-reduced.
1266 if (Imm && !Imm->isLoopInvariant(L))
1268 // If there are to users with the same base and the difference between
1269 // the two Imm values can't be folded into the address, full
1270 // strength reduction would increase register pressure.
1272 const SCEV *CurImm = UsersToProcess[i].Imm;
1273 if ((CurImm || Imm) && CurImm != Imm) {
1274 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1275 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1276 const Instruction *Inst = UsersToProcess[i].Inst;
1277 const Type *AccessTy = getAccessType(Inst);
1278 const SCEV *Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1279 if (!Diff->isZero() &&
1280 (!AllUsesAreAddresses ||
1281 !fitsInAddressMode(Diff, AccessTy, TLI, /*HasBaseReg=*/true)))
1284 } while (++i != e && Base == UsersToProcess[i].Base);
1287 // If there's exactly one user in this stride, fully strength-reducing it
1288 // won't increase register pressure. If it's starting from a non-zero base,
1289 // it'll be simpler this way.
1290 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1293 // Otherwise, if there are any users in this stride that don't require
1294 // a register for their base, full strength-reduction will increase
1295 // register pressure.
1296 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1297 if (UsersToProcess[i].Base->isZero())
1300 // Otherwise, go for it.
1304 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1305 /// with the specified start and step values in the specified loop.
1307 /// If NegateStride is true, the stride should be negated by using a
1308 /// subtract instead of an add.
1310 /// Return the created phi node.
1312 static PHINode *InsertAffinePhi(const SCEV *Start, const SCEV *Step,
1313 Instruction *IVIncInsertPt,
1315 SCEVExpander &Rewriter) {
1316 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1317 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1319 BasicBlock *Header = L->getHeader();
1320 BasicBlock *Preheader = L->getLoopPreheader();
1321 BasicBlock *LatchBlock = L->getLoopLatch();
1322 const Type *Ty = Start->getType();
1323 Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
1325 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1326 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1329 // If the stride is negative, insert a sub instead of an add for the
1331 bool isNegative = isNonConstantNegative(Step);
1332 const SCEV *IncAmount = Step;
1334 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1336 // Insert an add instruction right before the terminator corresponding
1337 // to the back-edge or just before the only use. The location is determined
1338 // by the caller and passed in as IVIncInsertPt.
1339 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1340 Preheader->getTerminator());
1343 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1346 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1349 if (!isa<ConstantInt>(StepV)) ++NumVariable;
1351 PN->addIncoming(IncV, LatchBlock);
1357 static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1358 // We want to emit code for users inside the loop first. To do this, we
1359 // rearrange BasedUser so that the entries at the end have
1360 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1361 // vector (so we handle them first).
1362 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1363 PartitionByIsUseOfPostIncrementedValue);
1365 // Sort this by base, so that things with the same base are handled
1366 // together. By partitioning first and stable-sorting later, we are
1367 // guaranteed that within each base we will pop off users from within the
1368 // loop before users outside of the loop with a particular base.
1370 // We would like to use stable_sort here, but we can't. The problem is that
1371 // const SCEV *'s don't have a deterministic ordering w.r.t to each other, so
1372 // we don't have anything to do a '<' comparison on. Because we think the
1373 // number of uses is small, do a horrible bubble sort which just relies on
1375 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1376 // Get a base value.
1377 const SCEV *Base = UsersToProcess[i].Base;
1379 // Compact everything with this base to be consecutive with this one.
1380 for (unsigned j = i+1; j != e; ++j) {
1381 if (UsersToProcess[j].Base == Base) {
1382 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1389 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1390 /// UsersToProcess, meaning lowering addresses all the way down to direct
1391 /// pointer arithmetic.
1394 LoopStrengthReduce::PrepareToStrengthReduceFully(
1395 std::vector<BasedUser> &UsersToProcess,
1397 const SCEV *CommonExprs,
1399 SCEVExpander &PreheaderRewriter) {
1400 DEBUG(errs() << " Fully reducing all users\n");
1402 // Rewrite the UsersToProcess records, creating a separate PHI for each
1403 // unique Base value.
1404 Instruction *IVIncInsertPt = L->getLoopLatch()->getTerminator();
1405 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1406 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1407 // pick the first Imm value here to start with, and adjust it for the
1409 const SCEV *Imm = UsersToProcess[i].Imm;
1410 const SCEV *Base = UsersToProcess[i].Base;
1411 const SCEV *Start = SE->getAddExpr(CommonExprs, Base, Imm);
1412 PHINode *Phi = InsertAffinePhi(Start, Stride, IVIncInsertPt, L,
1414 // Loop over all the users with the same base.
1416 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1417 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1418 UsersToProcess[i].Phi = Phi;
1419 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1420 "ShouldUseFullStrengthReductionMode should reject this!");
1421 } while (++i != e && Base == UsersToProcess[i].Base);
1425 /// FindIVIncInsertPt - Return the location to insert the increment instruction.
1426 /// If the only use if a use of postinc value, (must be the loop termination
1427 /// condition), then insert it just before the use.
1428 static Instruction *FindIVIncInsertPt(std::vector<BasedUser> &UsersToProcess,
1430 if (UsersToProcess.size() == 1 &&
1431 UsersToProcess[0].isUseOfPostIncrementedValue &&
1432 L->contains(UsersToProcess[0].Inst->getParent()))
1433 return UsersToProcess[0].Inst;
1434 return L->getLoopLatch()->getTerminator();
1437 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1438 /// given users to share.
1441 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1442 std::vector<BasedUser> &UsersToProcess,
1444 const SCEV *CommonExprs,
1446 Instruction *IVIncInsertPt,
1448 SCEVExpander &PreheaderRewriter) {
1449 DEBUG(errs() << " Inserting new PHI:\n");
1451 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1452 Stride, IVIncInsertPt, L,
1455 // Remember this in case a later stride is multiple of this.
1456 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1458 // All the users will share this new IV.
1459 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1460 UsersToProcess[i].Phi = Phi;
1462 DEBUG(errs() << " IV=");
1463 DEBUG(WriteAsOperand(errs(), Phi, /*PrintType=*/false));
1464 DEBUG(errs() << "\n");
1467 /// PrepareToStrengthReduceFromSmallerStride - Prepare for the given users to
1468 /// reuse an induction variable with a stride that is a factor of the current
1469 /// induction variable.
1472 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1473 std::vector<BasedUser> &UsersToProcess,
1475 const IVExpr &ReuseIV,
1476 Instruction *PreInsertPt) {
1477 DEBUG(errs() << " Rewriting in terms of existing IV of STRIDE "
1478 << *ReuseIV.Stride << " and BASE " << *ReuseIV.Base << "\n");
1480 // All the users will share the reused IV.
1481 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1482 UsersToProcess[i].Phi = ReuseIV.PHI;
1484 Constant *C = dyn_cast<Constant>(CommonBaseV);
1486 (!C->isNullValue() &&
1487 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1489 // We want the common base emitted into the preheader! This is just
1490 // using cast as a copy so BitCast (no-op cast) is appropriate
1491 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1492 "commonbase", PreInsertPt);
1495 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1496 const Type *AccessTy,
1497 std::vector<BasedUser> &UsersToProcess,
1498 const TargetLowering *TLI) {
1499 SmallVector<Instruction*, 16> AddrModeInsts;
1500 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1501 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1503 ExtAddrMode AddrMode =
1504 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1505 AccessTy, UsersToProcess[i].Inst,
1506 AddrModeInsts, *TLI);
1507 if (GV && GV != AddrMode.BaseGV)
1509 if (Offset && !AddrMode.BaseOffs)
1510 // FIXME: How to accurate check it's immediate offset is folded.
1512 AddrModeInsts.clear();
1517 /// StrengthReduceIVUsersOfStride - Strength reduce all of the users of a single
1518 /// stride of IV. All of the users may have different starting values, and this
1519 /// may not be the only stride.
1520 void LoopStrengthReduce::StrengthReduceIVUsersOfStride(const SCEV *const &Stride,
1521 IVUsersOfOneStride &Uses,
1523 // If all the users are moved to another stride, then there is nothing to do.
1524 if (Uses.Users.empty())
1527 // Keep track if every use in UsersToProcess is an address. If they all are,
1528 // we may be able to rewrite the entire collection of them in terms of a
1529 // smaller-stride IV.
1530 bool AllUsesAreAddresses = true;
1532 // Keep track if every use of a single stride is outside the loop. If so,
1533 // we want to be more aggressive about reusing a smaller-stride IV; a
1534 // multiply outside the loop is better than another IV inside. Well, usually.
1535 bool AllUsesAreOutsideLoop = true;
1537 // Transform our list of users and offsets to a bit more complex table. In
1538 // this new vector, each 'BasedUser' contains 'Base' the base of the
1539 // strided accessas well as the old information from Uses. We progressively
1540 // move information from the Base field to the Imm field, until we eventually
1541 // have the full access expression to rewrite the use.
1542 std::vector<BasedUser> UsersToProcess;
1543 const SCEV *CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1544 AllUsesAreOutsideLoop,
1547 // Sort the UsersToProcess array so that users with common bases are
1548 // next to each other.
1549 SortUsersToProcess(UsersToProcess);
1551 // If we managed to find some expressions in common, we'll need to carry
1552 // their value in a register and add it in for each use. This will take up
1553 // a register operand, which potentially restricts what stride values are
1555 bool HaveCommonExprs = !CommonExprs->isZero();
1556 const Type *ReplacedTy = CommonExprs->getType();
1558 // If all uses are addresses, consider sinking the immediate part of the
1559 // common expression back into uses if they can fit in the immediate fields.
1560 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1561 const SCEV *NewCommon = CommonExprs;
1562 const SCEV *Imm = SE->getIntegerSCEV(0, ReplacedTy);
1563 MoveImmediateValues(TLI, Type::getVoidTy(
1564 L->getLoopPreheader()->getContext()),
1565 NewCommon, Imm, true, L, SE);
1566 if (!Imm->isZero()) {
1569 // If the immediate part of the common expression is a GV, check if it's
1570 // possible to fold it into the target addressing mode.
1571 GlobalValue *GV = 0;
1572 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
1573 GV = dyn_cast<GlobalValue>(SU->getValue());
1575 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
1576 Offset = SC->getValue()->getSExtValue();
1578 // Pass VoidTy as the AccessTy to be conservative, because
1579 // there could be multiple access types among all the uses.
1580 DoSink = IsImmFoldedIntoAddrMode(GV, Offset,
1581 Type::getVoidTy(L->getLoopPreheader()->getContext()),
1582 UsersToProcess, TLI);
1585 DEBUG(errs() << " Sinking " << *Imm << " back down into uses\n");
1586 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1587 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1588 CommonExprs = NewCommon;
1589 HaveCommonExprs = !CommonExprs->isZero();
1595 // Now that we know what we need to do, insert the PHI node itself.
1597 DEBUG(errs() << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1599 << " Common base: " << *CommonExprs << "\n");
1601 SCEVExpander Rewriter(*SE);
1602 SCEVExpander PreheaderRewriter(*SE);
1604 BasicBlock *Preheader = L->getLoopPreheader();
1605 Instruction *PreInsertPt = Preheader->getTerminator();
1606 BasicBlock *LatchBlock = L->getLoopLatch();
1607 Instruction *IVIncInsertPt = LatchBlock->getTerminator();
1609 Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
1611 const SCEV *RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1612 IVExpr ReuseIV(SE->getIntegerSCEV(0,
1613 Type::getInt32Ty(Preheader->getContext())),
1614 SE->getIntegerSCEV(0,
1615 Type::getInt32Ty(Preheader->getContext())),
1618 // Choose a strength-reduction strategy and prepare for it by creating
1619 // the necessary PHIs and adjusting the bookkeeping.
1620 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1621 AllUsesAreAddresses, Stride)) {
1622 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1625 // Emit the initial base value into the loop preheader.
1626 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1629 // If all uses are addresses, check if it is possible to reuse an IV. The
1630 // new IV must have a stride that is a multiple of the old stride; the
1631 // multiple must be a number that can be encoded in the scale field of the
1632 // target addressing mode; and we must have a valid instruction after this
1633 // substitution, including the immediate field, if any.
1634 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1635 AllUsesAreOutsideLoop,
1636 Stride, ReuseIV, ReplacedTy,
1638 if (!RewriteFactor->isZero())
1639 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1640 ReuseIV, PreInsertPt);
1642 IVIncInsertPt = FindIVIncInsertPt(UsersToProcess, L);
1643 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1644 CommonBaseV, IVIncInsertPt,
1645 L, PreheaderRewriter);
1649 // Process all the users now, replacing their strided uses with
1650 // strength-reduced forms. This outer loop handles all bases, the inner
1651 // loop handles all users of a particular base.
1652 while (!UsersToProcess.empty()) {
1653 const SCEV *Base = UsersToProcess.back().Base;
1654 Instruction *Inst = UsersToProcess.back().Inst;
1656 // Emit the code for Base into the preheader.
1658 if (!Base->isZero()) {
1659 BaseV = PreheaderRewriter.expandCodeFor(Base, 0, PreInsertPt);
1661 DEBUG(errs() << " INSERTING code for BASE = " << *Base << ":");
1662 if (BaseV->hasName())
1663 DEBUG(errs() << " Result value name = %" << BaseV->getName());
1664 DEBUG(errs() << "\n");
1666 // If BaseV is a non-zero constant, make sure that it gets inserted into
1667 // the preheader, instead of being forward substituted into the uses. We
1668 // do this by forcing a BitCast (noop cast) to be inserted into the
1669 // preheader in this case.
1670 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false) &&
1671 isa<Constant>(BaseV)) {
1672 // We want this constant emitted into the preheader! This is just
1673 // using cast as a copy so BitCast (no-op cast) is appropriate
1674 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1679 // Emit the code to add the immediate offset to the Phi value, just before
1680 // the instructions that we identified as using this stride and base.
1682 // FIXME: Use emitted users to emit other users.
1683 BasedUser &User = UsersToProcess.back();
1685 DEBUG(errs() << " Examining ");
1686 if (User.isUseOfPostIncrementedValue)
1687 DEBUG(errs() << "postinc");
1689 DEBUG(errs() << "preinc");
1690 DEBUG(errs() << " use ");
1691 DEBUG(WriteAsOperand(errs(), UsersToProcess.back().OperandValToReplace,
1692 /*PrintType=*/false));
1693 DEBUG(errs() << " in Inst: " << *User.Inst);
1695 // If this instruction wants to use the post-incremented value, move it
1696 // after the post-inc and use its value instead of the PHI.
1697 Value *RewriteOp = User.Phi;
1698 if (User.isUseOfPostIncrementedValue) {
1699 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1700 // If this user is in the loop, make sure it is the last thing in the
1701 // loop to ensure it is dominated by the increment. In case it's the
1702 // only use of the iv, the increment instruction is already before the
1704 if (L->contains(User.Inst->getParent()) && User.Inst != IVIncInsertPt)
1705 User.Inst->moveBefore(IVIncInsertPt);
1708 const SCEV *RewriteExpr = SE->getUnknown(RewriteOp);
1710 if (SE->getEffectiveSCEVType(RewriteOp->getType()) !=
1711 SE->getEffectiveSCEVType(ReplacedTy)) {
1712 assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1713 SE->getTypeSizeInBits(ReplacedTy) &&
1714 "Unexpected widening cast!");
1715 RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1718 // If we had to insert new instructions for RewriteOp, we have to
1719 // consider that they may not have been able to end up immediately
1720 // next to RewriteOp, because non-PHI instructions may never precede
1721 // PHI instructions in a block. In this case, remember where the last
1722 // instruction was inserted so that if we're replacing a different
1723 // PHI node, we can use the later point to expand the final
1725 Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
1726 if (RewriteOp == User.Phi) NewBasePt = 0;
1728 // Clear the SCEVExpander's expression map so that we are guaranteed
1729 // to have the code emitted where we expect it.
1732 // If we are reusing the iv, then it must be multiplied by a constant
1733 // factor to take advantage of the addressing mode scale component.
1734 if (!RewriteFactor->isZero()) {
1735 // If we're reusing an IV with a nonzero base (currently this happens
1736 // only when all reuses are outside the loop) subtract that base here.
1737 // The base has been used to initialize the PHI node but we don't want
1739 if (!ReuseIV.Base->isZero()) {
1740 const SCEV *typedBase = ReuseIV.Base;
1741 if (SE->getEffectiveSCEVType(RewriteExpr->getType()) !=
1742 SE->getEffectiveSCEVType(ReuseIV.Base->getType())) {
1743 // It's possible the original IV is a larger type than the new IV,
1744 // in which case we have to truncate the Base. We checked in
1745 // RequiresTypeConversion that this is valid.
1746 assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1747 SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
1748 "Unexpected lengthening conversion!");
1749 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1750 RewriteExpr->getType());
1752 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1755 // Multiply old variable, with base removed, by new scale factor.
1756 RewriteExpr = SE->getMulExpr(RewriteFactor,
1759 // The common base is emitted in the loop preheader. But since we
1760 // are reusing an IV, it has not been used to initialize the PHI node.
1761 // Add it to the expression used to rewrite the uses.
1762 // When this use is outside the loop, we earlier subtracted the
1763 // common base, and are adding it back here. Use the same expression
1764 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1765 if (!CommonExprs->isZero()) {
1766 if (L->contains(User.Inst->getParent()))
1767 RewriteExpr = SE->getAddExpr(RewriteExpr,
1768 SE->getUnknown(CommonBaseV));
1770 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1774 // Now that we know what we need to do, insert code before User for the
1775 // immediate and any loop-variant expressions.
1777 // Add BaseV to the PHI value if needed.
1778 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1780 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1781 Rewriter, L, this, *LI,
1784 // Mark old value we replaced as possibly dead, so that it is eliminated
1785 // if we just replaced the last use of that value.
1786 DeadInsts.push_back(User.OperandValToReplace);
1788 UsersToProcess.pop_back();
1791 // If there are any more users to process with the same base, process them
1792 // now. We sorted by base above, so we just have to check the last elt.
1793 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1794 // TODO: Next, find out which base index is the most common, pull it out.
1797 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1798 // different starting values, into different PHIs.
1801 void LoopStrengthReduce::StrengthReduceIVUsers(Loop *L) {
1802 // Note: this processes each stride/type pair individually. All users
1803 // passed into StrengthReduceIVUsersOfStride have the same type AND stride.
1804 // Also, note that we iterate over IVUsesByStride indirectly by using
1805 // StrideOrder. This extra layer of indirection makes the ordering of
1806 // strides deterministic - not dependent on map order.
1807 for (unsigned Stride = 0, e = IU->StrideOrder.size(); Stride != e; ++Stride) {
1808 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
1809 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
1810 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
1811 // FIXME: Generalize to non-affine IV's.
1812 if (!SI->first->isLoopInvariant(L))
1814 StrengthReduceIVUsersOfStride(SI->first, *SI->second, L);
1818 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1819 /// set the IV user and stride information and return true, otherwise return
1821 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
1822 const SCEV* &CondStride) {
1823 for (unsigned Stride = 0, e = IU->StrideOrder.size();
1824 Stride != e && !CondUse; ++Stride) {
1825 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
1826 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
1827 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
1829 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1830 E = SI->second->Users.end(); UI != E; ++UI)
1831 if (UI->getUser() == Cond) {
1832 // NOTE: we could handle setcc instructions with multiple uses here, but
1833 // InstCombine does it as well for simple uses, it's not clear that it
1834 // occurs enough in real life to handle.
1836 CondStride = SI->first;
1844 // Constant strides come first which in turns are sorted by their absolute
1845 // values. If absolute values are the same, then positive strides comes first.
1847 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1848 struct StrideCompare {
1849 const ScalarEvolution *SE;
1850 explicit StrideCompare(const ScalarEvolution *se) : SE(se) {}
1852 bool operator()(const SCEV *const &LHS, const SCEV *const &RHS) {
1853 const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1854 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1856 int64_t LV = LHSC->getValue()->getSExtValue();
1857 int64_t RV = RHSC->getValue()->getSExtValue();
1858 uint64_t ALV = (LV < 0) ? -LV : LV;
1859 uint64_t ARV = (RV < 0) ? -RV : RV;
1867 // If it's the same value but different type, sort by bit width so
1868 // that we emit larger induction variables before smaller
1869 // ones, letting the smaller be re-written in terms of larger ones.
1870 return SE->getTypeSizeInBits(RHS->getType()) <
1871 SE->getTypeSizeInBits(LHS->getType());
1873 return LHSC && !RHSC;
1878 /// ChangeCompareStride - If a loop termination compare instruction is the
1879 /// only use of its stride, and the compaison is against a constant value,
1880 /// try eliminate the stride by moving the compare instruction to another
1881 /// stride and change its constant operand accordingly. e.g.
1887 /// if (v2 < 10) goto loop
1892 /// if (v1 < 30) goto loop
1893 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
1894 IVStrideUse* &CondUse,
1895 const SCEV* &CondStride,
1897 // If there's only one stride in the loop, there's nothing to do here.
1898 if (IU->StrideOrder.size() < 2)
1900 // If there are other users of the condition's stride, don't bother
1901 // trying to change the condition because the stride will still
1903 std::map<const SCEV *, IVUsersOfOneStride *>::iterator I =
1904 IU->IVUsesByStride.find(CondStride);
1905 if (I == IU->IVUsesByStride.end())
1907 if (I->second->Users.size() > 1) {
1908 for (ilist<IVStrideUse>::iterator II = I->second->Users.begin(),
1909 EE = I->second->Users.end(); II != EE; ++II) {
1910 if (II->getUser() == Cond)
1912 if (!isInstructionTriviallyDead(II->getUser()))
1916 // Only handle constant strides for now.
1917 const SCEVConstant *SC = dyn_cast<SCEVConstant>(CondStride);
1918 if (!SC) return Cond;
1920 ICmpInst::Predicate Predicate = Cond->getPredicate();
1921 int64_t CmpSSInt = SC->getValue()->getSExtValue();
1922 unsigned BitWidth = SE->getTypeSizeInBits(CondStride->getType());
1923 uint64_t SignBit = 1ULL << (BitWidth-1);
1924 const Type *CmpTy = Cond->getOperand(0)->getType();
1925 const Type *NewCmpTy = NULL;
1926 unsigned TyBits = SE->getTypeSizeInBits(CmpTy);
1927 unsigned NewTyBits = 0;
1928 const SCEV *NewStride = NULL;
1929 Value *NewCmpLHS = NULL;
1930 Value *NewCmpRHS = NULL;
1932 const SCEV *NewOffset = SE->getIntegerSCEV(0, CmpTy);
1934 if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
1935 int64_t CmpVal = C->getValue().getSExtValue();
1937 // Check the relevant induction variable for conformance to
1939 const SCEV *IV = SE->getSCEV(Cond->getOperand(0));
1940 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1941 if (!AR || !AR->isAffine())
1944 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
1945 // Check stride constant and the comparision constant signs to detect
1948 if ((StartC->getValue()->getSExtValue() < CmpVal && CmpSSInt < 0) ||
1949 (StartC->getValue()->getSExtValue() > CmpVal && CmpSSInt > 0))
1952 // More restrictive check for the other cases.
1953 if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
1957 // Look for a suitable stride / iv as replacement.
1958 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
1959 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
1960 IU->IVUsesByStride.find(IU->StrideOrder[i]);
1961 if (!isa<SCEVConstant>(SI->first) || SI->second->Users.empty())
1963 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1964 if (SSInt == CmpSSInt ||
1965 abs64(SSInt) < abs64(CmpSSInt) ||
1966 (SSInt % CmpSSInt) != 0)
1969 Scale = SSInt / CmpSSInt;
1970 int64_t NewCmpVal = CmpVal * Scale;
1972 // If old icmp value fits in icmp immediate field, but the new one doesn't
1973 // try something else.
1975 TLI->isLegalICmpImmediate(CmpVal) &&
1976 !TLI->isLegalICmpImmediate(NewCmpVal))
1979 APInt Mul = APInt(BitWidth*2, CmpVal, true);
1980 Mul = Mul * APInt(BitWidth*2, Scale, true);
1981 // Check for overflow.
1982 if (!Mul.isSignedIntN(BitWidth))
1984 // Check for overflow in the stride's type too.
1985 if (!Mul.isSignedIntN(SE->getTypeSizeInBits(SI->first->getType())))
1988 // Watch out for overflow.
1989 if (ICmpInst::isSigned(Predicate) &&
1990 (CmpVal & SignBit) != (NewCmpVal & SignBit))
1993 // Pick the best iv to use trying to avoid a cast.
1995 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1996 E = SI->second->Users.end(); UI != E; ++UI) {
1997 Value *Op = UI->getOperandValToReplace();
1999 // If the IVStrideUse implies a cast, check for an actual cast which
2000 // can be used to find the original IV expression.
2001 if (SE->getEffectiveSCEVType(Op->getType()) !=
2002 SE->getEffectiveSCEVType(SI->first->getType())) {
2003 CastInst *CI = dyn_cast<CastInst>(Op);
2004 // If it's not a simple cast, it's complicated.
2007 // If it's a cast from a type other than the stride type,
2008 // it's complicated.
2009 if (CI->getOperand(0)->getType() != SI->first->getType())
2011 // Ok, we found the IV expression in the stride's type.
2012 Op = CI->getOperand(0);
2016 if (NewCmpLHS->getType() == CmpTy)
2022 NewCmpTy = NewCmpLHS->getType();
2023 NewTyBits = SE->getTypeSizeInBits(NewCmpTy);
2024 const Type *NewCmpIntTy = IntegerType::get(Cond->getContext(), NewTyBits);
2025 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
2026 // Check if it is possible to rewrite it using
2027 // an iv / stride of a smaller integer type.
2028 unsigned Bits = NewTyBits;
2029 if (ICmpInst::isSigned(Predicate))
2031 uint64_t Mask = (1ULL << Bits) - 1;
2032 if (((uint64_t)NewCmpVal & Mask) != (uint64_t)NewCmpVal)
2036 // Don't rewrite if use offset is non-constant and the new type is
2037 // of a different type.
2038 // FIXME: too conservative?
2039 if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->getOffset()))
2043 bool AllUsesAreAddresses = true;
2044 bool AllUsesAreOutsideLoop = true;
2045 std::vector<BasedUser> UsersToProcess;
2046 const SCEV *CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
2047 AllUsesAreAddresses,
2048 AllUsesAreOutsideLoop,
2050 // Avoid rewriting the compare instruction with an iv of new stride
2051 // if it's likely the new stride uses will be rewritten using the
2052 // stride of the compare instruction.
2053 if (AllUsesAreAddresses &&
2054 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
2058 // Avoid rewriting the compare instruction with an iv which has
2059 // implicit extension or truncation built into it.
2060 // TODO: This is over-conservative.
2061 if (SE->getTypeSizeInBits(CondUse->getOffset()->getType()) != TyBits)
2064 // If scale is negative, use swapped predicate unless it's testing
2066 if (Scale < 0 && !Cond->isEquality())
2067 Predicate = ICmpInst::getSwappedPredicate(Predicate);
2069 NewStride = IU->StrideOrder[i];
2070 if (!isa<PointerType>(NewCmpTy))
2071 NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
2073 Constant *CI = ConstantInt::get(NewCmpIntTy, NewCmpVal);
2074 NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
2076 NewOffset = TyBits == NewTyBits
2077 ? SE->getMulExpr(CondUse->getOffset(),
2078 SE->getConstant(CmpTy, Scale))
2079 : SE->getConstant(NewCmpIntTy,
2080 cast<SCEVConstant>(CondUse->getOffset())->getValue()
2081 ->getSExtValue()*Scale);
2086 // Forgo this transformation if it the increment happens to be
2087 // unfortunately positioned after the condition, and the condition
2088 // has multiple uses which prevent it from being moved immediately
2089 // before the branch. See
2090 // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2091 // for an example of this situation.
2092 if (!Cond->hasOneUse()) {
2093 for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2100 // Create a new compare instruction using new stride / iv.
2101 ICmpInst *OldCond = Cond;
2102 // Insert new compare instruction.
2103 Cond = new ICmpInst(OldCond, Predicate, NewCmpLHS, NewCmpRHS,
2104 L->getHeader()->getName() + ".termcond");
2106 DEBUG(errs() << " Change compare stride in Inst " << *OldCond);
2107 DEBUG(errs() << " to " << *Cond << '\n');
2109 // Remove the old compare instruction. The old indvar is probably dead too.
2110 DeadInsts.push_back(CondUse->getOperandValToReplace());
2111 OldCond->replaceAllUsesWith(Cond);
2112 OldCond->eraseFromParent();
2114 IU->IVUsesByStride[NewStride]->addUser(NewOffset, Cond, NewCmpLHS);
2115 CondUse = &IU->IVUsesByStride[NewStride]->Users.back();
2116 CondStride = NewStride;
2124 /// OptimizeMax - Rewrite the loop's terminating condition if it uses
2125 /// a max computation.
2127 /// This is a narrow solution to a specific, but acute, problem. For loops
2133 /// } while (++i < n);
2135 /// the trip count isn't just 'n', because 'n' might not be positive. And
2136 /// unfortunately this can come up even for loops where the user didn't use
2137 /// a C do-while loop. For example, seemingly well-behaved top-test loops
2138 /// will commonly be lowered like this:
2144 /// } while (++i < n);
2147 /// and then it's possible for subsequent optimization to obscure the if
2148 /// test in such a way that indvars can't find it.
2150 /// When indvars can't find the if test in loops like this, it creates a
2151 /// max expression, which allows it to give the loop a canonical
2152 /// induction variable:
2155 /// max = n < 1 ? 1 : n;
2158 /// } while (++i != max);
2160 /// Canonical induction variables are necessary because the loop passes
2161 /// are designed around them. The most obvious example of this is the
2162 /// LoopInfo analysis, which doesn't remember trip count values. It
2163 /// expects to be able to rediscover the trip count each time it is
2164 /// needed, and it does this using a simple analyis that only succeeds if
2165 /// the loop has a canonical induction variable.
2167 /// However, when it comes time to generate code, the maximum operation
2168 /// can be quite costly, especially if it's inside of an outer loop.
2170 /// This function solves this problem by detecting this type of loop and
2171 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2172 /// the instructions for the maximum computation.
2174 ICmpInst *LoopStrengthReduce::OptimizeMax(Loop *L, ICmpInst *Cond,
2175 IVStrideUse* &CondUse) {
2176 // Check that the loop matches the pattern we're looking for.
2177 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2178 Cond->getPredicate() != CmpInst::ICMP_NE)
2181 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2182 if (!Sel || !Sel->hasOneUse()) return Cond;
2184 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2185 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2187 const SCEV *One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2189 // Add one to the backedge-taken count to get the trip count.
2190 const SCEV *IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
2192 // Check for a max calculation that matches the pattern.
2193 if (!isa<SCEVSMaxExpr>(IterationCount) && !isa<SCEVUMaxExpr>(IterationCount))
2195 const SCEVNAryExpr *Max = cast<SCEVNAryExpr>(IterationCount);
2196 if (Max != SE->getSCEV(Sel)) return Cond;
2198 // To handle a max with more than two operands, this optimization would
2199 // require additional checking and setup.
2200 if (Max->getNumOperands() != 2)
2203 const SCEV *MaxLHS = Max->getOperand(0);
2204 const SCEV *MaxRHS = Max->getOperand(1);
2205 if (!MaxLHS || MaxLHS != One) return Cond;
2207 // Check the relevant induction variable for conformance to
2209 const SCEV *IV = SE->getSCEV(Cond->getOperand(0));
2210 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2211 if (!AR || !AR->isAffine() ||
2212 AR->getStart() != One ||
2213 AR->getStepRecurrence(*SE) != One)
2216 assert(AR->getLoop() == L &&
2217 "Loop condition operand is an addrec in a different loop!");
2219 // Check the right operand of the select, and remember it, as it will
2220 // be used in the new comparison instruction.
2222 if (SE->getSCEV(Sel->getOperand(1)) == MaxRHS)
2223 NewRHS = Sel->getOperand(1);
2224 else if (SE->getSCEV(Sel->getOperand(2)) == MaxRHS)
2225 NewRHS = Sel->getOperand(2);
2226 if (!NewRHS) return Cond;
2228 // Determine the new comparison opcode. It may be signed or unsigned,
2229 // and the original comparison may be either equality or inequality.
2230 CmpInst::Predicate Pred =
2231 isa<SCEVSMaxExpr>(Max) ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
2232 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2233 Pred = CmpInst::getInversePredicate(Pred);
2235 // Ok, everything looks ok to change the condition into an SLT or SGE and
2236 // delete the max calculation.
2238 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
2240 // Delete the max calculation instructions.
2241 Cond->replaceAllUsesWith(NewCond);
2242 CondUse->setUser(NewCond);
2243 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2244 Cond->eraseFromParent();
2245 Sel->eraseFromParent();
2246 if (Cmp->use_empty())
2247 Cmp->eraseFromParent();
2251 /// OptimizeShadowIV - If IV is used in a int-to-float cast
2252 /// inside the loop then try to eliminate the cast opeation.
2253 void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2255 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2256 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2259 for (unsigned Stride = 0, e = IU->StrideOrder.size(); Stride != e;
2261 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
2262 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2263 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2264 if (!isa<SCEVConstant>(SI->first))
2267 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
2268 E = SI->second->Users.end(); UI != E; /* empty */) {
2269 ilist<IVStrideUse>::iterator CandidateUI = UI;
2271 Instruction *ShadowUse = CandidateUI->getUser();
2272 const Type *DestTy = NULL;
2274 /* If shadow use is a int->float cast then insert a second IV
2275 to eliminate this cast.
2277 for (unsigned i = 0; i < n; ++i)
2283 for (unsigned i = 0; i < n; ++i, ++d)
2286 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
2287 DestTy = UCast->getDestTy();
2288 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
2289 DestTy = SCast->getDestTy();
2290 if (!DestTy) continue;
2293 // If target does not support DestTy natively then do not apply
2294 // this transformation.
2295 EVT DVT = TLI->getValueType(DestTy);
2296 if (!TLI->isTypeLegal(DVT)) continue;
2299 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2301 if (PH->getNumIncomingValues() != 2) continue;
2303 const Type *SrcTy = PH->getType();
2304 int Mantissa = DestTy->getFPMantissaWidth();
2305 if (Mantissa == -1) continue;
2306 if ((int)SE->getTypeSizeInBits(SrcTy) > Mantissa)
2309 unsigned Entry, Latch;
2310 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2318 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2319 if (!Init) continue;
2320 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2322 BinaryOperator *Incr =
2323 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2324 if (!Incr) continue;
2325 if (Incr->getOpcode() != Instruction::Add
2326 && Incr->getOpcode() != Instruction::Sub)
2329 /* Initialize new IV, double d = 0.0 in above example. */
2330 ConstantInt *C = NULL;
2331 if (Incr->getOperand(0) == PH)
2332 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2333 else if (Incr->getOperand(1) == PH)
2334 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2340 // Ignore negative constants, as the code below doesn't handle them
2341 // correctly. TODO: Remove this restriction.
2342 if (!C->getValue().isStrictlyPositive()) continue;
2344 /* Add new PHINode. */
2345 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2347 /* create new increment. '++d' in above example. */
2348 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2349 BinaryOperator *NewIncr =
2350 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
2351 Instruction::FAdd : Instruction::FSub,
2352 NewPH, CFP, "IV.S.next.", Incr);
2354 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2355 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2357 /* Remove cast operation */
2358 ShadowUse->replaceAllUsesWith(NewPH);
2359 ShadowUse->eraseFromParent();
2366 /// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2367 /// uses in the loop, look to see if we can eliminate some, in favor of using
2368 /// common indvars for the different uses.
2369 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2370 // TODO: implement optzns here.
2372 OptimizeShadowIV(L);
2375 bool LoopStrengthReduce::StrideMightBeShared(const SCEV* Stride, Loop *L,
2377 int64_t SInt = cast<SCEVConstant>(Stride)->getValue()->getSExtValue();
2378 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
2379 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
2380 IU->IVUsesByStride.find(IU->StrideOrder[i]);
2381 const SCEV *Share = SI->first;
2382 if (!isa<SCEVConstant>(SI->first) || Share == Stride)
2384 int64_t SSInt = cast<SCEVConstant>(Share)->getValue()->getSExtValue();
2386 return true; // This can definitely be reused.
2387 if (unsigned(abs64(SSInt)) < SInt || (SSInt % SInt) != 0)
2389 int64_t Scale = SSInt / SInt;
2390 bool AllUsesAreAddresses = true;
2391 bool AllUsesAreOutsideLoop = true;
2392 std::vector<BasedUser> UsersToProcess;
2393 const SCEV *CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
2394 AllUsesAreAddresses,
2395 AllUsesAreOutsideLoop,
2397 if (AllUsesAreAddresses &&
2398 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess)) {
2401 // Any pre-inc iv use?
2402 IVUsersOfOneStride &StrideUses = *IU->IVUsesByStride[Share];
2403 for (ilist<IVStrideUse>::iterator I = StrideUses.Users.begin(),
2404 E = StrideUses.Users.end(); I != E; ++I) {
2405 if (!I->isUseOfPostIncrementedValue())
2413 /// isUsedByExitBranch - Return true if icmp is used by a loop terminating
2414 /// conditional branch or it's and / or with other conditions before being used
2415 /// as the condition.
2416 static bool isUsedByExitBranch(ICmpInst *Cond, Loop *L) {
2417 BasicBlock *CondBB = Cond->getParent();
2418 if (!L->isLoopExiting(CondBB))
2420 BranchInst *TermBr = dyn_cast<BranchInst>(CondBB->getTerminator());
2421 if (!TermBr || !TermBr->isConditional())
2424 Value *User = *Cond->use_begin();
2425 Instruction *UserInst = dyn_cast<Instruction>(User);
2427 (UserInst->getOpcode() == Instruction::And ||
2428 UserInst->getOpcode() == Instruction::Or)) {
2429 if (!UserInst->hasOneUse() || UserInst->getParent() != CondBB)
2431 User = *User->use_begin();
2432 UserInst = dyn_cast<Instruction>(User);
2434 return User == TermBr;
2437 static bool ShouldCountToZero(ICmpInst *Cond, IVStrideUse* &CondUse,
2438 ScalarEvolution *SE, Loop *L,
2439 const TargetLowering *TLI = 0) {
2440 if (!L->contains(Cond->getParent()))
2443 if (!isa<SCEVConstant>(CondUse->getOffset()))
2446 // Handle only tests for equality for the moment.
2447 if (!Cond->isEquality() || !Cond->hasOneUse())
2449 if (!isUsedByExitBranch(Cond, L))
2452 Value *CondOp0 = Cond->getOperand(0);
2453 const SCEV *IV = SE->getSCEV(CondOp0);
2454 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2455 if (!AR || !AR->isAffine())
2458 const SCEVConstant *SC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
2459 if (!SC || SC->getValue()->getSExtValue() < 0)
2460 // If it's already counting down, don't do anything.
2463 // If the RHS of the comparison is not an loop invariant, the rewrite
2464 // cannot be done. Also bail out if it's already comparing against a zero.
2465 // If we are checking this before cmp stride optimization, check if it's
2466 // comparing against a already legal immediate.
2467 Value *RHS = Cond->getOperand(1);
2468 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS);
2469 if (!L->isLoopInvariant(RHS) ||
2470 (RHSC && RHSC->isZero()) ||
2471 (RHSC && TLI && TLI->isLegalICmpImmediate(RHSC->getSExtValue())))
2474 // Make sure the IV is only used for counting. Value may be preinc or
2475 // postinc; 2 uses in either case.
2476 if (!CondOp0->hasNUses(2))
2482 /// OptimizeLoopTermCond - Change loop terminating condition to use the
2483 /// postinc iv when possible.
2484 void LoopStrengthReduce::OptimizeLoopTermCond(Loop *L) {
2485 // Finally, get the terminating condition for the loop if possible. If we
2486 // can, we want to change it to use a post-incremented version of its
2487 // induction variable, to allow coalescing the live ranges for the IV into
2488 // one register value.
2489 BasicBlock *LatchBlock = L->getLoopLatch();
2490 BasicBlock *ExitingBlock = L->getExitingBlock();
2493 // Multiple exits, just look at the exit in the latch block if there is one.
2494 ExitingBlock = LatchBlock;
2495 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2498 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2501 // Search IVUsesByStride to find Cond's IVUse if there is one.
2502 IVStrideUse *CondUse = 0;
2503 const SCEV *CondStride = 0;
2504 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2505 if (!FindIVUserForCond(Cond, CondUse, CondStride))
2508 bool UsePostInc = true;
2509 if (ExitingBlock != LatchBlock) {
2510 if (Cond->hasOneUse()) {
2511 // See below, we don't want the condition to be cloned.
2513 // If exiting block is the latch block, we know it's safe and profitable
2514 // to transform the icmp to use post-inc iv. Otherwise do so only if it
2515 // would not reuse another iv and its iv would be reused by other uses.
2516 // We are optimizing for the case where the icmp is the only use of the
2518 IVUsersOfOneStride &StrideUses = *IU->IVUsesByStride[CondStride];
2519 for (ilist<IVStrideUse>::iterator I = StrideUses.Users.begin(),
2520 E = StrideUses.Users.end(); I != E; ++I) {
2521 if (I->getUser() == Cond)
2523 if (!I->isUseOfPostIncrementedValue()) {
2530 // If iv for the stride might be shared and any of the users use pre-inc iv
2531 // might be used, then it's not safe to use post-inc iv.
2533 isa<SCEVConstant>(CondStride) &&
2534 StrideMightBeShared(CondStride, L, true))
2538 // If the trip count is computed in terms of a max (due to ScalarEvolution
2539 // being unable to find a sufficient guard, for example), change the loop
2540 // comparison to use SLT or ULT instead of NE.
2541 Cond = OptimizeMax(L, Cond, CondUse);
2543 // If possible, change stride and operands of the compare instruction to
2544 // eliminate one stride. However, avoid rewriting the compare instruction with
2545 // an iv of new stride if it's likely the new stride uses will be rewritten
2546 // using the stride of the compare instruction.
2547 if (ExitingBlock == LatchBlock && isa<SCEVConstant>(CondStride)) {
2548 // If the condition stride is a constant and it's the only use, we might
2549 // want to optimize it first by turning it to count toward zero.
2550 if (!StrideMightBeShared(CondStride, L, false) &&
2551 !ShouldCountToZero(Cond, CondUse, SE, L, TLI))
2552 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
2558 // It's possible for the setcc instruction to be anywhere in the loop, and
2559 // possible for it to have multiple users. If it is not immediately before
2560 // the latch block branch, move it.
2561 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2562 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
2563 Cond->moveBefore(TermBr);
2565 // Otherwise, clone the terminating condition and insert into the loopend.
2566 Cond = cast<ICmpInst>(Cond->clone());
2567 Cond->setName(L->getHeader()->getName() + ".termcond");
2568 LatchBlock->getInstList().insert(TermBr, Cond);
2570 // Clone the IVUse, as the old use still exists!
2571 IU->IVUsesByStride[CondStride]->addUser(CondUse->getOffset(), Cond,
2572 CondUse->getOperandValToReplace());
2573 CondUse = &IU->IVUsesByStride[CondStride]->Users.back();
2577 // If we get to here, we know that we can transform the setcc instruction to
2578 // use the post-incremented version of the IV, allowing us to coalesce the
2579 // live ranges for the IV correctly.
2580 CondUse->setOffset(SE->getMinusSCEV(CondUse->getOffset(), CondStride));
2581 CondUse->setIsUseOfPostIncrementedValue(true);
2587 bool LoopStrengthReduce::OptimizeLoopCountIVOfStride(const SCEV* &Stride,
2588 IVStrideUse* &CondUse,
2590 // If the only use is an icmp of an loop exiting conditional branch, then
2591 // attempts the optimization.
2592 BasedUser User = BasedUser(*CondUse, SE);
2593 assert(isa<ICmpInst>(User.Inst) && "Expecting an ICMPInst!");
2594 ICmpInst *Cond = cast<ICmpInst>(User.Inst);
2596 // Less strict check now that compare stride optimization is done.
2597 if (!ShouldCountToZero(Cond, CondUse, SE, L))
2600 Value *CondOp0 = Cond->getOperand(0);
2601 PHINode *PHIExpr = dyn_cast<PHINode>(CondOp0);
2604 // Value tested is postinc. Find the phi node.
2605 Incr = dyn_cast<BinaryOperator>(CondOp0);
2606 // FIXME: Just use User.OperandValToReplace here?
2607 if (!Incr || Incr->getOpcode() != Instruction::Add)
2610 PHIExpr = dyn_cast<PHINode>(Incr->getOperand(0));
2613 // 1 use for preinc value, the increment.
2614 if (!PHIExpr->hasOneUse())
2617 assert(isa<PHINode>(CondOp0) &&
2618 "Unexpected loop exiting counting instruction sequence!");
2619 PHIExpr = cast<PHINode>(CondOp0);
2620 // Value tested is preinc. Find the increment.
2621 // A CmpInst is not a BinaryOperator; we depend on this.
2622 Instruction::use_iterator UI = PHIExpr->use_begin();
2623 Incr = dyn_cast<BinaryOperator>(UI);
2625 Incr = dyn_cast<BinaryOperator>(++UI);
2626 // One use for postinc value, the phi. Unnecessarily conservative?
2627 if (!Incr || !Incr->hasOneUse() || Incr->getOpcode() != Instruction::Add)
2631 // Replace the increment with a decrement.
2632 DEBUG(errs() << "LSR: Examining use ");
2633 DEBUG(WriteAsOperand(errs(), CondOp0, /*PrintType=*/false));
2634 DEBUG(errs() << " in Inst: " << *Cond << '\n');
2635 BinaryOperator *Decr = BinaryOperator::Create(Instruction::Sub,
2636 Incr->getOperand(0), Incr->getOperand(1), "tmp", Incr);
2637 Incr->replaceAllUsesWith(Decr);
2638 Incr->eraseFromParent();
2640 // Substitute endval-startval for the original startval, and 0 for the
2641 // original endval. Since we're only testing for equality this is OK even
2642 // if the computation wraps around.
2643 BasicBlock *Preheader = L->getLoopPreheader();
2644 Instruction *PreInsertPt = Preheader->getTerminator();
2645 unsigned InBlock = L->contains(PHIExpr->getIncomingBlock(0)) ? 1 : 0;
2646 Value *StartVal = PHIExpr->getIncomingValue(InBlock);
2647 Value *EndVal = Cond->getOperand(1);
2648 DEBUG(errs() << " Optimize loop counting iv to count down ["
2649 << *EndVal << " .. " << *StartVal << "]\n");
2651 // FIXME: check for case where both are constant.
2652 Constant* Zero = ConstantInt::get(Cond->getOperand(1)->getType(), 0);
2653 BinaryOperator *NewStartVal = BinaryOperator::Create(Instruction::Sub,
2654 EndVal, StartVal, "tmp", PreInsertPt);
2655 PHIExpr->setIncomingValue(InBlock, NewStartVal);
2656 Cond->setOperand(1, Zero);
2657 DEBUG(errs() << " New icmp: " << *Cond << "\n");
2659 int64_t SInt = cast<SCEVConstant>(Stride)->getValue()->getSExtValue();
2660 const SCEV *NewStride = 0;
2662 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
2663 const SCEV *OldStride = IU->StrideOrder[i];
2664 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OldStride))
2665 if (SC->getValue()->getSExtValue() == -SInt) {
2667 NewStride = OldStride;
2673 NewStride = SE->getIntegerSCEV(-SInt, Stride->getType());
2674 IU->AddUser(NewStride, CondUse->getOffset(), Cond, Cond->getOperand(0));
2675 IU->IVUsesByStride[Stride]->removeUser(CondUse);
2677 CondUse = &IU->IVUsesByStride[NewStride]->Users.back();
2685 /// OptimizeLoopCountIV - If, after all sharing of IVs, the IV used for deciding
2686 /// when to exit the loop is used only for that purpose, try to rearrange things
2687 /// so it counts down to a test against zero.
2688 bool LoopStrengthReduce::OptimizeLoopCountIV(Loop *L) {
2689 bool ThisChanged = false;
2690 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
2691 const SCEV *Stride = IU->StrideOrder[i];
2692 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
2693 IU->IVUsesByStride.find(Stride);
2694 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2695 // FIXME: Generalize to non-affine IV's.
2696 if (!SI->first->isLoopInvariant(L))
2698 // If stride is a constant and it has an icmpinst use, check if we can
2699 // optimize the loop to count down.
2700 if (isa<SCEVConstant>(Stride) && SI->second->Users.size() == 1) {
2701 Instruction *User = SI->second->Users.begin()->getUser();
2702 if (!isa<ICmpInst>(User))
2704 const SCEV *CondStride = Stride;
2705 IVStrideUse *Use = &*SI->second->Users.begin();
2706 if (!OptimizeLoopCountIVOfStride(CondStride, Use, L))
2710 // Now check if it's possible to reuse this iv for other stride uses.
2711 for (unsigned j = 0, ee = IU->StrideOrder.size(); j != ee; ++j) {
2712 const SCEV *SStride = IU->StrideOrder[j];
2713 if (SStride == CondStride)
2715 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SII =
2716 IU->IVUsesByStride.find(SStride);
2717 assert(SII != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2718 // FIXME: Generalize to non-affine IV's.
2719 if (!SII->first->isLoopInvariant(L))
2721 // FIXME: Rewrite other stride using CondStride.
2726 Changed |= ThisChanged;
2730 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
2732 IU = &getAnalysis<IVUsers>();
2733 LI = &getAnalysis<LoopInfo>();
2734 DT = &getAnalysis<DominatorTree>();
2735 SE = &getAnalysis<ScalarEvolution>();
2738 // If LoopSimplify form is not available, stay out of trouble.
2739 if (!L->getLoopPreheader() || !L->getLoopLatch())
2742 if (!IU->IVUsesByStride.empty()) {
2743 DEBUG(errs() << "\nLSR on \"" << L->getHeader()->getParent()->getName()
2747 // Sort the StrideOrder so we process larger strides first.
2748 std::stable_sort(IU->StrideOrder.begin(), IU->StrideOrder.end(),
2751 // Optimize induction variables. Some indvar uses can be transformed to use
2752 // strides that will be needed for other purposes. A common example of this
2753 // is the exit test for the loop, which can often be rewritten to use the
2754 // computation of some other indvar to decide when to terminate the loop.
2757 // Change loop terminating condition to use the postinc iv when possible
2758 // and optimize loop terminating compare. FIXME: Move this after
2759 // StrengthReduceIVUsersOfStride?
2760 OptimizeLoopTermCond(L);
2762 // FIXME: We can shrink overlarge IV's here. e.g. if the code has
2763 // computation in i64 values and the target doesn't support i64, demote
2764 // the computation to 32-bit if safe.
2766 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
2767 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2768 // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2769 // Need to be careful that IV's are all the same type. Only works for
2770 // intptr_t indvars.
2772 // IVsByStride keeps IVs for one particular loop.
2773 assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
2775 StrengthReduceIVUsers(L);
2777 // After all sharing is done, see if we can adjust the loop to test against
2778 // zero instead of counting up to a maximum. This is usually faster.
2779 OptimizeLoopCountIV(L);
2782 // We're done analyzing this loop; release all the state we built up for it.
2783 IVsByStride.clear();
2784 StrideNoReuse.clear();
2786 // Clean up after ourselves
2787 if (!DeadInsts.empty())
2788 DeleteTriviallyDeadInstructions();
2790 // At this point, it is worth checking to see if any recurrence PHIs are also
2791 // dead, so that we can remove them as well.
2792 DeleteDeadPHIs(L->getHeader());