1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs a strength reduction on array references inside loops that
11 // have as one or more of their components the loop induction variable.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "loop-reduce"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Type.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/IVUsers.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/LoopPass.h"
26 #include "llvm/Analysis/ScalarEvolutionExpander.h"
27 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ValueHandle.h"
36 #include "llvm/Target/TargetLowering.h"
40 STATISTIC(NumReduced , "Number of IV uses strength reduced");
41 STATISTIC(NumInserted, "Number of PHIs inserted");
42 STATISTIC(NumVariable, "Number of PHIs with variable strides");
43 STATISTIC(NumEliminated, "Number of strides eliminated");
44 STATISTIC(NumShadow, "Number of Shadow IVs optimized");
45 STATISTIC(NumImmSunk, "Number of common expr immediates sunk into uses");
46 STATISTIC(NumLoopCond, "Number of loop terminating conds optimized");
48 static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
56 /// IVInfo - This structure keeps track of one IV expression inserted during
57 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
58 /// well as the PHI node and increment value created for rewrite.
59 struct VISIBILITY_HIDDEN IVExpr {
64 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi)
65 : Stride(stride), Base(base), PHI(phi) {}
68 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
69 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
70 struct VISIBILITY_HIDDEN IVsOfOneStride {
71 std::vector<IVExpr> IVs;
73 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI) {
74 IVs.push_back(IVExpr(Stride, Base, PHI));
78 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
85 /// IVsByStride - Keep track of all IVs that have been inserted for a
86 /// particular stride.
87 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
89 /// StrideNoReuse - Keep track of all the strides whose ivs cannot be
90 /// reused (nor should they be rewritten to reuse other strides).
91 SmallSet<SCEVHandle, 4> StrideNoReuse;
93 /// DeadInsts - Keep track of instructions we may have made dead, so that
94 /// we can remove them after we are done working.
95 SmallVector<WeakVH, 16> DeadInsts;
97 /// TLI - Keep a pointer of a TargetLowering to consult for determining
98 /// transformation profitability.
99 const TargetLowering *TLI;
102 static char ID; // Pass ID, replacement for typeid
103 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
104 LoopPass(&ID), TLI(tli) {
107 bool runOnLoop(Loop *L, LPPassManager &LPM);
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110 // We split critical edges, so we change the CFG. However, we do update
111 // many analyses if they are around.
112 AU.addPreservedID(LoopSimplifyID);
113 AU.addPreserved<LoopInfo>();
114 AU.addPreserved<DominanceFrontier>();
115 AU.addPreserved<DominatorTree>();
117 AU.addRequiredID(LoopSimplifyID);
118 AU.addRequired<LoopInfo>();
119 AU.addRequired<DominatorTree>();
120 AU.addRequired<ScalarEvolution>();
121 AU.addPreserved<ScalarEvolution>();
122 AU.addRequired<IVUsers>();
123 AU.addPreserved<IVUsers>();
127 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
128 IVStrideUse* &CondUse,
129 const SCEVHandle* &CondStride);
131 void OptimizeIndvars(Loop *L);
132 void OptimizeLoopCountIV(Loop *L);
133 void OptimizeLoopTermCond(Loop *L);
135 /// OptimizeShadowIV - If IV is used in a int-to-float cast
136 /// inside the loop then try to eliminate the cast opeation.
137 void OptimizeShadowIV(Loop *L);
139 /// OptimizeSMax - Rewrite the loop's terminating condition
140 /// if it uses an smax computation.
141 ICmpInst *OptimizeSMax(Loop *L, ICmpInst *Cond,
142 IVStrideUse* &CondUse);
144 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
145 const SCEVHandle *&CondStride);
146 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
147 SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
148 IVExpr&, const Type*,
149 const std::vector<BasedUser>& UsersToProcess);
150 bool ValidScale(bool, int64_t,
151 const std::vector<BasedUser>& UsersToProcess);
152 bool ValidOffset(bool, int64_t, int64_t,
153 const std::vector<BasedUser>& UsersToProcess);
154 SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
155 IVUsersOfOneStride &Uses,
157 bool &AllUsesAreAddresses,
158 bool &AllUsesAreOutsideLoop,
159 std::vector<BasedUser> &UsersToProcess);
160 bool ShouldUseFullStrengthReductionMode(
161 const std::vector<BasedUser> &UsersToProcess,
163 bool AllUsesAreAddresses,
165 void PrepareToStrengthReduceFully(
166 std::vector<BasedUser> &UsersToProcess,
168 SCEVHandle CommonExprs,
170 SCEVExpander &PreheaderRewriter);
171 void PrepareToStrengthReduceFromSmallerStride(
172 std::vector<BasedUser> &UsersToProcess,
174 const IVExpr &ReuseIV,
175 Instruction *PreInsertPt);
176 void PrepareToStrengthReduceWithNewPhi(
177 std::vector<BasedUser> &UsersToProcess,
179 SCEVHandle CommonExprs,
181 Instruction *IVIncInsertPt,
183 SCEVExpander &PreheaderRewriter);
184 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
185 IVUsersOfOneStride &Uses,
187 void DeleteTriviallyDeadInstructions();
191 char LoopStrengthReduce::ID = 0;
192 static RegisterPass<LoopStrengthReduce>
193 X("loop-reduce", "Loop Strength Reduction");
195 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
196 return new LoopStrengthReduce(TLI);
199 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
200 /// specified set are trivially dead, delete them and see if this makes any of
201 /// their operands subsequently dead.
202 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
203 if (DeadInsts.empty()) return;
205 while (!DeadInsts.empty()) {
206 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.back());
207 DeadInsts.pop_back();
209 if (I == 0 || !isInstructionTriviallyDead(I))
212 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
213 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
216 DeadInsts.push_back(U);
220 I->eraseFromParent();
225 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a
226 /// subexpression that is an AddRec from a loop other than L. An outer loop
227 /// of L is OK, but not an inner loop nor a disjoint loop.
228 static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
229 // This is very common, put it first.
230 if (isa<SCEVConstant>(S))
232 if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
233 for (unsigned int i=0; i< AE->getNumOperands(); i++)
234 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
238 if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
239 if (const Loop *newLoop = AE->getLoop()) {
242 // if newLoop is an outer loop of L, this is OK.
243 if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
248 if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
249 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
250 containsAddRecFromDifferentLoop(DE->getRHS(), L);
252 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
253 // need this when it is.
254 if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
255 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
256 containsAddRecFromDifferentLoop(DE->getRHS(), L);
258 if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
259 return containsAddRecFromDifferentLoop(CE->getOperand(), L);
263 /// isAddressUse - Returns true if the specified instruction is using the
264 /// specified value as an address.
265 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
266 bool isAddress = isa<LoadInst>(Inst);
267 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
268 if (SI->getOperand(1) == OperandVal)
270 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
271 // Addressing modes can also be folded into prefetches and a variety
273 switch (II->getIntrinsicID()) {
275 case Intrinsic::prefetch:
276 case Intrinsic::x86_sse2_loadu_dq:
277 case Intrinsic::x86_sse2_loadu_pd:
278 case Intrinsic::x86_sse_loadu_ps:
279 case Intrinsic::x86_sse_storeu_ps:
280 case Intrinsic::x86_sse2_storeu_pd:
281 case Intrinsic::x86_sse2_storeu_dq:
282 case Intrinsic::x86_sse2_storel_dq:
283 if (II->getOperand(1) == OperandVal)
291 /// getAccessType - Return the type of the memory being accessed.
292 static const Type *getAccessType(const Instruction *Inst) {
293 const Type *AccessTy = Inst->getType();
294 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
295 AccessTy = SI->getOperand(0)->getType();
296 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
297 // Addressing modes can also be folded into prefetches and a variety
299 switch (II->getIntrinsicID()) {
301 case Intrinsic::x86_sse_storeu_ps:
302 case Intrinsic::x86_sse2_storeu_pd:
303 case Intrinsic::x86_sse2_storeu_dq:
304 case Intrinsic::x86_sse2_storel_dq:
305 AccessTy = II->getOperand(1)->getType();
313 /// BasedUser - For a particular base value, keep information about how we've
314 /// partitioned the expression so far.
316 /// SE - The current ScalarEvolution object.
319 /// Base - The Base value for the PHI node that needs to be inserted for
320 /// this use. As the use is processed, information gets moved from this
321 /// field to the Imm field (below). BasedUser values are sorted by this
325 /// Inst - The instruction using the induction variable.
328 /// OperandValToReplace - The operand value of Inst to replace with the
330 Value *OperandValToReplace;
332 /// isSigned - The stride (and thus also the Base) of this use may be in
333 /// a narrower type than the use itself (OperandValToReplace->getType()).
334 /// When this is the case, the isSigned field indicates whether the
335 /// IV expression should be signed-extended instead of zero-extended to
336 /// fit the type of the use.
339 /// Imm - The immediate value that should be added to the base immediately
340 /// before Inst, because it will be folded into the imm field of the
341 /// instruction. This is also sometimes used for loop-variant values that
342 /// must be added inside the loop.
345 /// Phi - The induction variable that performs the striding that
346 /// should be used for this user.
349 // isUseOfPostIncrementedValue - True if this should use the
350 // post-incremented version of this IV, not the preincremented version.
351 // This can only be set in special cases, such as the terminating setcc
352 // instruction for a loop and uses outside the loop that are dominated by
354 bool isUseOfPostIncrementedValue;
356 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
357 : SE(se), Base(IVSU.getOffset()), Inst(IVSU.getUser()),
358 OperandValToReplace(IVSU.getOperandValToReplace()),
359 isSigned(IVSU.isSigned()),
360 Imm(SE->getIntegerSCEV(0, Base->getType())),
361 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue()) {}
363 // Once we rewrite the code to insert the new IVs we want, update the
364 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
366 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
367 Instruction *InsertPt,
368 SCEVExpander &Rewriter, Loop *L, Pass *P,
370 SmallVectorImpl<WeakVH> &DeadInsts);
372 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
374 SCEVExpander &Rewriter,
375 Instruction *IP, Loop *L,
381 void BasedUser::dump() const {
382 cerr << " Base=" << *Base;
383 cerr << " Imm=" << *Imm;
384 cerr << " Inst: " << *Inst;
387 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
389 SCEVExpander &Rewriter,
390 Instruction *IP, Loop *L,
392 // Figure out where we *really* want to insert this code. In particular, if
393 // the user is inside of a loop that is nested inside of L, we really don't
394 // want to insert this expression before the user, we'd rather pull it out as
395 // many loops as possible.
396 Instruction *BaseInsertPt = IP;
398 // Figure out the most-nested loop that IP is in.
399 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
401 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
402 // the preheader of the outer-most loop where NewBase is not loop invariant.
403 if (L->contains(IP->getParent()))
404 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
405 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
406 InsertLoop = InsertLoop->getParentLoop();
409 Value *Base = Rewriter.expandCodeFor(NewBase, 0, BaseInsertPt);
411 SCEVHandle NewValSCEV = SE->getUnknown(Base);
413 // If there is no immediate value, skip the next part.
414 if (!Imm->isZero()) {
415 // If we are inserting the base and imm values in the same block, make sure
416 // to adjust the IP position if insertion reused a result.
417 if (IP == BaseInsertPt)
418 IP = Rewriter.getInsertionPoint();
420 // Always emit the immediate (if non-zero) into the same block as the user.
421 NewValSCEV = SE->getAddExpr(NewValSCEV, Imm);
425 NewValSCEV = SE->getTruncateOrSignExtend(NewValSCEV, Ty);
427 NewValSCEV = SE->getTruncateOrZeroExtend(NewValSCEV, Ty);
429 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
433 // Once we rewrite the code to insert the new IVs we want, update the
434 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
435 // to it. NewBasePt is the last instruction which contributes to the
436 // value of NewBase in the case that it's a diffferent instruction from
437 // the PHI that NewBase is computed from, or null otherwise.
439 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
440 Instruction *NewBasePt,
441 SCEVExpander &Rewriter, Loop *L, Pass *P,
443 SmallVectorImpl<WeakVH> &DeadInsts) {
444 if (!isa<PHINode>(Inst)) {
445 // By default, insert code at the user instruction.
446 BasicBlock::iterator InsertPt = Inst;
448 // However, if the Operand is itself an instruction, the (potentially
449 // complex) inserted code may be shared by many users. Because of this, we
450 // want to emit code for the computation of the operand right before its old
451 // computation. This is usually safe, because we obviously used to use the
452 // computation when it was computed in its current block. However, in some
453 // cases (e.g. use of a post-incremented induction variable) the NewBase
454 // value will be pinned to live somewhere after the original computation.
455 // In this case, we have to back off.
457 // If this is a use outside the loop (which means after, since it is based
458 // on a loop indvar) we use the post-incremented value, so that we don't
459 // artificially make the preinc value live out the bottom of the loop.
460 if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
461 if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
462 InsertPt = NewBasePt;
464 } else if (Instruction *OpInst
465 = dyn_cast<Instruction>(OperandValToReplace)) {
467 while (isa<PHINode>(InsertPt)) ++InsertPt;
470 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
471 OperandValToReplace->getType(),
472 Rewriter, InsertPt, L, LI);
473 // Replace the use of the operand Value with the new Phi we just created.
474 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
476 DOUT << " Replacing with ";
477 DEBUG(WriteAsOperand(*DOUT, NewVal, /*PrintType=*/false));
478 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
482 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
483 // expression into each operand block that uses it. Note that PHI nodes can
484 // have multiple entries for the same predecessor. We use a map to make sure
485 // that a PHI node only has a single Value* for each predecessor (which also
486 // prevents us from inserting duplicate code in some blocks).
487 DenseMap<BasicBlock*, Value*> InsertedCode;
488 PHINode *PN = cast<PHINode>(Inst);
489 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
490 if (PN->getIncomingValue(i) == OperandValToReplace) {
491 // If the original expression is outside the loop, put the replacement
492 // code in the same place as the original expression,
493 // which need not be an immediate predecessor of this PHI. This way we
494 // need only one copy of it even if it is referenced multiple times in
495 // the PHI. We don't do this when the original expression is inside the
496 // loop because multiple copies sometimes do useful sinking of code in
498 Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
499 if (L->contains(OldLoc->getParent())) {
500 // If this is a critical edge, split the edge so that we do not insert
501 // the code on all predecessor/successor paths. We do this unless this
502 // is the canonical backedge for this loop, as this can make some
503 // inserted code be in an illegal position.
504 BasicBlock *PHIPred = PN->getIncomingBlock(i);
505 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
506 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
508 // First step, split the critical edge.
509 SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
511 // Next step: move the basic block. In particular, if the PHI node
512 // is outside of the loop, and PredTI is in the loop, we want to
513 // move the block to be immediately before the PHI block, not
514 // immediately after PredTI.
515 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
516 BasicBlock *NewBB = PN->getIncomingBlock(i);
517 NewBB->moveBefore(PN->getParent());
520 // Splitting the edge can reduce the number of PHI entries we have.
521 e = PN->getNumIncomingValues();
524 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
526 // Insert the code into the end of the predecessor block.
527 Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
528 PN->getIncomingBlock(i)->getTerminator() :
529 OldLoc->getParent()->getTerminator();
530 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
531 Rewriter, InsertPt, L, LI);
533 DOUT << " Changing PHI use to ";
534 DEBUG(WriteAsOperand(*DOUT, Code, /*PrintType=*/false));
535 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
538 // Replace the use of the operand Value with the new Phi we just created.
539 PN->setIncomingValue(i, Code);
544 // PHI node might have become a constant value after SplitCriticalEdge.
545 DeadInsts.push_back(Inst);
549 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
550 /// mode, and does not need to be put in a register first.
551 static bool fitsInAddressMode(const SCEVHandle &V, const Type *AccessTy,
552 const TargetLowering *TLI, bool HasBaseReg) {
553 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
554 int64_t VC = SC->getValue()->getSExtValue();
556 TargetLowering::AddrMode AM;
558 AM.HasBaseReg = HasBaseReg;
559 return TLI->isLegalAddressingMode(AM, AccessTy);
561 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
562 return (VC > -(1 << 16) && VC < (1 << 16)-1);
566 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
567 if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
569 TargetLowering::AddrMode AM;
571 AM.HasBaseReg = HasBaseReg;
572 return TLI->isLegalAddressingMode(AM, AccessTy);
574 // Default: assume global addresses are not legal.
581 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
582 /// loop varying to the Imm operand.
583 static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
584 Loop *L, ScalarEvolution *SE) {
585 if (Val->isLoopInvariant(L)) return; // Nothing to do.
587 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
588 std::vector<SCEVHandle> NewOps;
589 NewOps.reserve(SAE->getNumOperands());
591 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
592 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
593 // If this is a loop-variant expression, it must stay in the immediate
594 // field of the expression.
595 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
597 NewOps.push_back(SAE->getOperand(i));
601 Val = SE->getIntegerSCEV(0, Val->getType());
603 Val = SE->getAddExpr(NewOps);
604 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
605 // Try to pull immediates out of the start value of nested addrec's.
606 SCEVHandle Start = SARE->getStart();
607 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
609 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
611 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
613 // Otherwise, all of Val is variant, move the whole thing over.
614 Imm = SE->getAddExpr(Imm, Val);
615 Val = SE->getIntegerSCEV(0, Val->getType());
620 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
621 /// that can fit into the immediate field of instructions in the target.
622 /// Accumulate these immediate values into the Imm value.
623 static void MoveImmediateValues(const TargetLowering *TLI,
624 const Type *AccessTy,
625 SCEVHandle &Val, SCEVHandle &Imm,
626 bool isAddress, Loop *L,
627 ScalarEvolution *SE) {
628 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
629 std::vector<SCEVHandle> NewOps;
630 NewOps.reserve(SAE->getNumOperands());
632 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
633 SCEVHandle NewOp = SAE->getOperand(i);
634 MoveImmediateValues(TLI, AccessTy, NewOp, Imm, isAddress, L, SE);
636 if (!NewOp->isLoopInvariant(L)) {
637 // If this is a loop-variant expression, it must stay in the immediate
638 // field of the expression.
639 Imm = SE->getAddExpr(Imm, NewOp);
641 NewOps.push_back(NewOp);
646 Val = SE->getIntegerSCEV(0, Val->getType());
648 Val = SE->getAddExpr(NewOps);
650 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
651 // Try to pull immediates out of the start value of nested addrec's.
652 SCEVHandle Start = SARE->getStart();
653 MoveImmediateValues(TLI, AccessTy, Start, Imm, isAddress, L, SE);
655 if (Start != SARE->getStart()) {
656 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
658 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
661 } else if (const SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
662 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
664 fitsInAddressMode(SME->getOperand(0), AccessTy, TLI, false) &&
665 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
667 SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
668 SCEVHandle NewOp = SME->getOperand(1);
669 MoveImmediateValues(TLI, AccessTy, NewOp, SubImm, isAddress, L, SE);
671 // If we extracted something out of the subexpressions, see if we can
673 if (NewOp != SME->getOperand(1)) {
674 // Scale SubImm up by "8". If the result is a target constant, we are
676 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
677 if (fitsInAddressMode(SubImm, AccessTy, TLI, false)) {
678 // Accumulate the immediate.
679 Imm = SE->getAddExpr(Imm, SubImm);
681 // Update what is left of 'Val'.
682 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
689 // Loop-variant expressions must stay in the immediate field of the
691 if ((isAddress && fitsInAddressMode(Val, AccessTy, TLI, false)) ||
692 !Val->isLoopInvariant(L)) {
693 Imm = SE->getAddExpr(Imm, Val);
694 Val = SE->getIntegerSCEV(0, Val->getType());
698 // Otherwise, no immediates to move.
701 static void MoveImmediateValues(const TargetLowering *TLI,
703 SCEVHandle &Val, SCEVHandle &Imm,
704 bool isAddress, Loop *L,
705 ScalarEvolution *SE) {
706 const Type *AccessTy = getAccessType(User);
707 MoveImmediateValues(TLI, AccessTy, Val, Imm, isAddress, L, SE);
710 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
711 /// added together. This is used to reassociate common addition subexprs
712 /// together for maximal sharing when rewriting bases.
713 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
715 ScalarEvolution *SE) {
716 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
717 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
718 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
719 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
720 SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
721 if (SARE->getOperand(0) == Zero) {
722 SubExprs.push_back(Expr);
724 // Compute the addrec with zero as its base.
725 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
726 Ops[0] = Zero; // Start with zero base.
727 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
730 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
732 } else if (!Expr->isZero()) {
734 SubExprs.push_back(Expr);
738 // This is logically local to the following function, but C++ says we have
739 // to make it file scope.
740 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
742 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
743 /// the Uses, removing any common subexpressions, except that if all such
744 /// subexpressions can be folded into an addressing mode for all uses inside
745 /// the loop (this case is referred to as "free" in comments herein) we do
746 /// not remove anything. This looks for things like (a+b+c) and
747 /// (a+c+d) and computes the common (a+c) subexpression. The common expression
748 /// is *removed* from the Bases and returned.
750 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
751 ScalarEvolution *SE, Loop *L,
752 const TargetLowering *TLI) {
753 unsigned NumUses = Uses.size();
755 // Only one use? This is a very common case, so we handle it specially and
757 SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
758 SCEVHandle Result = Zero;
759 SCEVHandle FreeResult = Zero;
761 // If the use is inside the loop, use its base, regardless of what it is:
762 // it is clearly shared across all the IV's. If the use is outside the loop
763 // (which means after it) we don't want to factor anything *into* the loop,
764 // so just use 0 as the base.
765 if (L->contains(Uses[0].Inst->getParent()))
766 std::swap(Result, Uses[0].Base);
770 // To find common subexpressions, count how many of Uses use each expression.
771 // If any subexpressions are used Uses.size() times, they are common.
772 // Also track whether all uses of each expression can be moved into an
773 // an addressing mode "for free"; such expressions are left within the loop.
774 // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
775 std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
777 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
778 // order we see them.
779 std::vector<SCEVHandle> UniqueSubExprs;
781 std::vector<SCEVHandle> SubExprs;
782 unsigned NumUsesInsideLoop = 0;
783 for (unsigned i = 0; i != NumUses; ++i) {
784 // If the user is outside the loop, just ignore it for base computation.
785 // Since the user is outside the loop, it must be *after* the loop (if it
786 // were before, it could not be based on the loop IV). We don't want users
787 // after the loop to affect base computation of values *inside* the loop,
788 // because we can always add their offsets to the result IV after the loop
789 // is done, ensuring we get good code inside the loop.
790 if (!L->contains(Uses[i].Inst->getParent()))
794 // If the base is zero (which is common), return zero now, there are no
796 if (Uses[i].Base == Zero) return Zero;
798 // If this use is as an address we may be able to put CSEs in the addressing
799 // mode rather than hoisting them.
800 bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
801 // We may need the AccessTy below, but only when isAddrUse, so compute it
802 // only in that case.
803 const Type *AccessTy = 0;
805 AccessTy = getAccessType(Uses[i].Inst);
807 // Split the expression into subexprs.
808 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
809 // Add one to SubExpressionUseData.Count for each subexpr present, and
810 // if the subexpr is not a valid immediate within an addressing mode use,
811 // set SubExpressionUseData.notAllUsesAreFree. We definitely want to
812 // hoist these out of the loop (if they are common to all uses).
813 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
814 if (++SubExpressionUseData[SubExprs[j]].Count == 1)
815 UniqueSubExprs.push_back(SubExprs[j]);
816 if (!isAddrUse || !fitsInAddressMode(SubExprs[j], AccessTy, TLI, false))
817 SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
822 // Now that we know how many times each is used, build Result. Iterate over
823 // UniqueSubexprs so that we have a stable ordering.
824 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
825 std::map<SCEVHandle, SubExprUseData>::iterator I =
826 SubExpressionUseData.find(UniqueSubExprs[i]);
827 assert(I != SubExpressionUseData.end() && "Entry not found?");
828 if (I->second.Count == NumUsesInsideLoop) { // Found CSE!
829 if (I->second.notAllUsesAreFree)
830 Result = SE->getAddExpr(Result, I->first);
832 FreeResult = SE->getAddExpr(FreeResult, I->first);
834 // Remove non-cse's from SubExpressionUseData.
835 SubExpressionUseData.erase(I);
838 if (FreeResult != Zero) {
839 // We have some subexpressions that can be subsumed into addressing
840 // modes in every use inside the loop. However, it's possible that
841 // there are so many of them that the combined FreeResult cannot
842 // be subsumed, or that the target cannot handle both a FreeResult
843 // and a Result in the same instruction (for example because it would
844 // require too many registers). Check this.
845 for (unsigned i=0; i<NumUses; ++i) {
846 if (!L->contains(Uses[i].Inst->getParent()))
848 // We know this is an addressing mode use; if there are any uses that
849 // are not, FreeResult would be Zero.
850 const Type *AccessTy = getAccessType(Uses[i].Inst);
851 if (!fitsInAddressMode(FreeResult, AccessTy, TLI, Result!=Zero)) {
852 // FIXME: could split up FreeResult into pieces here, some hoisted
853 // and some not. There is no obvious advantage to this.
854 Result = SE->getAddExpr(Result, FreeResult);
861 // If we found no CSE's, return now.
862 if (Result == Zero) return Result;
864 // If we still have a FreeResult, remove its subexpressions from
865 // SubExpressionUseData. This means they will remain in the use Bases.
866 if (FreeResult != Zero) {
867 SeparateSubExprs(SubExprs, FreeResult, SE);
868 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
869 std::map<SCEVHandle, SubExprUseData>::iterator I =
870 SubExpressionUseData.find(SubExprs[j]);
871 SubExpressionUseData.erase(I);
876 // Otherwise, remove all of the CSE's we found from each of the base values.
877 for (unsigned i = 0; i != NumUses; ++i) {
878 // Uses outside the loop don't necessarily include the common base, but
879 // the final IV value coming into those uses does. Instead of trying to
880 // remove the pieces of the common base, which might not be there,
881 // subtract off the base to compensate for this.
882 if (!L->contains(Uses[i].Inst->getParent())) {
883 Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
887 // Split the expression into subexprs.
888 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
890 // Remove any common subexpressions.
891 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
892 if (SubExpressionUseData.count(SubExprs[j])) {
893 SubExprs.erase(SubExprs.begin()+j);
897 // Finally, add the non-shared expressions together.
898 if (SubExprs.empty())
901 Uses[i].Base = SE->getAddExpr(SubExprs);
908 /// ValidScale - Check whether the given Scale is valid for all loads and
909 /// stores in UsersToProcess.
911 bool LoopStrengthReduce::ValidScale(bool HasBaseReg, int64_t Scale,
912 const std::vector<BasedUser>& UsersToProcess) {
916 for (unsigned i = 0, e = UsersToProcess.size(); i!=e; ++i) {
917 // If this is a load or other access, pass the type of the access in.
918 const Type *AccessTy = Type::VoidTy;
919 if (isAddressUse(UsersToProcess[i].Inst,
920 UsersToProcess[i].OperandValToReplace))
921 AccessTy = getAccessType(UsersToProcess[i].Inst);
922 else if (isa<PHINode>(UsersToProcess[i].Inst))
925 TargetLowering::AddrMode AM;
926 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
927 AM.BaseOffs = SC->getValue()->getSExtValue();
928 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
931 // If load[imm+r*scale] is illegal, bail out.
932 if (!TLI->isLegalAddressingMode(AM, AccessTy))
938 /// ValidOffset - Check whether the given Offset is valid for all loads and
939 /// stores in UsersToProcess.
941 bool LoopStrengthReduce::ValidOffset(bool HasBaseReg,
944 const std::vector<BasedUser>& UsersToProcess) {
948 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
949 // If this is a load or other access, pass the type of the access in.
950 const Type *AccessTy = Type::VoidTy;
951 if (isAddressUse(UsersToProcess[i].Inst,
952 UsersToProcess[i].OperandValToReplace))
953 AccessTy = getAccessType(UsersToProcess[i].Inst);
954 else if (isa<PHINode>(UsersToProcess[i].Inst))
957 TargetLowering::AddrMode AM;
958 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
959 AM.BaseOffs = SC->getValue()->getSExtValue();
960 AM.BaseOffs = (uint64_t)AM.BaseOffs + (uint64_t)Offset;
961 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
964 // If load[imm+r*scale] is illegal, bail out.
965 if (!TLI->isLegalAddressingMode(AM, AccessTy))
971 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
973 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
977 Ty1 = SE->getEffectiveSCEVType(Ty1);
978 Ty2 = SE->getEffectiveSCEVType(Ty2);
981 if (Ty1->canLosslesslyBitCastTo(Ty2))
983 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
988 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
989 /// of a previous stride and it is a legal value for the target addressing
990 /// mode scale component and optional base reg. This allows the users of
991 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
992 /// reuse is possible. Factors can be negative on same targets, e.g. ARM.
994 /// If all uses are outside the loop, we don't require that all multiplies
995 /// be folded into the addressing mode, nor even that the factor be constant;
996 /// a multiply (executed once) outside the loop is better than another IV
997 /// within. Well, usually.
998 SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
999 bool AllUsesAreAddresses,
1000 bool AllUsesAreOutsideLoop,
1001 const SCEVHandle &Stride,
1002 IVExpr &IV, const Type *Ty,
1003 const std::vector<BasedUser>& UsersToProcess) {
1004 if (StrideNoReuse.count(Stride))
1005 return SE->getIntegerSCEV(0, Stride->getType());
1007 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
1008 int64_t SInt = SC->getValue()->getSExtValue();
1009 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1010 NewStride != e; ++NewStride) {
1011 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1012 IVsByStride.find(IU->StrideOrder[NewStride]);
1013 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first) ||
1014 StrideNoReuse.count(SI->first))
1016 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1017 if (SI->first != Stride &&
1018 (unsigned(abs64(SInt)) < SSInt || (SInt % SSInt) != 0))
1020 int64_t Scale = SInt / SSInt;
1021 // Check that this stride is valid for all the types used for loads and
1022 // stores; if it can be used for some and not others, we might as well use
1023 // the original stride everywhere, since we have to create the IV for it
1024 // anyway. If the scale is 1, then we don't need to worry about folding
1027 (AllUsesAreAddresses &&
1028 ValidScale(HasBaseReg, Scale, UsersToProcess))) {
1029 // Prefer to reuse an IV with a base of zero.
1030 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1031 IE = SI->second.IVs.end(); II != IE; ++II)
1032 // Only reuse previous IV if it would not require a type conversion
1033 // and if the base difference can be folded.
1034 if (II->Base->isZero() &&
1035 !RequiresTypeConversion(II->Base->getType(), Ty)) {
1037 return SE->getIntegerSCEV(Scale, Stride->getType());
1039 // Otherwise, settle for an IV with a foldable base.
1040 if (AllUsesAreAddresses)
1041 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1042 IE = SI->second.IVs.end(); II != IE; ++II)
1043 // Only reuse previous IV if it would not require a type conversion
1044 // and if the base difference can be folded.
1045 if (SE->getEffectiveSCEVType(II->Base->getType()) ==
1046 SE->getEffectiveSCEVType(Ty) &&
1047 isa<SCEVConstant>(II->Base)) {
1049 cast<SCEVConstant>(II->Base)->getValue()->getSExtValue();
1050 if (Base > INT32_MIN && Base <= INT32_MAX &&
1051 ValidOffset(HasBaseReg, -Base * Scale,
1052 Scale, UsersToProcess)) {
1054 return SE->getIntegerSCEV(Scale, Stride->getType());
1059 } else if (AllUsesAreOutsideLoop) {
1060 // Accept nonconstant strides here; it is really really right to substitute
1061 // an existing IV if we can.
1062 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1063 NewStride != e; ++NewStride) {
1064 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1065 IVsByStride.find(IU->StrideOrder[NewStride]);
1066 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1068 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1069 if (SI->first != Stride && SSInt != 1)
1071 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1072 IE = SI->second.IVs.end(); II != IE; ++II)
1073 // Accept nonzero base here.
1074 // Only reuse previous IV if it would not require a type conversion.
1075 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1080 // Special case, old IV is -1*x and this one is x. Can treat this one as
1082 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1083 NewStride != e; ++NewStride) {
1084 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1085 IVsByStride.find(IU->StrideOrder[NewStride]);
1086 if (SI == IVsByStride.end())
1088 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1089 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
1090 if (Stride == ME->getOperand(1) &&
1091 SC->getValue()->getSExtValue() == -1LL)
1092 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1093 IE = SI->second.IVs.end(); II != IE; ++II)
1094 // Accept nonzero base here.
1095 // Only reuse previous IV if it would not require type conversion.
1096 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1098 return SE->getIntegerSCEV(-1LL, Stride->getType());
1102 return SE->getIntegerSCEV(0, Stride->getType());
1105 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1106 /// returns true if Val's isUseOfPostIncrementedValue is true.
1107 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1108 return Val.isUseOfPostIncrementedValue;
1111 /// isNonConstantNegative - Return true if the specified scev is negated, but
1113 static bool isNonConstantNegative(const SCEVHandle &Expr) {
1114 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1115 if (!Mul) return false;
1117 // If there is a constant factor, it will be first.
1118 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1119 if (!SC) return false;
1121 // Return true if the value is negative, this matches things like (-42 * V).
1122 return SC->getValue()->getValue().isNegative();
1125 // CollectIVUsers - Transform our list of users and offsets to a bit more
1126 // complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1127 // of the strided accesses, as well as the old information from Uses. We
1128 // progressively move information from the Base field to the Imm field, until
1129 // we eventually have the full access expression to rewrite the use.
1130 SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1131 IVUsersOfOneStride &Uses,
1133 bool &AllUsesAreAddresses,
1134 bool &AllUsesAreOutsideLoop,
1135 std::vector<BasedUser> &UsersToProcess) {
1136 // FIXME: Generalize to non-affine IV's.
1137 if (!Stride->isLoopInvariant(L))
1138 return SE->getIntegerSCEV(0, Stride->getType());
1140 UsersToProcess.reserve(Uses.Users.size());
1141 for (ilist<IVStrideUse>::iterator I = Uses.Users.begin(),
1142 E = Uses.Users.end(); I != E; ++I) {
1143 UsersToProcess.push_back(BasedUser(*I, SE));
1145 // Move any loop variant operands from the offset field to the immediate
1146 // field of the use, so that we don't try to use something before it is
1148 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1149 UsersToProcess.back().Imm, L, SE);
1150 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1151 "Base value is not loop invariant!");
1154 // We now have a whole bunch of uses of like-strided induction variables, but
1155 // they might all have different bases. We want to emit one PHI node for this
1156 // stride which we fold as many common expressions (between the IVs) into as
1157 // possible. Start by identifying the common expressions in the base values
1158 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1159 // "A+B"), emit it to the preheader, then remove the expression from the
1160 // UsersToProcess base values.
1161 SCEVHandle CommonExprs =
1162 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1164 // Next, figure out what we can represent in the immediate fields of
1165 // instructions. If we can represent anything there, move it to the imm
1166 // fields of the BasedUsers. We do this so that it increases the commonality
1167 // of the remaining uses.
1168 unsigned NumPHI = 0;
1169 bool HasAddress = false;
1170 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1171 // If the user is not in the current loop, this means it is using the exit
1172 // value of the IV. Do not put anything in the base, make sure it's all in
1173 // the immediate field to allow as much factoring as possible.
1174 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1175 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1176 UsersToProcess[i].Base);
1177 UsersToProcess[i].Base =
1178 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1180 // Not all uses are outside the loop.
1181 AllUsesAreOutsideLoop = false;
1183 // Addressing modes can be folded into loads and stores. Be careful that
1184 // the store is through the expression, not of the expression though.
1186 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1187 UsersToProcess[i].OperandValToReplace);
1188 if (isa<PHINode>(UsersToProcess[i].Inst)) {
1196 // If this use isn't an address, then not all uses are addresses.
1197 if (!isAddress && !isPHI)
1198 AllUsesAreAddresses = false;
1200 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1201 UsersToProcess[i].Imm, isAddress, L, SE);
1205 // If one of the use is a PHI node and all other uses are addresses, still
1206 // allow iv reuse. Essentially we are trading one constant multiplication
1207 // for one fewer iv.
1209 AllUsesAreAddresses = false;
1211 // There are no in-loop address uses.
1212 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1213 AllUsesAreAddresses = false;
1218 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1219 /// is valid and profitable for the given set of users of a stride. In
1220 /// full strength-reduction mode, all addresses at the current stride are
1221 /// strength-reduced all the way down to pointer arithmetic.
1223 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1224 const std::vector<BasedUser> &UsersToProcess,
1226 bool AllUsesAreAddresses,
1227 SCEVHandle Stride) {
1228 if (!EnableFullLSRMode)
1231 // The heuristics below aim to avoid increasing register pressure, but
1232 // fully strength-reducing all the addresses increases the number of
1233 // add instructions, so don't do this when optimizing for size.
1234 // TODO: If the loop is large, the savings due to simpler addresses
1235 // may oughtweight the costs of the extra increment instructions.
1236 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1239 // TODO: For now, don't do full strength reduction if there could
1240 // potentially be greater-stride multiples of the current stride
1241 // which could reuse the current stride IV.
1242 if (IU->StrideOrder.back() != Stride)
1245 // Iterate through the uses to find conditions that automatically rule out
1247 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1248 const SCEV *Base = UsersToProcess[i].Base;
1249 const SCEV *Imm = UsersToProcess[i].Imm;
1250 // If any users have a loop-variant component, they can't be fully
1251 // strength-reduced.
1252 if (Imm && !Imm->isLoopInvariant(L))
1254 // If there are to users with the same base and the difference between
1255 // the two Imm values can't be folded into the address, full
1256 // strength reduction would increase register pressure.
1258 const SCEV *CurImm = UsersToProcess[i].Imm;
1259 if ((CurImm || Imm) && CurImm != Imm) {
1260 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1261 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1262 const Instruction *Inst = UsersToProcess[i].Inst;
1263 const Type *AccessTy = getAccessType(Inst);
1264 SCEVHandle Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1265 if (!Diff->isZero() &&
1266 (!AllUsesAreAddresses ||
1267 !fitsInAddressMode(Diff, AccessTy, TLI, /*HasBaseReg=*/true)))
1270 } while (++i != e && Base == UsersToProcess[i].Base);
1273 // If there's exactly one user in this stride, fully strength-reducing it
1274 // won't increase register pressure. If it's starting from a non-zero base,
1275 // it'll be simpler this way.
1276 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1279 // Otherwise, if there are any users in this stride that don't require
1280 // a register for their base, full strength-reduction will increase
1281 // register pressure.
1282 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1283 if (UsersToProcess[i].Base->isZero())
1286 // Otherwise, go for it.
1290 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1291 /// with the specified start and step values in the specified loop.
1293 /// If NegateStride is true, the stride should be negated by using a
1294 /// subtract instead of an add.
1296 /// Return the created phi node.
1298 static PHINode *InsertAffinePhi(SCEVHandle Start, SCEVHandle Step,
1299 Instruction *IVIncInsertPt,
1301 SCEVExpander &Rewriter) {
1302 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1303 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1305 BasicBlock *Header = L->getHeader();
1306 BasicBlock *Preheader = L->getLoopPreheader();
1307 BasicBlock *LatchBlock = L->getLoopLatch();
1308 const Type *Ty = Start->getType();
1309 Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
1311 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1312 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1315 // If the stride is negative, insert a sub instead of an add for the
1317 bool isNegative = isNonConstantNegative(Step);
1318 SCEVHandle IncAmount = Step;
1320 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1322 // Insert an add instruction right before the terminator corresponding
1323 // to the back-edge or just before the only use. The location is determined
1324 // by the caller and passed in as IVIncInsertPt.
1325 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1326 Preheader->getTerminator());
1329 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1332 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1335 if (!isa<ConstantInt>(StepV)) ++NumVariable;
1337 PN->addIncoming(IncV, LatchBlock);
1343 static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1344 // We want to emit code for users inside the loop first. To do this, we
1345 // rearrange BasedUser so that the entries at the end have
1346 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1347 // vector (so we handle them first).
1348 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1349 PartitionByIsUseOfPostIncrementedValue);
1351 // Sort this by base, so that things with the same base are handled
1352 // together. By partitioning first and stable-sorting later, we are
1353 // guaranteed that within each base we will pop off users from within the
1354 // loop before users outside of the loop with a particular base.
1356 // We would like to use stable_sort here, but we can't. The problem is that
1357 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1358 // we don't have anything to do a '<' comparison on. Because we think the
1359 // number of uses is small, do a horrible bubble sort which just relies on
1361 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1362 // Get a base value.
1363 SCEVHandle Base = UsersToProcess[i].Base;
1365 // Compact everything with this base to be consecutive with this one.
1366 for (unsigned j = i+1; j != e; ++j) {
1367 if (UsersToProcess[j].Base == Base) {
1368 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1375 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1376 /// UsersToProcess, meaning lowering addresses all the way down to direct
1377 /// pointer arithmetic.
1380 LoopStrengthReduce::PrepareToStrengthReduceFully(
1381 std::vector<BasedUser> &UsersToProcess,
1383 SCEVHandle CommonExprs,
1385 SCEVExpander &PreheaderRewriter) {
1386 DOUT << " Fully reducing all users\n";
1388 // Rewrite the UsersToProcess records, creating a separate PHI for each
1389 // unique Base value.
1390 Instruction *IVIncInsertPt = L->getLoopLatch()->getTerminator();
1391 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1392 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1393 // pick the first Imm value here to start with, and adjust it for the
1395 SCEVHandle Imm = UsersToProcess[i].Imm;
1396 SCEVHandle Base = UsersToProcess[i].Base;
1397 SCEVHandle Start = SE->getAddExpr(CommonExprs, Base, Imm);
1398 PHINode *Phi = InsertAffinePhi(Start, Stride, IVIncInsertPt, L,
1400 // Loop over all the users with the same base.
1402 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1403 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1404 UsersToProcess[i].Phi = Phi;
1405 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1406 "ShouldUseFullStrengthReductionMode should reject this!");
1407 } while (++i != e && Base == UsersToProcess[i].Base);
1411 /// FindIVIncInsertPt - Return the location to insert the increment instruction.
1412 /// If the only use if a use of postinc value, (must be the loop termination
1413 /// condition), then insert it just before the use.
1414 static Instruction *FindIVIncInsertPt(std::vector<BasedUser> &UsersToProcess,
1416 if (UsersToProcess.size() == 1 &&
1417 UsersToProcess[0].isUseOfPostIncrementedValue &&
1418 L->contains(UsersToProcess[0].Inst->getParent()))
1419 return UsersToProcess[0].Inst;
1420 return L->getLoopLatch()->getTerminator();
1423 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1424 /// given users to share.
1427 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1428 std::vector<BasedUser> &UsersToProcess,
1430 SCEVHandle CommonExprs,
1432 Instruction *IVIncInsertPt,
1434 SCEVExpander &PreheaderRewriter) {
1435 DOUT << " Inserting new PHI:\n";
1437 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1438 Stride, IVIncInsertPt, L,
1441 // Remember this in case a later stride is multiple of this.
1442 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1444 // All the users will share this new IV.
1445 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1446 UsersToProcess[i].Phi = Phi;
1449 DEBUG(WriteAsOperand(*DOUT, Phi, /*PrintType=*/false));
1453 /// PrepareToStrengthReduceFromSmallerStride - Prepare for the given users to
1454 /// reuse an induction variable with a stride that is a factor of the current
1455 /// induction variable.
1458 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1459 std::vector<BasedUser> &UsersToProcess,
1461 const IVExpr &ReuseIV,
1462 Instruction *PreInsertPt) {
1463 DOUT << " Rewriting in terms of existing IV of STRIDE " << *ReuseIV.Stride
1464 << " and BASE " << *ReuseIV.Base << "\n";
1466 // All the users will share the reused IV.
1467 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1468 UsersToProcess[i].Phi = ReuseIV.PHI;
1470 Constant *C = dyn_cast<Constant>(CommonBaseV);
1472 (!C->isNullValue() &&
1473 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1475 // We want the common base emitted into the preheader! This is just
1476 // using cast as a copy so BitCast (no-op cast) is appropriate
1477 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1478 "commonbase", PreInsertPt);
1481 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1482 const Type *AccessTy,
1483 std::vector<BasedUser> &UsersToProcess,
1484 const TargetLowering *TLI) {
1485 SmallVector<Instruction*, 16> AddrModeInsts;
1486 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1487 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1489 ExtAddrMode AddrMode =
1490 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1491 AccessTy, UsersToProcess[i].Inst,
1492 AddrModeInsts, *TLI);
1493 if (GV && GV != AddrMode.BaseGV)
1495 if (Offset && !AddrMode.BaseOffs)
1496 // FIXME: How to accurate check it's immediate offset is folded.
1498 AddrModeInsts.clear();
1503 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1504 /// stride of IV. All of the users may have different starting values, and this
1505 /// may not be the only stride.
1506 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1507 IVUsersOfOneStride &Uses,
1509 // If all the users are moved to another stride, then there is nothing to do.
1510 if (Uses.Users.empty())
1513 // Keep track if every use in UsersToProcess is an address. If they all are,
1514 // we may be able to rewrite the entire collection of them in terms of a
1515 // smaller-stride IV.
1516 bool AllUsesAreAddresses = true;
1518 // Keep track if every use of a single stride is outside the loop. If so,
1519 // we want to be more aggressive about reusing a smaller-stride IV; a
1520 // multiply outside the loop is better than another IV inside. Well, usually.
1521 bool AllUsesAreOutsideLoop = true;
1523 // Transform our list of users and offsets to a bit more complex table. In
1524 // this new vector, each 'BasedUser' contains 'Base' the base of the
1525 // strided accessas well as the old information from Uses. We progressively
1526 // move information from the Base field to the Imm field, until we eventually
1527 // have the full access expression to rewrite the use.
1528 std::vector<BasedUser> UsersToProcess;
1529 SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1530 AllUsesAreOutsideLoop,
1533 // Sort the UsersToProcess array so that users with common bases are
1534 // next to each other.
1535 SortUsersToProcess(UsersToProcess);
1537 // If we managed to find some expressions in common, we'll need to carry
1538 // their value in a register and add it in for each use. This will take up
1539 // a register operand, which potentially restricts what stride values are
1541 bool HaveCommonExprs = !CommonExprs->isZero();
1542 const Type *ReplacedTy = CommonExprs->getType();
1544 // If all uses are addresses, consider sinking the immediate part of the
1545 // common expression back into uses if they can fit in the immediate fields.
1546 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1547 SCEVHandle NewCommon = CommonExprs;
1548 SCEVHandle Imm = SE->getIntegerSCEV(0, ReplacedTy);
1549 MoveImmediateValues(TLI, Type::VoidTy, NewCommon, Imm, true, L, SE);
1550 if (!Imm->isZero()) {
1553 // If the immediate part of the common expression is a GV, check if it's
1554 // possible to fold it into the target addressing mode.
1555 GlobalValue *GV = 0;
1556 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
1557 GV = dyn_cast<GlobalValue>(SU->getValue());
1559 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
1560 Offset = SC->getValue()->getSExtValue();
1562 // Pass VoidTy as the AccessTy to be conservative, because
1563 // there could be multiple access types among all the uses.
1564 DoSink = IsImmFoldedIntoAddrMode(GV, Offset, Type::VoidTy,
1565 UsersToProcess, TLI);
1568 DOUT << " Sinking " << *Imm << " back down into uses\n";
1569 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1570 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1571 CommonExprs = NewCommon;
1572 HaveCommonExprs = !CommonExprs->isZero();
1578 // Now that we know what we need to do, insert the PHI node itself.
1580 DOUT << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1582 << " Common base: " << *CommonExprs << "\n";
1584 SCEVExpander Rewriter(*SE);
1585 SCEVExpander PreheaderRewriter(*SE);
1587 BasicBlock *Preheader = L->getLoopPreheader();
1588 Instruction *PreInsertPt = Preheader->getTerminator();
1589 BasicBlock *LatchBlock = L->getLoopLatch();
1590 Instruction *IVIncInsertPt = LatchBlock->getTerminator();
1592 Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
1594 SCEVHandle RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1595 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1596 SE->getIntegerSCEV(0, Type::Int32Ty),
1599 /// Choose a strength-reduction strategy and prepare for it by creating
1600 /// the necessary PHIs and adjusting the bookkeeping.
1601 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1602 AllUsesAreAddresses, Stride)) {
1603 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1606 // Emit the initial base value into the loop preheader.
1607 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1610 // If all uses are addresses, check if it is possible to reuse an IV. The
1611 // new IV must have a stride that is a multiple of the old stride; the
1612 // multiple must be a number that can be encoded in the scale field of the
1613 // target addressing mode; and we must have a valid instruction after this
1614 // substitution, including the immediate field, if any.
1615 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1616 AllUsesAreOutsideLoop,
1617 Stride, ReuseIV, ReplacedTy,
1619 if (!RewriteFactor->isZero())
1620 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1621 ReuseIV, PreInsertPt);
1623 IVIncInsertPt = FindIVIncInsertPt(UsersToProcess, L);
1624 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1625 CommonBaseV, IVIncInsertPt,
1626 L, PreheaderRewriter);
1630 // Process all the users now, replacing their strided uses with
1631 // strength-reduced forms. This outer loop handles all bases, the inner
1632 // loop handles all users of a particular base.
1633 while (!UsersToProcess.empty()) {
1634 SCEVHandle Base = UsersToProcess.back().Base;
1635 Instruction *Inst = UsersToProcess.back().Inst;
1637 // Emit the code for Base into the preheader.
1639 if (!Base->isZero()) {
1640 BaseV = PreheaderRewriter.expandCodeFor(Base, 0, PreInsertPt);
1642 DOUT << " INSERTING code for BASE = " << *Base << ":";
1643 if (BaseV->hasName())
1644 DOUT << " Result value name = %" << BaseV->getNameStr();
1647 // If BaseV is a non-zero constant, make sure that it gets inserted into
1648 // the preheader, instead of being forward substituted into the uses. We
1649 // do this by forcing a BitCast (noop cast) to be inserted into the
1650 // preheader in this case.
1651 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false)) {
1652 // We want this constant emitted into the preheader! This is just
1653 // using cast as a copy so BitCast (no-op cast) is appropriate
1654 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1659 // Emit the code to add the immediate offset to the Phi value, just before
1660 // the instructions that we identified as using this stride and base.
1662 // FIXME: Use emitted users to emit other users.
1663 BasedUser &User = UsersToProcess.back();
1665 DOUT << " Examining ";
1666 if (User.isUseOfPostIncrementedValue)
1671 DEBUG(WriteAsOperand(*DOUT, UsersToProcess.back().OperandValToReplace,
1672 /*PrintType=*/false));
1673 DOUT << " in Inst: " << *(User.Inst);
1675 // If this instruction wants to use the post-incremented value, move it
1676 // after the post-inc and use its value instead of the PHI.
1677 Value *RewriteOp = User.Phi;
1678 if (User.isUseOfPostIncrementedValue) {
1679 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1680 // If this user is in the loop, make sure it is the last thing in the
1681 // loop to ensure it is dominated by the increment. In case it's the
1682 // only use of the iv, the increment instruction is already before the
1684 if (L->contains(User.Inst->getParent()) && User.Inst != IVIncInsertPt)
1685 User.Inst->moveBefore(IVIncInsertPt);
1688 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
1690 if (SE->getEffectiveSCEVType(RewriteOp->getType()) !=
1691 SE->getEffectiveSCEVType(ReplacedTy)) {
1692 assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1693 SE->getTypeSizeInBits(ReplacedTy) &&
1694 "Unexpected widening cast!");
1695 RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1698 // If we had to insert new instructions for RewriteOp, we have to
1699 // consider that they may not have been able to end up immediately
1700 // next to RewriteOp, because non-PHI instructions may never precede
1701 // PHI instructions in a block. In this case, remember where the last
1702 // instruction was inserted so that if we're replacing a different
1703 // PHI node, we can use the later point to expand the final
1705 Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
1706 if (RewriteOp == User.Phi) NewBasePt = 0;
1708 // Clear the SCEVExpander's expression map so that we are guaranteed
1709 // to have the code emitted where we expect it.
1712 // If we are reusing the iv, then it must be multiplied by a constant
1713 // factor to take advantage of the addressing mode scale component.
1714 if (!RewriteFactor->isZero()) {
1715 // If we're reusing an IV with a nonzero base (currently this happens
1716 // only when all reuses are outside the loop) subtract that base here.
1717 // The base has been used to initialize the PHI node but we don't want
1719 if (!ReuseIV.Base->isZero()) {
1720 SCEVHandle typedBase = ReuseIV.Base;
1721 if (SE->getEffectiveSCEVType(RewriteExpr->getType()) !=
1722 SE->getEffectiveSCEVType(ReuseIV.Base->getType())) {
1723 // It's possible the original IV is a larger type than the new IV,
1724 // in which case we have to truncate the Base. We checked in
1725 // RequiresTypeConversion that this is valid.
1726 assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1727 SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
1728 "Unexpected lengthening conversion!");
1729 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1730 RewriteExpr->getType());
1732 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1735 // Multiply old variable, with base removed, by new scale factor.
1736 RewriteExpr = SE->getMulExpr(RewriteFactor,
1739 // The common base is emitted in the loop preheader. But since we
1740 // are reusing an IV, it has not been used to initialize the PHI node.
1741 // Add it to the expression used to rewrite the uses.
1742 // When this use is outside the loop, we earlier subtracted the
1743 // common base, and are adding it back here. Use the same expression
1744 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1745 if (!CommonExprs->isZero()) {
1746 if (L->contains(User.Inst->getParent()))
1747 RewriteExpr = SE->getAddExpr(RewriteExpr,
1748 SE->getUnknown(CommonBaseV));
1750 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1754 // Now that we know what we need to do, insert code before User for the
1755 // immediate and any loop-variant expressions.
1757 // Add BaseV to the PHI value if needed.
1758 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1760 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1761 Rewriter, L, this, *LI,
1764 // Mark old value we replaced as possibly dead, so that it is eliminated
1765 // if we just replaced the last use of that value.
1766 DeadInsts.push_back(User.OperandValToReplace);
1768 UsersToProcess.pop_back();
1771 // If there are any more users to process with the same base, process them
1772 // now. We sorted by base above, so we just have to check the last elt.
1773 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1774 // TODO: Next, find out which base index is the most common, pull it out.
1777 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1778 // different starting values, into different PHIs.
1781 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1782 /// set the IV user and stride information and return true, otherwise return
1784 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
1785 const SCEVHandle *&CondStride) {
1786 for (unsigned Stride = 0, e = IU->StrideOrder.size();
1787 Stride != e && !CondUse; ++Stride) {
1788 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
1789 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
1790 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
1792 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1793 E = SI->second->Users.end(); UI != E; ++UI)
1794 if (UI->getUser() == Cond) {
1795 // NOTE: we could handle setcc instructions with multiple uses here, but
1796 // InstCombine does it as well for simple uses, it's not clear that it
1797 // occurs enough in real life to handle.
1799 CondStride = &SI->first;
1807 // Constant strides come first which in turns are sorted by their absolute
1808 // values. If absolute values are the same, then positive strides comes first.
1810 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1811 struct StrideCompare {
1812 const ScalarEvolution *SE;
1813 explicit StrideCompare(const ScalarEvolution *se) : SE(se) {}
1815 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1816 const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1817 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1819 int64_t LV = LHSC->getValue()->getSExtValue();
1820 int64_t RV = RHSC->getValue()->getSExtValue();
1821 uint64_t ALV = (LV < 0) ? -LV : LV;
1822 uint64_t ARV = (RV < 0) ? -RV : RV;
1830 // If it's the same value but different type, sort by bit width so
1831 // that we emit larger induction variables before smaller
1832 // ones, letting the smaller be re-written in terms of larger ones.
1833 return SE->getTypeSizeInBits(RHS->getType()) <
1834 SE->getTypeSizeInBits(LHS->getType());
1836 return LHSC && !RHSC;
1841 /// ChangeCompareStride - If a loop termination compare instruction is the
1842 /// only use of its stride, and the compaison is against a constant value,
1843 /// try eliminate the stride by moving the compare instruction to another
1844 /// stride and change its constant operand accordingly. e.g.
1850 /// if (v2 < 10) goto loop
1855 /// if (v1 < 30) goto loop
1856 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
1857 IVStrideUse* &CondUse,
1858 const SCEVHandle* &CondStride) {
1859 // If there's only one stride in the loop, there's nothing to do here.
1860 if (IU->StrideOrder.size() < 2)
1862 // If there are other users of the condition's stride, don't bother
1863 // trying to change the condition because the stride will still
1865 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator I =
1866 IU->IVUsesByStride.find(*CondStride);
1867 if (I == IU->IVUsesByStride.end() ||
1868 I->second->Users.size() != 1)
1870 // Only handle constant strides for now.
1871 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
1872 if (!SC) return Cond;
1874 ICmpInst::Predicate Predicate = Cond->getPredicate();
1875 int64_t CmpSSInt = SC->getValue()->getSExtValue();
1876 unsigned BitWidth = SE->getTypeSizeInBits((*CondStride)->getType());
1877 uint64_t SignBit = 1ULL << (BitWidth-1);
1878 const Type *CmpTy = Cond->getOperand(0)->getType();
1879 const Type *NewCmpTy = NULL;
1880 unsigned TyBits = SE->getTypeSizeInBits(CmpTy);
1881 unsigned NewTyBits = 0;
1882 SCEVHandle *NewStride = NULL;
1883 Value *NewCmpLHS = NULL;
1884 Value *NewCmpRHS = NULL;
1886 SCEVHandle NewOffset = SE->getIntegerSCEV(0, CmpTy);
1888 if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
1889 int64_t CmpVal = C->getValue().getSExtValue();
1891 // Check stride constant and the comparision constant signs to detect
1893 if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
1896 // Look for a suitable stride / iv as replacement.
1897 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
1898 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
1899 IU->IVUsesByStride.find(IU->StrideOrder[i]);
1900 if (!isa<SCEVConstant>(SI->first))
1902 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1903 if (SSInt == CmpSSInt ||
1904 abs64(SSInt) < abs64(CmpSSInt) ||
1905 (SSInt % CmpSSInt) != 0)
1908 Scale = SSInt / CmpSSInt;
1909 int64_t NewCmpVal = CmpVal * Scale;
1910 APInt Mul = APInt(BitWidth*2, CmpVal, true);
1911 Mul = Mul * APInt(BitWidth*2, Scale, true);
1912 // Check for overflow.
1913 if (!Mul.isSignedIntN(BitWidth))
1915 // Check for overflow in the stride's type too.
1916 if (!Mul.isSignedIntN(SE->getTypeSizeInBits(SI->first->getType())))
1919 // Watch out for overflow.
1920 if (ICmpInst::isSignedPredicate(Predicate) &&
1921 (CmpVal & SignBit) != (NewCmpVal & SignBit))
1924 if (NewCmpVal == CmpVal)
1926 // Pick the best iv to use trying to avoid a cast.
1928 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1929 E = SI->second->Users.end(); UI != E; ++UI) {
1930 Value *Op = UI->getOperandValToReplace();
1932 // If the IVStrideUse implies a cast, check for an actual cast which
1933 // can be used to find the original IV expression.
1934 if (SE->getEffectiveSCEVType(Op->getType()) !=
1935 SE->getEffectiveSCEVType(SI->first->getType())) {
1936 CastInst *CI = dyn_cast<CastInst>(Op);
1937 // If it's not a simple cast, it's complicated.
1940 // If it's a cast from a type other than the stride type,
1941 // it's complicated.
1942 if (CI->getOperand(0)->getType() != SI->first->getType())
1944 // Ok, we found the IV expression in the stride's type.
1945 Op = CI->getOperand(0);
1949 if (NewCmpLHS->getType() == CmpTy)
1955 NewCmpTy = NewCmpLHS->getType();
1956 NewTyBits = SE->getTypeSizeInBits(NewCmpTy);
1957 const Type *NewCmpIntTy = IntegerType::get(NewTyBits);
1958 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
1959 // Check if it is possible to rewrite it using
1960 // an iv / stride of a smaller integer type.
1961 unsigned Bits = NewTyBits;
1962 if (ICmpInst::isSignedPredicate(Predicate))
1964 uint64_t Mask = (1ULL << Bits) - 1;
1965 if (((uint64_t)NewCmpVal & Mask) != (uint64_t)NewCmpVal)
1969 // Don't rewrite if use offset is non-constant and the new type is
1970 // of a different type.
1971 // FIXME: too conservative?
1972 if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->getOffset()))
1975 bool AllUsesAreAddresses = true;
1976 bool AllUsesAreOutsideLoop = true;
1977 std::vector<BasedUser> UsersToProcess;
1978 SCEVHandle CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
1979 AllUsesAreAddresses,
1980 AllUsesAreOutsideLoop,
1982 // Avoid rewriting the compare instruction with an iv of new stride
1983 // if it's likely the new stride uses will be rewritten using the
1984 // stride of the compare instruction.
1985 if (AllUsesAreAddresses &&
1986 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
1989 // If scale is negative, use swapped predicate unless it's testing
1991 if (Scale < 0 && !Cond->isEquality())
1992 Predicate = ICmpInst::getSwappedPredicate(Predicate);
1994 NewStride = &IU->StrideOrder[i];
1995 if (!isa<PointerType>(NewCmpTy))
1996 NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
1998 ConstantInt *CI = ConstantInt::get(NewCmpIntTy, NewCmpVal);
1999 NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
2001 NewOffset = TyBits == NewTyBits
2002 ? SE->getMulExpr(CondUse->getOffset(),
2003 SE->getConstant(ConstantInt::get(CmpTy, Scale)))
2004 : SE->getConstant(ConstantInt::get(NewCmpIntTy,
2005 cast<SCEVConstant>(CondUse->getOffset())->getValue()
2006 ->getSExtValue()*Scale));
2011 // Forgo this transformation if it the increment happens to be
2012 // unfortunately positioned after the condition, and the condition
2013 // has multiple uses which prevent it from being moved immediately
2014 // before the branch. See
2015 // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2016 // for an example of this situation.
2017 if (!Cond->hasOneUse()) {
2018 for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2025 // Create a new compare instruction using new stride / iv.
2026 ICmpInst *OldCond = Cond;
2027 // Insert new compare instruction.
2028 Cond = new ICmpInst(Predicate, NewCmpLHS, NewCmpRHS,
2029 L->getHeader()->getName() + ".termcond",
2032 // Remove the old compare instruction. The old indvar is probably dead too.
2033 DeadInsts.push_back(CondUse->getOperandValToReplace());
2034 OldCond->replaceAllUsesWith(Cond);
2035 OldCond->eraseFromParent();
2037 IU->IVUsesByStride[*NewStride]->addUser(NewOffset, Cond, NewCmpLHS, false);
2038 CondUse = &IU->IVUsesByStride[*NewStride]->Users.back();
2039 CondStride = NewStride;
2047 /// OptimizeSMax - Rewrite the loop's terminating condition if it uses
2048 /// an smax computation.
2050 /// This is a narrow solution to a specific, but acute, problem. For loops
2056 /// } while (++i < n);
2058 /// where the comparison is signed, the trip count isn't just 'n', because
2059 /// 'n' could be negative. And unfortunately this can come up even for loops
2060 /// where the user didn't use a C do-while loop. For example, seemingly
2061 /// well-behaved top-test loops will commonly be lowered like this:
2067 /// } while (++i < n);
2070 /// and then it's possible for subsequent optimization to obscure the if
2071 /// test in such a way that indvars can't find it.
2073 /// When indvars can't find the if test in loops like this, it creates a
2074 /// signed-max expression, which allows it to give the loop a canonical
2075 /// induction variable:
2078 /// smax = n < 1 ? 1 : n;
2081 /// } while (++i != smax);
2083 /// Canonical induction variables are necessary because the loop passes
2084 /// are designed around them. The most obvious example of this is the
2085 /// LoopInfo analysis, which doesn't remember trip count values. It
2086 /// expects to be able to rediscover the trip count each time it is
2087 /// needed, and it does this using a simple analyis that only succeeds if
2088 /// the loop has a canonical induction variable.
2090 /// However, when it comes time to generate code, the maximum operation
2091 /// can be quite costly, especially if it's inside of an outer loop.
2093 /// This function solves this problem by detecting this type of loop and
2094 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2095 /// the instructions for the maximum computation.
2097 ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
2098 IVStrideUse* &CondUse) {
2099 // Check that the loop matches the pattern we're looking for.
2100 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2101 Cond->getPredicate() != CmpInst::ICMP_NE)
2104 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2105 if (!Sel || !Sel->hasOneUse()) return Cond;
2107 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2108 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2110 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2112 // Add one to the backedge-taken count to get the trip count.
2113 SCEVHandle IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
2115 // Check for a max calculation that matches the pattern.
2116 const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
2117 if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
2119 SCEVHandle SMaxLHS = SMax->getOperand(0);
2120 SCEVHandle SMaxRHS = SMax->getOperand(1);
2121 if (!SMaxLHS || SMaxLHS != One) return Cond;
2123 // Check the relevant induction variable for conformance to
2125 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2126 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2127 if (!AR || !AR->isAffine() ||
2128 AR->getStart() != One ||
2129 AR->getStepRecurrence(*SE) != One)
2132 assert(AR->getLoop() == L &&
2133 "Loop condition operand is an addrec in a different loop!");
2135 // Check the right operand of the select, and remember it, as it will
2136 // be used in the new comparison instruction.
2138 if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
2139 NewRHS = Sel->getOperand(1);
2140 else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
2141 NewRHS = Sel->getOperand(2);
2142 if (!NewRHS) return Cond;
2144 // Ok, everything looks ok to change the condition into an SLT or SGE and
2145 // delete the max calculation.
2147 new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
2150 Cond->getOperand(0), NewRHS, "scmp", Cond);
2152 // Delete the max calculation instructions.
2153 Cond->replaceAllUsesWith(NewCond);
2154 CondUse->setUser(NewCond);
2155 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2156 Cond->eraseFromParent();
2157 Sel->eraseFromParent();
2158 if (Cmp->use_empty())
2159 Cmp->eraseFromParent();
2163 /// OptimizeShadowIV - If IV is used in a int-to-float cast
2164 /// inside the loop then try to eliminate the cast opeation.
2165 void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2167 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2168 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2171 for (unsigned Stride = 0, e = IU->StrideOrder.size(); Stride != e;
2173 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2174 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2175 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2176 if (!isa<SCEVConstant>(SI->first))
2179 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
2180 E = SI->second->Users.end(); UI != E; /* empty */) {
2181 ilist<IVStrideUse>::iterator CandidateUI = UI;
2183 Instruction *ShadowUse = CandidateUI->getUser();
2184 const Type *DestTy = NULL;
2186 /* If shadow use is a int->float cast then insert a second IV
2187 to eliminate this cast.
2189 for (unsigned i = 0; i < n; ++i)
2195 for (unsigned i = 0; i < n; ++i, ++d)
2198 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
2199 DestTy = UCast->getDestTy();
2200 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
2201 DestTy = SCast->getDestTy();
2202 if (!DestTy) continue;
2205 // If target does not support DestTy natively then do not apply
2206 // this transformation.
2207 MVT DVT = TLI->getValueType(DestTy);
2208 if (!TLI->isTypeLegal(DVT)) continue;
2211 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2213 if (PH->getNumIncomingValues() != 2) continue;
2215 const Type *SrcTy = PH->getType();
2216 int Mantissa = DestTy->getFPMantissaWidth();
2217 if (Mantissa == -1) continue;
2218 if ((int)SE->getTypeSizeInBits(SrcTy) > Mantissa)
2221 unsigned Entry, Latch;
2222 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2230 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2231 if (!Init) continue;
2232 ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2234 BinaryOperator *Incr =
2235 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2236 if (!Incr) continue;
2237 if (Incr->getOpcode() != Instruction::Add
2238 && Incr->getOpcode() != Instruction::Sub)
2241 /* Initialize new IV, double d = 0.0 in above example. */
2242 ConstantInt *C = NULL;
2243 if (Incr->getOperand(0) == PH)
2244 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2245 else if (Incr->getOperand(1) == PH)
2246 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2252 /* Add new PHINode. */
2253 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2255 /* create new increment. '++d' in above example. */
2256 ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2257 BinaryOperator *NewIncr =
2258 BinaryOperator::Create(Incr->getOpcode(),
2259 NewPH, CFP, "IV.S.next.", Incr);
2261 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2262 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2264 /* Remove cast operation */
2265 ShadowUse->replaceAllUsesWith(NewPH);
2266 ShadowUse->eraseFromParent();
2273 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2274 // uses in the loop, look to see if we can eliminate some, in favor of using
2275 // common indvars for the different uses.
2276 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2277 // TODO: implement optzns here.
2279 OptimizeShadowIV(L);
2282 /// OptimizeLoopTermCond - Change loop terminating condition to use the
2283 /// postinc iv when possible.
2284 void LoopStrengthReduce::OptimizeLoopTermCond(Loop *L) {
2285 // Finally, get the terminating condition for the loop if possible. If we
2286 // can, we want to change it to use a post-incremented version of its
2287 // induction variable, to allow coalescing the live ranges for the IV into
2288 // one register value.
2289 BasicBlock *LatchBlock = L->getLoopLatch();
2290 BasicBlock *ExitBlock = L->getExitingBlock();
2292 // Multiple exits, just look at the exit in the latch block if there is one.
2293 ExitBlock = LatchBlock;
2294 BranchInst *TermBr = dyn_cast<BranchInst>(ExitBlock->getTerminator());
2297 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2300 // Search IVUsesByStride to find Cond's IVUse if there is one.
2301 IVStrideUse *CondUse = 0;
2302 const SCEVHandle *CondStride = 0;
2303 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2304 if (!FindIVUserForCond(Cond, CondUse, CondStride))
2305 return; // setcc doesn't use the IV.
2307 if (ExitBlock != LatchBlock) {
2308 if (!Cond->hasOneUse())
2309 // See below, we don't want the condition to be cloned.
2312 // If exiting block is the latch block, we know it's safe and profitable to
2313 // transform the icmp to use post-inc iv. Otherwise do so only if it would
2314 // not reuse another iv and its iv would be reused by other uses. We are
2315 // optimizing for the case where the icmp is the only use of the iv.
2316 IVUsersOfOneStride &StrideUses = *IU->IVUsesByStride[*CondStride];
2317 for (ilist<IVStrideUse>::iterator I = StrideUses.Users.begin(),
2318 E = StrideUses.Users.end(); I != E; ++I) {
2319 if (I->getUser() == Cond)
2321 if (!I->isUseOfPostIncrementedValue())
2325 // FIXME: This is expensive, and worse still ChangeCompareStride does a
2326 // similar check. Can we perform all the icmp related transformations after
2327 // StrengthReduceStridedIVUsers?
2328 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride)) {
2329 int64_t SInt = SC->getValue()->getSExtValue();
2330 for (unsigned NewStride = 0, ee = IU->StrideOrder.size(); NewStride != ee;
2332 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2333 IU->IVUsesByStride.find(IU->StrideOrder[NewStride]);
2334 if (!isa<SCEVConstant>(SI->first) || SI->first == *CondStride)
2337 cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2339 return; // This can definitely be reused.
2340 if (unsigned(abs64(SSInt)) < SInt || (SSInt % SInt) != 0)
2342 int64_t Scale = SSInt / SInt;
2343 bool AllUsesAreAddresses = true;
2344 bool AllUsesAreOutsideLoop = true;
2345 std::vector<BasedUser> UsersToProcess;
2346 SCEVHandle CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
2347 AllUsesAreAddresses,
2348 AllUsesAreOutsideLoop,
2350 // Avoid rewriting the compare instruction with an iv of new stride
2351 // if it's likely the new stride uses will be rewritten using the
2352 // stride of the compare instruction.
2353 if (AllUsesAreAddresses &&
2354 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
2359 StrideNoReuse.insert(*CondStride);
2362 // If the trip count is computed in terms of an smax (due to ScalarEvolution
2363 // being unable to find a sufficient guard, for example), change the loop
2364 // comparison to use SLT instead of NE.
2365 Cond = OptimizeSMax(L, Cond, CondUse);
2367 // If possible, change stride and operands of the compare instruction to
2368 // eliminate one stride.
2369 if (ExitBlock == LatchBlock)
2370 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
2372 // It's possible for the setcc instruction to be anywhere in the loop, and
2373 // possible for it to have multiple users. If it is not immediately before
2374 // the latch block branch, move it.
2375 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2376 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
2377 Cond->moveBefore(TermBr);
2379 // Otherwise, clone the terminating condition and insert into the loopend.
2380 Cond = cast<ICmpInst>(Cond->clone());
2381 Cond->setName(L->getHeader()->getName() + ".termcond");
2382 LatchBlock->getInstList().insert(TermBr, Cond);
2384 // Clone the IVUse, as the old use still exists!
2385 IU->IVUsesByStride[*CondStride]->addUser(CondUse->getOffset(), Cond,
2386 CondUse->getOperandValToReplace(),
2388 CondUse = &IU->IVUsesByStride[*CondStride]->Users.back();
2392 // If we get to here, we know that we can transform the setcc instruction to
2393 // use the post-incremented version of the IV, allowing us to coalesce the
2394 // live ranges for the IV correctly.
2395 CondUse->setOffset(SE->getMinusSCEV(CondUse->getOffset(), *CondStride));
2396 CondUse->setIsUseOfPostIncrementedValue(true);
2402 // OptimizeLoopCountIV - If, after all sharing of IVs, the IV used for deciding
2403 // when to exit the loop is used only for that purpose, try to rearrange things
2404 // so it counts down to a test against zero.
2405 void LoopStrengthReduce::OptimizeLoopCountIV(Loop *L) {
2407 // If the number of times the loop is executed isn't computable, give up.
2408 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2409 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2412 // Get the terminating condition for the loop if possible (this isn't
2413 // necessarily in the latch, or a block that's a predecessor of the header).
2414 SmallVector<BasicBlock*, 8> ExitBlocks;
2415 L->getExitBlocks(ExitBlocks);
2416 if (ExitBlocks.size() != 1) return;
2418 // Okay, there is one exit block. Try to find the condition that causes the
2419 // loop to be exited.
2420 BasicBlock *ExitBlock = ExitBlocks[0];
2422 BasicBlock *ExitingBlock = 0;
2423 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2425 if (L->contains(*PI)) {
2426 if (ExitingBlock == 0)
2429 return; // More than one block exiting!
2431 assert(ExitingBlock && "No exits from loop, something is broken!");
2433 // Okay, we've computed the exiting block. See what condition causes us to
2436 // FIXME: we should be able to handle switch instructions (with a single exit)
2437 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2438 if (TermBr == 0) return;
2439 assert(TermBr->isConditional() && "If unconditional, it can't be in loop!");
2440 if (!isa<ICmpInst>(TermBr->getCondition()))
2442 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2444 // Handle only tests for equality for the moment, and only stride 1.
2445 if (Cond->getPredicate() != CmpInst::ICMP_EQ)
2447 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2448 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2449 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2450 if (!AR || !AR->isAffine() || AR->getStepRecurrence(*SE) != One)
2453 // Make sure the IV is only used for counting. Value may be preinc or
2454 // postinc; 2 uses in either case.
2455 if (!Cond->getOperand(0)->hasNUses(2))
2457 PHINode *phi = dyn_cast<PHINode>(Cond->getOperand(0));
2459 if (phi && phi->getParent()==L->getHeader()) {
2460 // value tested is preinc. Find the increment.
2461 // A CmpInst is not a BinaryOperator; we depend on this.
2462 Instruction::use_iterator UI = phi->use_begin();
2463 incr = dyn_cast<BinaryOperator>(UI);
2465 incr = dyn_cast<BinaryOperator>(++UI);
2466 // 1 use for postinc value, the phi. Unnecessarily conservative?
2467 if (!incr || !incr->hasOneUse() || incr->getOpcode()!=Instruction::Add)
2470 // Value tested is postinc. Find the phi node.
2471 incr = dyn_cast<BinaryOperator>(Cond->getOperand(0));
2472 if (!incr || incr->getOpcode()!=Instruction::Add)
2475 Instruction::use_iterator UI = Cond->getOperand(0)->use_begin();
2476 phi = dyn_cast<PHINode>(UI);
2478 phi = dyn_cast<PHINode>(++UI);
2479 // 1 use for preinc value, the increment.
2480 if (!phi || phi->getParent()!=L->getHeader() || !phi->hasOneUse())
2484 // Replace the increment with a decrement.
2485 BinaryOperator *decr =
2486 BinaryOperator::Create(Instruction::Sub, incr->getOperand(0),
2487 incr->getOperand(1), "tmp", incr);
2488 incr->replaceAllUsesWith(decr);
2489 incr->eraseFromParent();
2491 // Substitute endval-startval for the original startval, and 0 for the
2492 // original endval. Since we're only testing for equality this is OK even
2493 // if the computation wraps around.
2494 BasicBlock *Preheader = L->getLoopPreheader();
2495 Instruction *PreInsertPt = Preheader->getTerminator();
2496 int inBlock = L->contains(phi->getIncomingBlock(0)) ? 1 : 0;
2497 Value *startVal = phi->getIncomingValue(inBlock);
2498 Value *endVal = Cond->getOperand(1);
2499 // FIXME check for case where both are constant
2500 ConstantInt* Zero = ConstantInt::get(Cond->getOperand(1)->getType(), 0);
2501 BinaryOperator *NewStartVal =
2502 BinaryOperator::Create(Instruction::Sub, endVal, startVal,
2503 "tmp", PreInsertPt);
2504 phi->setIncomingValue(inBlock, NewStartVal);
2505 Cond->setOperand(1, Zero);
2510 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
2512 IU = &getAnalysis<IVUsers>();
2513 LI = &getAnalysis<LoopInfo>();
2514 DT = &getAnalysis<DominatorTree>();
2515 SE = &getAnalysis<ScalarEvolution>();
2518 if (!IU->IVUsesByStride.empty()) {
2520 DOUT << "\nLSR on \"" << L->getHeader()->getParent()->getNameStart()
2525 // Sort the StrideOrder so we process larger strides first.
2526 std::stable_sort(IU->StrideOrder.begin(), IU->StrideOrder.end(),
2529 // Optimize induction variables. Some indvar uses can be transformed to use
2530 // strides that will be needed for other purposes. A common example of this
2531 // is the exit test for the loop, which can often be rewritten to use the
2532 // computation of some other indvar to decide when to terminate the loop.
2535 // Change loop terminating condition to use the postinc iv when possible
2536 // and optimize loop terminating compare. FIXME: Move this after
2537 // StrengthReduceStridedIVUsers?
2538 OptimizeLoopTermCond(L);
2540 // FIXME: We can shrink overlarge IV's here. e.g. if the code has
2541 // computation in i64 values and the target doesn't support i64, demote
2542 // the computation to 32-bit if safe.
2544 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
2545 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2546 // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2547 // Need to be careful that IV's are all the same type. Only works for
2548 // intptr_t indvars.
2550 // IVsByStride keeps IVs for one particular loop.
2551 assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
2553 // Note: this processes each stride/type pair individually. All users
2554 // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2555 // Also, note that we iterate over IVUsesByStride indirectly by using
2556 // StrideOrder. This extra layer of indirection makes the ordering of
2557 // strides deterministic - not dependent on map order.
2558 for (unsigned Stride = 0, e = IU->StrideOrder.size();
2559 Stride != e; ++Stride) {
2560 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2561 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2562 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2563 // FIXME: Generalize to non-affine IV's.
2564 if (!SI->first->isLoopInvariant(L))
2566 StrengthReduceStridedIVUsers(SI->first, *SI->second, L);
2570 // After all sharing is done, see if we can adjust the loop to test against
2571 // zero instead of counting up to a maximum. This is usually faster.
2572 OptimizeLoopCountIV(L);
2574 // We're done analyzing this loop; release all the state we built up for it.
2575 IVsByStride.clear();
2576 StrideNoReuse.clear();
2578 // Clean up after ourselves
2579 if (!DeadInsts.empty())
2580 DeleteTriviallyDeadInstructions();
2582 // At this point, it is worth checking to see if any recurrence PHIs are also
2583 // dead, so that we can remove them as well.
2584 DeleteDeadPHIs(L->getHeader());