Teach SCEVExpander to expand arithmetic involving pointers into GEP
[oota-llvm.git] / lib / Transforms / Scalar / LoopStrengthReduce.cpp
1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
13 //===----------------------------------------------------------------------===//
14
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/SmallPtrSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ValueHandle.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include <algorithm>
39 using namespace llvm;
40
41 STATISTIC(NumReduced ,    "Number of IV uses strength reduced");
42 STATISTIC(NumInserted,    "Number of PHIs inserted");
43 STATISTIC(NumVariable,    "Number of PHIs with variable strides");
44 STATISTIC(NumEliminated,  "Number of strides eliminated");
45 STATISTIC(NumShadow,      "Number of Shadow IVs optimized");
46 STATISTIC(NumImmSunk,     "Number of common expr immediates sunk into uses");
47 STATISTIC(NumLoopCond,    "Number of loop terminating conds optimized");
48
49 static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
50                                        cl::init(false),
51                                        cl::Hidden);
52
53 namespace {
54
55   struct BasedUser;
56
57   /// IVInfo - This structure keeps track of one IV expression inserted during
58   /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
59   /// well as the PHI node and increment value created for rewrite.
60   struct VISIBILITY_HIDDEN IVExpr {
61     SCEVHandle  Stride;
62     SCEVHandle  Base;
63     PHINode    *PHI;
64
65     IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi)
66       : Stride(stride), Base(base), PHI(phi) {}
67   };
68
69   /// IVsOfOneStride - This structure keeps track of all IV expression inserted
70   /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
71   struct VISIBILITY_HIDDEN IVsOfOneStride {
72     std::vector<IVExpr> IVs;
73
74     void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI) {
75       IVs.push_back(IVExpr(Stride, Base, PHI));
76     }
77   };
78
79   class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
80     IVUsers *IU;
81     LoopInfo *LI;
82     DominatorTree *DT;
83     ScalarEvolution *SE;
84     bool Changed;
85
86     /// IVsByStride - Keep track of all IVs that have been inserted for a
87     /// particular stride.
88     std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
89
90     /// StrideNoReuse - Keep track of all the strides whose ivs cannot be
91     /// reused (nor should they be rewritten to reuse other strides).
92     SmallSet<SCEVHandle, 4> StrideNoReuse;
93
94     /// DeadInsts - Keep track of instructions we may have made dead, so that
95     /// we can remove them after we are done working.
96     SmallVector<WeakVH, 16> DeadInsts;
97
98     /// TLI - Keep a pointer of a TargetLowering to consult for determining
99     /// transformation profitability.
100     const TargetLowering *TLI;
101
102   public:
103     static char ID; // Pass ID, replacement for typeid
104     explicit LoopStrengthReduce(const TargetLowering *tli = NULL) : 
105       LoopPass(&ID), TLI(tli) {
106     }
107
108     bool runOnLoop(Loop *L, LPPassManager &LPM);
109
110     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
111       // We split critical edges, so we change the CFG.  However, we do update
112       // many analyses if they are around.
113       AU.addPreservedID(LoopSimplifyID);
114       AU.addPreserved<LoopInfo>();
115       AU.addPreserved<DominanceFrontier>();
116       AU.addPreserved<DominatorTree>();
117
118       AU.addRequiredID(LoopSimplifyID);
119       AU.addRequired<LoopInfo>();
120       AU.addRequired<DominatorTree>();
121       AU.addRequired<ScalarEvolution>();
122       AU.addPreserved<ScalarEvolution>();
123       AU.addRequired<IVUsers>();
124       AU.addPreserved<IVUsers>();
125     }
126
127   private:
128     ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
129                                   IVStrideUse* &CondUse,
130                                   const SCEVHandle* &CondStride);
131
132     void OptimizeIndvars(Loop *L);
133     void OptimizeLoopCountIV(Loop *L);
134     void OptimizeLoopTermCond(Loop *L);
135
136     /// OptimizeShadowIV - If IV is used in a int-to-float cast
137     /// inside the loop then try to eliminate the cast opeation.
138     void OptimizeShadowIV(Loop *L);
139
140     /// OptimizeSMax - Rewrite the loop's terminating condition
141     /// if it uses an smax computation.
142     ICmpInst *OptimizeSMax(Loop *L, ICmpInst *Cond,
143                            IVStrideUse* &CondUse);
144
145     bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
146                            const SCEVHandle *&CondStride);
147     bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
148     SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
149                              IVExpr&, const Type*,
150                              const std::vector<BasedUser>& UsersToProcess);
151     bool ValidScale(bool, int64_t,
152                     const std::vector<BasedUser>& UsersToProcess);
153     bool ValidOffset(bool, int64_t, int64_t,
154                      const std::vector<BasedUser>& UsersToProcess);
155     SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
156                               IVUsersOfOneStride &Uses,
157                               Loop *L,
158                               bool &AllUsesAreAddresses,
159                               bool &AllUsesAreOutsideLoop,
160                               std::vector<BasedUser> &UsersToProcess);
161     bool ShouldUseFullStrengthReductionMode(
162                                 const std::vector<BasedUser> &UsersToProcess,
163                                 const Loop *L,
164                                 bool AllUsesAreAddresses,
165                                 SCEVHandle Stride);
166     void PrepareToStrengthReduceFully(
167                              std::vector<BasedUser> &UsersToProcess,
168                              SCEVHandle Stride,
169                              SCEVHandle CommonExprs,
170                              const Loop *L,
171                              SCEVExpander &PreheaderRewriter);
172     void PrepareToStrengthReduceFromSmallerStride(
173                                          std::vector<BasedUser> &UsersToProcess,
174                                          Value *CommonBaseV,
175                                          const IVExpr &ReuseIV,
176                                          Instruction *PreInsertPt);
177     void PrepareToStrengthReduceWithNewPhi(
178                                   std::vector<BasedUser> &UsersToProcess,
179                                   SCEVHandle Stride,
180                                   SCEVHandle CommonExprs,
181                                   Value *CommonBaseV,
182                                   Instruction *IVIncInsertPt,
183                                   const Loop *L,
184                                   SCEVExpander &PreheaderRewriter);
185     void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
186                                       IVUsersOfOneStride &Uses,
187                                       Loop *L);
188     void DeleteTriviallyDeadInstructions();
189   };
190 }
191
192 char LoopStrengthReduce::ID = 0;
193 static RegisterPass<LoopStrengthReduce>
194 X("loop-reduce", "Loop Strength Reduction");
195
196 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
197   return new LoopStrengthReduce(TLI);
198 }
199
200 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
201 /// specified set are trivially dead, delete them and see if this makes any of
202 /// their operands subsequently dead.
203 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
204   if (DeadInsts.empty()) return;
205   
206   while (!DeadInsts.empty()) {
207     Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.back());
208     DeadInsts.pop_back();
209     
210     if (I == 0 || !isInstructionTriviallyDead(I))
211       continue;
212
213     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
214       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
215         *OI = 0;
216         if (U->use_empty())
217           DeadInsts.push_back(U);
218       }
219     }
220     
221     I->eraseFromParent();
222     Changed = true;
223   }
224 }
225
226 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a 
227 /// subexpression that is an AddRec from a loop other than L.  An outer loop 
228 /// of L is OK, but not an inner loop nor a disjoint loop.
229 static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
230   // This is very common, put it first.
231   if (isa<SCEVConstant>(S))
232     return false;
233   if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
234     for (unsigned int i=0; i< AE->getNumOperands(); i++)
235       if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
236         return true;
237     return false;
238   }
239   if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
240     if (const Loop *newLoop = AE->getLoop()) {
241       if (newLoop == L)
242         return false;
243       // if newLoop is an outer loop of L, this is OK.
244       if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
245         return false;
246     }
247     return true;
248   }
249   if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
250     return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
251            containsAddRecFromDifferentLoop(DE->getRHS(), L);
252 #if 0
253   // SCEVSDivExpr has been backed out temporarily, but will be back; we'll 
254   // need this when it is.
255   if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
256     return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
257            containsAddRecFromDifferentLoop(DE->getRHS(), L);
258 #endif
259   if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
260     return containsAddRecFromDifferentLoop(CE->getOperand(), L);
261   return false;
262 }
263
264 /// isAddressUse - Returns true if the specified instruction is using the
265 /// specified value as an address.
266 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
267   bool isAddress = isa<LoadInst>(Inst);
268   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
269     if (SI->getOperand(1) == OperandVal)
270       isAddress = true;
271   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
272     // Addressing modes can also be folded into prefetches and a variety
273     // of intrinsics.
274     switch (II->getIntrinsicID()) {
275       default: break;
276       case Intrinsic::prefetch:
277       case Intrinsic::x86_sse2_loadu_dq:
278       case Intrinsic::x86_sse2_loadu_pd:
279       case Intrinsic::x86_sse_loadu_ps:
280       case Intrinsic::x86_sse_storeu_ps:
281       case Intrinsic::x86_sse2_storeu_pd:
282       case Intrinsic::x86_sse2_storeu_dq:
283       case Intrinsic::x86_sse2_storel_dq:
284         if (II->getOperand(1) == OperandVal)
285           isAddress = true;
286         break;
287     }
288   }
289   return isAddress;
290 }
291
292 /// getAccessType - Return the type of the memory being accessed.
293 static const Type *getAccessType(const Instruction *Inst) {
294   const Type *AccessTy = Inst->getType();
295   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
296     AccessTy = SI->getOperand(0)->getType();
297   else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
298     // Addressing modes can also be folded into prefetches and a variety
299     // of intrinsics.
300     switch (II->getIntrinsicID()) {
301     default: break;
302     case Intrinsic::x86_sse_storeu_ps:
303     case Intrinsic::x86_sse2_storeu_pd:
304     case Intrinsic::x86_sse2_storeu_dq:
305     case Intrinsic::x86_sse2_storel_dq:
306       AccessTy = II->getOperand(1)->getType();
307       break;
308     }
309   }
310   return AccessTy;
311 }
312
313 namespace {
314   /// BasedUser - For a particular base value, keep information about how we've
315   /// partitioned the expression so far.
316   struct BasedUser {
317     /// SE - The current ScalarEvolution object.
318     ScalarEvolution *SE;
319
320     /// Base - The Base value for the PHI node that needs to be inserted for
321     /// this use.  As the use is processed, information gets moved from this
322     /// field to the Imm field (below).  BasedUser values are sorted by this
323     /// field.
324     SCEVHandle Base;
325     
326     /// Inst - The instruction using the induction variable.
327     Instruction *Inst;
328
329     /// OperandValToReplace - The operand value of Inst to replace with the
330     /// EmittedBase.
331     Value *OperandValToReplace;
332
333     /// isSigned - The stride (and thus also the Base) of this use may be in
334     /// a narrower type than the use itself (OperandValToReplace->getType()).
335     /// When this is the case, the isSigned field indicates whether the
336     /// IV expression should be signed-extended instead of zero-extended to
337     /// fit the type of the use.
338     bool isSigned;
339
340     /// Imm - The immediate value that should be added to the base immediately
341     /// before Inst, because it will be folded into the imm field of the
342     /// instruction.  This is also sometimes used for loop-variant values that
343     /// must be added inside the loop.
344     SCEVHandle Imm;
345
346     /// Phi - The induction variable that performs the striding that
347     /// should be used for this user.
348     PHINode *Phi;
349
350     // isUseOfPostIncrementedValue - True if this should use the
351     // post-incremented version of this IV, not the preincremented version.
352     // This can only be set in special cases, such as the terminating setcc
353     // instruction for a loop and uses outside the loop that are dominated by
354     // the loop.
355     bool isUseOfPostIncrementedValue;
356     
357     BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
358       : SE(se), Base(IVSU.getOffset()), Inst(IVSU.getUser()),
359         OperandValToReplace(IVSU.getOperandValToReplace()),
360         isSigned(IVSU.isSigned()),
361         Imm(SE->getIntegerSCEV(0, Base->getType())), 
362         isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue()) {}
363
364     // Once we rewrite the code to insert the new IVs we want, update the
365     // operands of Inst to use the new expression 'NewBase', with 'Imm' added
366     // to it.
367     void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
368                                         Instruction *InsertPt,
369                                        SCEVExpander &Rewriter, Loop *L, Pass *P,
370                                         LoopInfo &LI,
371                                         SmallVectorImpl<WeakVH> &DeadInsts);
372     
373     Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase, 
374                                        const Type *Ty,
375                                        SCEVExpander &Rewriter,
376                                        Instruction *IP, Loop *L,
377                                        LoopInfo &LI);
378     void dump() const;
379   };
380 }
381
382 void BasedUser::dump() const {
383   cerr << " Base=" << *Base;
384   cerr << " Imm=" << *Imm;
385   cerr << "   Inst: " << *Inst;
386 }
387
388 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase, 
389                                               const Type *Ty,
390                                               SCEVExpander &Rewriter,
391                                               Instruction *IP, Loop *L,
392                                               LoopInfo &LI) {
393   // Figure out where we *really* want to insert this code.  In particular, if
394   // the user is inside of a loop that is nested inside of L, we really don't
395   // want to insert this expression before the user, we'd rather pull it out as
396   // many loops as possible.
397   Instruction *BaseInsertPt = IP;
398   
399   // Figure out the most-nested loop that IP is in.
400   Loop *InsertLoop = LI.getLoopFor(IP->getParent());
401   
402   // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
403   // the preheader of the outer-most loop where NewBase is not loop invariant.
404   if (L->contains(IP->getParent()))
405     while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
406       BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
407       InsertLoop = InsertLoop->getParentLoop();
408     }
409   
410   Value *Base = Rewriter.expandCodeFor(NewBase, 0, BaseInsertPt);
411
412   SCEVHandle NewValSCEV = SE->getUnknown(Base);
413
414   // If there is no immediate value, skip the next part.
415   if (!Imm->isZero()) {
416     // If we are inserting the base and imm values in the same block, make sure
417     // to adjust the IP position if insertion reused a result.
418     if (IP == BaseInsertPt)
419       IP = Rewriter.getInsertionPoint();
420
421     // Always emit the immediate (if non-zero) into the same block as the user.
422     NewValSCEV = SE->getAddExpr(NewValSCEV, Imm);
423   }
424
425   if (isSigned)
426     NewValSCEV = SE->getTruncateOrSignExtend(NewValSCEV, Ty);
427   else
428     NewValSCEV = SE->getTruncateOrZeroExtend(NewValSCEV, Ty);
429
430   return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
431 }
432
433
434 // Once we rewrite the code to insert the new IVs we want, update the
435 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
436 // to it. NewBasePt is the last instruction which contributes to the
437 // value of NewBase in the case that it's a diffferent instruction from
438 // the PHI that NewBase is computed from, or null otherwise.
439 //
440 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
441                                                Instruction *NewBasePt,
442                                       SCEVExpander &Rewriter, Loop *L, Pass *P,
443                                       LoopInfo &LI,
444                                       SmallVectorImpl<WeakVH> &DeadInsts) {
445   if (!isa<PHINode>(Inst)) {
446     // By default, insert code at the user instruction.
447     BasicBlock::iterator InsertPt = Inst;
448     
449     // However, if the Operand is itself an instruction, the (potentially
450     // complex) inserted code may be shared by many users.  Because of this, we
451     // want to emit code for the computation of the operand right before its old
452     // computation.  This is usually safe, because we obviously used to use the
453     // computation when it was computed in its current block.  However, in some
454     // cases (e.g. use of a post-incremented induction variable) the NewBase
455     // value will be pinned to live somewhere after the original computation.
456     // In this case, we have to back off.
457     //
458     // If this is a use outside the loop (which means after, since it is based
459     // on a loop indvar) we use the post-incremented value, so that we don't
460     // artificially make the preinc value live out the bottom of the loop. 
461     if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
462       if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
463         InsertPt = NewBasePt;
464         ++InsertPt;
465       } else if (Instruction *OpInst
466                  = dyn_cast<Instruction>(OperandValToReplace)) {
467         InsertPt = OpInst;
468         while (isa<PHINode>(InsertPt)) ++InsertPt;
469       }
470     }
471     Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
472                                                 OperandValToReplace->getType(),
473                                                 Rewriter, InsertPt, L, LI);
474     // Replace the use of the operand Value with the new Phi we just created.
475     Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
476
477     DOUT << "      Replacing with ";
478     DEBUG(WriteAsOperand(*DOUT, NewVal, /*PrintType=*/false));
479     DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
480     return;
481   }
482
483   // PHI nodes are more complex.  We have to insert one copy of the NewBase+Imm
484   // expression into each operand block that uses it.  Note that PHI nodes can
485   // have multiple entries for the same predecessor.  We use a map to make sure
486   // that a PHI node only has a single Value* for each predecessor (which also
487   // prevents us from inserting duplicate code in some blocks).
488   DenseMap<BasicBlock*, Value*> InsertedCode;
489   PHINode *PN = cast<PHINode>(Inst);
490   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
491     if (PN->getIncomingValue(i) == OperandValToReplace) {
492       // If the original expression is outside the loop, put the replacement
493       // code in the same place as the original expression,
494       // which need not be an immediate predecessor of this PHI.  This way we 
495       // need only one copy of it even if it is referenced multiple times in
496       // the PHI.  We don't do this when the original expression is inside the
497       // loop because multiple copies sometimes do useful sinking of code in
498       // that case(?).
499       Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
500       if (L->contains(OldLoc->getParent())) {
501         // If this is a critical edge, split the edge so that we do not insert
502         // the code on all predecessor/successor paths.  We do this unless this
503         // is the canonical backedge for this loop, as this can make some
504         // inserted code be in an illegal position.
505         BasicBlock *PHIPred = PN->getIncomingBlock(i);
506         if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
507             (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
508
509           // First step, split the critical edge.
510           SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
511
512           // Next step: move the basic block.  In particular, if the PHI node
513           // is outside of the loop, and PredTI is in the loop, we want to
514           // move the block to be immediately before the PHI block, not
515           // immediately after PredTI.
516           if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
517             BasicBlock *NewBB = PN->getIncomingBlock(i);
518             NewBB->moveBefore(PN->getParent());
519           }
520
521           // Splitting the edge can reduce the number of PHI entries we have.
522           e = PN->getNumIncomingValues();
523         }
524       }
525       Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
526       if (!Code) {
527         // Insert the code into the end of the predecessor block.
528         Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
529                                 PN->getIncomingBlock(i)->getTerminator() :
530                                 OldLoc->getParent()->getTerminator();
531         Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
532                                            Rewriter, InsertPt, L, LI);
533
534         DOUT << "      Changing PHI use to ";
535         DEBUG(WriteAsOperand(*DOUT, Code, /*PrintType=*/false));
536         DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
537       }
538
539       // Replace the use of the operand Value with the new Phi we just created.
540       PN->setIncomingValue(i, Code);
541       Rewriter.clear();
542     }
543   }
544
545   // PHI node might have become a constant value after SplitCriticalEdge.
546   DeadInsts.push_back(Inst);
547 }
548
549
550 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
551 /// mode, and does not need to be put in a register first.
552 static bool fitsInAddressMode(const SCEVHandle &V, const Type *AccessTy,
553                              const TargetLowering *TLI, bool HasBaseReg) {
554   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
555     int64_t VC = SC->getValue()->getSExtValue();
556     if (TLI) {
557       TargetLowering::AddrMode AM;
558       AM.BaseOffs = VC;
559       AM.HasBaseReg = HasBaseReg;
560       return TLI->isLegalAddressingMode(AM, AccessTy);
561     } else {
562       // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
563       return (VC > -(1 << 16) && VC < (1 << 16)-1);
564     }
565   }
566
567   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
568     if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
569       if (TLI) {
570         TargetLowering::AddrMode AM;
571         AM.BaseGV = GV;
572         AM.HasBaseReg = HasBaseReg;
573         return TLI->isLegalAddressingMode(AM, AccessTy);
574       } else {
575         // Default: assume global addresses are not legal.
576       }
577     }
578
579   return false;
580 }
581
582 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
583 /// loop varying to the Imm operand.
584 static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
585                                              Loop *L, ScalarEvolution *SE) {
586   if (Val->isLoopInvariant(L)) return;  // Nothing to do.
587   
588   if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
589     std::vector<SCEVHandle> NewOps;
590     NewOps.reserve(SAE->getNumOperands());
591     
592     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
593       if (!SAE->getOperand(i)->isLoopInvariant(L)) {
594         // If this is a loop-variant expression, it must stay in the immediate
595         // field of the expression.
596         Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
597       } else {
598         NewOps.push_back(SAE->getOperand(i));
599       }
600
601     if (NewOps.empty())
602       Val = SE->getIntegerSCEV(0, Val->getType());
603     else
604       Val = SE->getAddExpr(NewOps);
605   } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
606     // Try to pull immediates out of the start value of nested addrec's.
607     SCEVHandle Start = SARE->getStart();
608     MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
609     
610     std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
611     Ops[0] = Start;
612     Val = SE->getAddRecExpr(Ops, SARE->getLoop());
613   } else {
614     // Otherwise, all of Val is variant, move the whole thing over.
615     Imm = SE->getAddExpr(Imm, Val);
616     Val = SE->getIntegerSCEV(0, Val->getType());
617   }
618 }
619
620
621 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
622 /// that can fit into the immediate field of instructions in the target.
623 /// Accumulate these immediate values into the Imm value.
624 static void MoveImmediateValues(const TargetLowering *TLI,
625                                 const Type *AccessTy,
626                                 SCEVHandle &Val, SCEVHandle &Imm,
627                                 bool isAddress, Loop *L,
628                                 ScalarEvolution *SE) {
629   if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
630     std::vector<SCEVHandle> NewOps;
631     NewOps.reserve(SAE->getNumOperands());
632     
633     for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
634       SCEVHandle NewOp = SAE->getOperand(i);
635       MoveImmediateValues(TLI, AccessTy, NewOp, Imm, isAddress, L, SE);
636       
637       if (!NewOp->isLoopInvariant(L)) {
638         // If this is a loop-variant expression, it must stay in the immediate
639         // field of the expression.
640         Imm = SE->getAddExpr(Imm, NewOp);
641       } else {
642         NewOps.push_back(NewOp);
643       }
644     }
645
646     if (NewOps.empty())
647       Val = SE->getIntegerSCEV(0, Val->getType());
648     else
649       Val = SE->getAddExpr(NewOps);
650     return;
651   } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
652     // Try to pull immediates out of the start value of nested addrec's.
653     SCEVHandle Start = SARE->getStart();
654     MoveImmediateValues(TLI, AccessTy, Start, Imm, isAddress, L, SE);
655     
656     if (Start != SARE->getStart()) {
657       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
658       Ops[0] = Start;
659       Val = SE->getAddRecExpr(Ops, SARE->getLoop());
660     }
661     return;
662   } else if (const SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
663     // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
664     if (isAddress &&
665         fitsInAddressMode(SME->getOperand(0), AccessTy, TLI, false) &&
666         SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
667
668       SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
669       SCEVHandle NewOp = SME->getOperand(1);
670       MoveImmediateValues(TLI, AccessTy, NewOp, SubImm, isAddress, L, SE);
671       
672       // If we extracted something out of the subexpressions, see if we can 
673       // simplify this!
674       if (NewOp != SME->getOperand(1)) {
675         // Scale SubImm up by "8".  If the result is a target constant, we are
676         // good.
677         SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
678         if (fitsInAddressMode(SubImm, AccessTy, TLI, false)) {
679           // Accumulate the immediate.
680           Imm = SE->getAddExpr(Imm, SubImm);
681           
682           // Update what is left of 'Val'.
683           Val = SE->getMulExpr(SME->getOperand(0), NewOp);
684           return;
685         }
686       }
687     }
688   }
689
690   // Loop-variant expressions must stay in the immediate field of the
691   // expression.
692   if ((isAddress && fitsInAddressMode(Val, AccessTy, TLI, false)) ||
693       !Val->isLoopInvariant(L)) {
694     Imm = SE->getAddExpr(Imm, Val);
695     Val = SE->getIntegerSCEV(0, Val->getType());
696     return;
697   }
698
699   // Otherwise, no immediates to move.
700 }
701
702 static void MoveImmediateValues(const TargetLowering *TLI,
703                                 Instruction *User,
704                                 SCEVHandle &Val, SCEVHandle &Imm,
705                                 bool isAddress, Loop *L,
706                                 ScalarEvolution *SE) {
707   const Type *AccessTy = getAccessType(User);
708   MoveImmediateValues(TLI, AccessTy, Val, Imm, isAddress, L, SE);
709 }
710
711 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
712 /// added together.  This is used to reassociate common addition subexprs
713 /// together for maximal sharing when rewriting bases.
714 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
715                              SCEVHandle Expr,
716                              ScalarEvolution *SE) {
717   if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
718     for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
719       SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
720   } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
721     SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
722     if (SARE->getOperand(0) == Zero) {
723       SubExprs.push_back(Expr);
724     } else {
725       // Compute the addrec with zero as its base.
726       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
727       Ops[0] = Zero;   // Start with zero base.
728       SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
729       
730
731       SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
732     }
733   } else if (!Expr->isZero()) {
734     // Do not add zero.
735     SubExprs.push_back(Expr);
736   }
737 }
738
739 // This is logically local to the following function, but C++ says we have 
740 // to make it file scope.
741 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
742
743 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
744 /// the Uses, removing any common subexpressions, except that if all such
745 /// subexpressions can be folded into an addressing mode for all uses inside
746 /// the loop (this case is referred to as "free" in comments herein) we do
747 /// not remove anything.  This looks for things like (a+b+c) and
748 /// (a+c+d) and computes the common (a+c) subexpression.  The common expression
749 /// is *removed* from the Bases and returned.
750 static SCEVHandle 
751 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
752                                     ScalarEvolution *SE, Loop *L,
753                                     const TargetLowering *TLI) {
754   unsigned NumUses = Uses.size();
755
756   // Only one use?  This is a very common case, so we handle it specially and
757   // cheaply.
758   SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
759   SCEVHandle Result = Zero;
760   SCEVHandle FreeResult = Zero;
761   if (NumUses == 1) {
762     // If the use is inside the loop, use its base, regardless of what it is:
763     // it is clearly shared across all the IV's.  If the use is outside the loop
764     // (which means after it) we don't want to factor anything *into* the loop,
765     // so just use 0 as the base.
766     if (L->contains(Uses[0].Inst->getParent()))
767       std::swap(Result, Uses[0].Base);
768     return Result;
769   }
770
771   // To find common subexpressions, count how many of Uses use each expression.
772   // If any subexpressions are used Uses.size() times, they are common.
773   // Also track whether all uses of each expression can be moved into an
774   // an addressing mode "for free"; such expressions are left within the loop.
775   // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
776   std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
777   
778   // UniqueSubExprs - Keep track of all of the subexpressions we see in the
779   // order we see them.
780   std::vector<SCEVHandle> UniqueSubExprs;
781
782   std::vector<SCEVHandle> SubExprs;
783   unsigned NumUsesInsideLoop = 0;
784   for (unsigned i = 0; i != NumUses; ++i) {
785     // If the user is outside the loop, just ignore it for base computation.
786     // Since the user is outside the loop, it must be *after* the loop (if it
787     // were before, it could not be based on the loop IV).  We don't want users
788     // after the loop to affect base computation of values *inside* the loop,
789     // because we can always add their offsets to the result IV after the loop
790     // is done, ensuring we get good code inside the loop.
791     if (!L->contains(Uses[i].Inst->getParent()))
792       continue;
793     NumUsesInsideLoop++;
794     
795     // If the base is zero (which is common), return zero now, there are no
796     // CSEs we can find.
797     if (Uses[i].Base == Zero) return Zero;
798
799     // If this use is as an address we may be able to put CSEs in the addressing
800     // mode rather than hoisting them.
801     bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
802     // We may need the AccessTy below, but only when isAddrUse, so compute it
803     // only in that case.
804     const Type *AccessTy = 0;
805     if (isAddrUse)
806       AccessTy = getAccessType(Uses[i].Inst);
807
808     // Split the expression into subexprs.
809     SeparateSubExprs(SubExprs, Uses[i].Base, SE);
810     // Add one to SubExpressionUseData.Count for each subexpr present, and
811     // if the subexpr is not a valid immediate within an addressing mode use,
812     // set SubExpressionUseData.notAllUsesAreFree.  We definitely want to
813     // hoist these out of the loop (if they are common to all uses).
814     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
815       if (++SubExpressionUseData[SubExprs[j]].Count == 1)
816         UniqueSubExprs.push_back(SubExprs[j]);
817       if (!isAddrUse || !fitsInAddressMode(SubExprs[j], AccessTy, TLI, false))
818         SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
819     }
820     SubExprs.clear();
821   }
822
823   // Now that we know how many times each is used, build Result.  Iterate over
824   // UniqueSubexprs so that we have a stable ordering.
825   for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
826     std::map<SCEVHandle, SubExprUseData>::iterator I = 
827        SubExpressionUseData.find(UniqueSubExprs[i]);
828     assert(I != SubExpressionUseData.end() && "Entry not found?");
829     if (I->second.Count == NumUsesInsideLoop) { // Found CSE! 
830       if (I->second.notAllUsesAreFree)
831         Result = SE->getAddExpr(Result, I->first);
832       else 
833         FreeResult = SE->getAddExpr(FreeResult, I->first);
834     } else
835       // Remove non-cse's from SubExpressionUseData.
836       SubExpressionUseData.erase(I);
837   }
838
839   if (FreeResult != Zero) {
840     // We have some subexpressions that can be subsumed into addressing
841     // modes in every use inside the loop.  However, it's possible that
842     // there are so many of them that the combined FreeResult cannot
843     // be subsumed, or that the target cannot handle both a FreeResult
844     // and a Result in the same instruction (for example because it would
845     // require too many registers).  Check this.
846     for (unsigned i=0; i<NumUses; ++i) {
847       if (!L->contains(Uses[i].Inst->getParent()))
848         continue;
849       // We know this is an addressing mode use; if there are any uses that
850       // are not, FreeResult would be Zero.
851       const Type *AccessTy = getAccessType(Uses[i].Inst);
852       if (!fitsInAddressMode(FreeResult, AccessTy, TLI, Result!=Zero)) {
853         // FIXME:  could split up FreeResult into pieces here, some hoisted
854         // and some not.  There is no obvious advantage to this.
855         Result = SE->getAddExpr(Result, FreeResult);
856         FreeResult = Zero;
857         break;
858       }
859     }
860   }
861
862   // If we found no CSE's, return now.
863   if (Result == Zero) return Result;
864   
865   // If we still have a FreeResult, remove its subexpressions from
866   // SubExpressionUseData.  This means they will remain in the use Bases.
867   if (FreeResult != Zero) {
868     SeparateSubExprs(SubExprs, FreeResult, SE);
869     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
870       std::map<SCEVHandle, SubExprUseData>::iterator I = 
871          SubExpressionUseData.find(SubExprs[j]);
872       SubExpressionUseData.erase(I);
873     }
874     SubExprs.clear();
875   }
876
877   // Otherwise, remove all of the CSE's we found from each of the base values.
878   for (unsigned i = 0; i != NumUses; ++i) {
879     // Uses outside the loop don't necessarily include the common base, but
880     // the final IV value coming into those uses does.  Instead of trying to
881     // remove the pieces of the common base, which might not be there,
882     // subtract off the base to compensate for this.
883     if (!L->contains(Uses[i].Inst->getParent())) {
884       Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
885       continue;
886     }
887
888     // Split the expression into subexprs.
889     SeparateSubExprs(SubExprs, Uses[i].Base, SE);
890
891     // Remove any common subexpressions.
892     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
893       if (SubExpressionUseData.count(SubExprs[j])) {
894         SubExprs.erase(SubExprs.begin()+j);
895         --j; --e;
896       }
897     
898     // Finally, add the non-shared expressions together.
899     if (SubExprs.empty())
900       Uses[i].Base = Zero;
901     else
902       Uses[i].Base = SE->getAddExpr(SubExprs);
903     SubExprs.clear();
904   }
905  
906   return Result;
907 }
908
909 /// ValidScale - Check whether the given Scale is valid for all loads and 
910 /// stores in UsersToProcess.
911 ///
912 bool LoopStrengthReduce::ValidScale(bool HasBaseReg, int64_t Scale,
913                                const std::vector<BasedUser>& UsersToProcess) {
914   if (!TLI)
915     return true;
916
917   for (unsigned i = 0, e = UsersToProcess.size(); i!=e; ++i) {
918     // If this is a load or other access, pass the type of the access in.
919     const Type *AccessTy = Type::VoidTy;
920     if (isAddressUse(UsersToProcess[i].Inst,
921                      UsersToProcess[i].OperandValToReplace))
922       AccessTy = getAccessType(UsersToProcess[i].Inst);
923     else if (isa<PHINode>(UsersToProcess[i].Inst))
924       continue;
925     
926     TargetLowering::AddrMode AM;
927     if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
928       AM.BaseOffs = SC->getValue()->getSExtValue();
929     AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
930     AM.Scale = Scale;
931
932     // If load[imm+r*scale] is illegal, bail out.
933     if (!TLI->isLegalAddressingMode(AM, AccessTy))
934       return false;
935   }
936   return true;
937 }
938
939 /// ValidOffset - Check whether the given Offset is valid for all loads and
940 /// stores in UsersToProcess.
941 ///
942 bool LoopStrengthReduce::ValidOffset(bool HasBaseReg,
943                                int64_t Offset,
944                                int64_t Scale,
945                                const std::vector<BasedUser>& UsersToProcess) {
946   if (!TLI)
947     return true;
948
949   for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
950     // If this is a load or other access, pass the type of the access in.
951     const Type *AccessTy = Type::VoidTy;
952     if (isAddressUse(UsersToProcess[i].Inst,
953                      UsersToProcess[i].OperandValToReplace))
954       AccessTy = getAccessType(UsersToProcess[i].Inst);
955     else if (isa<PHINode>(UsersToProcess[i].Inst))
956       continue;
957
958     TargetLowering::AddrMode AM;
959     if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
960       AM.BaseOffs = SC->getValue()->getSExtValue();
961     AM.BaseOffs = (uint64_t)AM.BaseOffs + (uint64_t)Offset;
962     AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
963     AM.Scale = Scale;
964
965     // If load[imm+r*scale] is illegal, bail out.
966     if (!TLI->isLegalAddressingMode(AM, AccessTy))
967       return false;
968   }
969   return true;
970 }
971
972 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
973 /// a nop.
974 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
975                                                 const Type *Ty2) {
976   if (Ty1 == Ty2)
977     return false;
978   Ty1 = SE->getEffectiveSCEVType(Ty1);
979   Ty2 = SE->getEffectiveSCEVType(Ty2);
980   if (Ty1 == Ty2)
981     return false;
982   if (Ty1->canLosslesslyBitCastTo(Ty2))
983     return false;
984   if (TLI && TLI->isTruncateFree(Ty1, Ty2))
985     return false;
986   return true;
987 }
988
989 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
990 /// of a previous stride and it is a legal value for the target addressing
991 /// mode scale component and optional base reg. This allows the users of
992 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
993 /// reuse is possible.  Factors can be negative on same targets, e.g. ARM.
994 ///
995 /// If all uses are outside the loop, we don't require that all multiplies
996 /// be folded into the addressing mode, nor even that the factor be constant; 
997 /// a multiply (executed once) outside the loop is better than another IV 
998 /// within.  Well, usually.
999 SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
1000                                 bool AllUsesAreAddresses,
1001                                 bool AllUsesAreOutsideLoop,
1002                                 const SCEVHandle &Stride, 
1003                                 IVExpr &IV, const Type *Ty,
1004                                 const std::vector<BasedUser>& UsersToProcess) {
1005   if (StrideNoReuse.count(Stride))
1006     return SE->getIntegerSCEV(0, Stride->getType());
1007
1008   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
1009     int64_t SInt = SC->getValue()->getSExtValue();
1010     for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1011          NewStride != e; ++NewStride) {
1012       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
1013                 IVsByStride.find(IU->StrideOrder[NewStride]);
1014       if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first) ||
1015           StrideNoReuse.count(SI->first))
1016         continue;
1017       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1018       if (SI->first != Stride &&
1019           (unsigned(abs64(SInt)) < SSInt || (SInt % SSInt) != 0))
1020         continue;
1021       int64_t Scale = SInt / SSInt;
1022       // Check that this stride is valid for all the types used for loads and
1023       // stores; if it can be used for some and not others, we might as well use
1024       // the original stride everywhere, since we have to create the IV for it
1025       // anyway. If the scale is 1, then we don't need to worry about folding
1026       // multiplications.
1027       if (Scale == 1 ||
1028           (AllUsesAreAddresses &&
1029            ValidScale(HasBaseReg, Scale, UsersToProcess))) {
1030         // Prefer to reuse an IV with a base of zero.
1031         for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1032                IE = SI->second.IVs.end(); II != IE; ++II)
1033           // Only reuse previous IV if it would not require a type conversion
1034           // and if the base difference can be folded.
1035           if (II->Base->isZero() &&
1036               !RequiresTypeConversion(II->Base->getType(), Ty)) {
1037             IV = *II;
1038             return SE->getIntegerSCEV(Scale, Stride->getType());
1039           }
1040         // Otherwise, settle for an IV with a foldable base.
1041         if (AllUsesAreAddresses)
1042           for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1043                  IE = SI->second.IVs.end(); II != IE; ++II)
1044             // Only reuse previous IV if it would not require a type conversion
1045             // and if the base difference can be folded.
1046             if (SE->getEffectiveSCEVType(II->Base->getType()) ==
1047                 SE->getEffectiveSCEVType(Ty) &&
1048                 isa<SCEVConstant>(II->Base)) {
1049               int64_t Base =
1050                 cast<SCEVConstant>(II->Base)->getValue()->getSExtValue();
1051               if (Base > INT32_MIN && Base <= INT32_MAX &&
1052                   ValidOffset(HasBaseReg, -Base * Scale,
1053                               Scale, UsersToProcess)) {
1054                 IV = *II;
1055                 return SE->getIntegerSCEV(Scale, Stride->getType());
1056               }
1057             }
1058       }
1059     }
1060   } else if (AllUsesAreOutsideLoop) {
1061     // Accept nonconstant strides here; it is really really right to substitute
1062     // an existing IV if we can.
1063     for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1064          NewStride != e; ++NewStride) {
1065       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
1066                 IVsByStride.find(IU->StrideOrder[NewStride]);
1067       if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1068         continue;
1069       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1070       if (SI->first != Stride && SSInt != 1)
1071         continue;
1072       for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1073              IE = SI->second.IVs.end(); II != IE; ++II)
1074         // Accept nonzero base here.
1075         // Only reuse previous IV if it would not require a type conversion.
1076         if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1077           IV = *II;
1078           return Stride;
1079         }
1080     }
1081     // Special case, old IV is -1*x and this one is x.  Can treat this one as
1082     // -1*old.
1083     for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1084          NewStride != e; ++NewStride) {
1085       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
1086                 IVsByStride.find(IU->StrideOrder[NewStride]);
1087       if (SI == IVsByStride.end()) 
1088         continue;
1089       if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1090         if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
1091           if (Stride == ME->getOperand(1) &&
1092               SC->getValue()->getSExtValue() == -1LL)
1093             for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1094                    IE = SI->second.IVs.end(); II != IE; ++II)
1095               // Accept nonzero base here.
1096               // Only reuse previous IV if it would not require type conversion.
1097               if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1098                 IV = *II;
1099                 return SE->getIntegerSCEV(-1LL, Stride->getType());
1100               }
1101     }
1102   }
1103   return SE->getIntegerSCEV(0, Stride->getType());
1104 }
1105
1106 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1107 /// returns true if Val's isUseOfPostIncrementedValue is true.
1108 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1109   return Val.isUseOfPostIncrementedValue;
1110 }
1111
1112 /// isNonConstantNegative - Return true if the specified scev is negated, but
1113 /// not a constant.
1114 static bool isNonConstantNegative(const SCEVHandle &Expr) {
1115   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1116   if (!Mul) return false;
1117   
1118   // If there is a constant factor, it will be first.
1119   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1120   if (!SC) return false;
1121   
1122   // Return true if the value is negative, this matches things like (-42 * V).
1123   return SC->getValue()->getValue().isNegative();
1124 }
1125
1126 // CollectIVUsers - Transform our list of users and offsets to a bit more
1127 // complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1128 // of the strided accesses, as well as the old information from Uses. We
1129 // progressively move information from the Base field to the Imm field, until
1130 // we eventually have the full access expression to rewrite the use.
1131 SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1132                                               IVUsersOfOneStride &Uses,
1133                                               Loop *L,
1134                                               bool &AllUsesAreAddresses,
1135                                               bool &AllUsesAreOutsideLoop,
1136                                        std::vector<BasedUser> &UsersToProcess) {
1137   // FIXME: Generalize to non-affine IV's.
1138   if (!Stride->isLoopInvariant(L))
1139     return SE->getIntegerSCEV(0, Stride->getType());
1140
1141   UsersToProcess.reserve(Uses.Users.size());
1142   for (ilist<IVStrideUse>::iterator I = Uses.Users.begin(),
1143        E = Uses.Users.end(); I != E; ++I) {
1144     UsersToProcess.push_back(BasedUser(*I, SE));
1145
1146     // Move any loop variant operands from the offset field to the immediate
1147     // field of the use, so that we don't try to use something before it is
1148     // computed.
1149     MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1150                                      UsersToProcess.back().Imm, L, SE);
1151     assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1152            "Base value is not loop invariant!");
1153   }
1154
1155   // We now have a whole bunch of uses of like-strided induction variables, but
1156   // they might all have different bases.  We want to emit one PHI node for this
1157   // stride which we fold as many common expressions (between the IVs) into as
1158   // possible.  Start by identifying the common expressions in the base values 
1159   // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1160   // "A+B"), emit it to the preheader, then remove the expression from the
1161   // UsersToProcess base values.
1162   SCEVHandle CommonExprs =
1163     RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1164
1165   // Next, figure out what we can represent in the immediate fields of
1166   // instructions.  If we can represent anything there, move it to the imm
1167   // fields of the BasedUsers.  We do this so that it increases the commonality
1168   // of the remaining uses.
1169   unsigned NumPHI = 0;
1170   bool HasAddress = false;
1171   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1172     // If the user is not in the current loop, this means it is using the exit
1173     // value of the IV.  Do not put anything in the base, make sure it's all in
1174     // the immediate field to allow as much factoring as possible.
1175     if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1176       UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1177                                              UsersToProcess[i].Base);
1178       UsersToProcess[i].Base = 
1179         SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1180     } else {
1181       // Not all uses are outside the loop.
1182       AllUsesAreOutsideLoop = false; 
1183
1184       // Addressing modes can be folded into loads and stores.  Be careful that
1185       // the store is through the expression, not of the expression though.
1186       bool isPHI = false;
1187       bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1188                                     UsersToProcess[i].OperandValToReplace);
1189       if (isa<PHINode>(UsersToProcess[i].Inst)) {
1190         isPHI = true;
1191         ++NumPHI;
1192       }
1193
1194       if (isAddress)
1195         HasAddress = true;
1196      
1197       // If this use isn't an address, then not all uses are addresses.
1198       if (!isAddress && !isPHI)
1199         AllUsesAreAddresses = false;
1200       
1201       MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1202                           UsersToProcess[i].Imm, isAddress, L, SE);
1203     }
1204   }
1205
1206   // If one of the use is a PHI node and all other uses are addresses, still
1207   // allow iv reuse. Essentially we are trading one constant multiplication
1208   // for one fewer iv.
1209   if (NumPHI > 1)
1210     AllUsesAreAddresses = false;
1211     
1212   // There are no in-loop address uses.
1213   if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1214     AllUsesAreAddresses = false;
1215
1216   return CommonExprs;
1217 }
1218
1219 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1220 /// is valid and profitable for the given set of users of a stride. In
1221 /// full strength-reduction mode, all addresses at the current stride are
1222 /// strength-reduced all the way down to pointer arithmetic.
1223 ///
1224 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1225                                    const std::vector<BasedUser> &UsersToProcess,
1226                                    const Loop *L,
1227                                    bool AllUsesAreAddresses,
1228                                    SCEVHandle Stride) {
1229   if (!EnableFullLSRMode)
1230     return false;
1231
1232   // The heuristics below aim to avoid increasing register pressure, but
1233   // fully strength-reducing all the addresses increases the number of
1234   // add instructions, so don't do this when optimizing for size.
1235   // TODO: If the loop is large, the savings due to simpler addresses
1236   // may oughtweight the costs of the extra increment instructions.
1237   if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1238     return false;
1239
1240   // TODO: For now, don't do full strength reduction if there could
1241   // potentially be greater-stride multiples of the current stride
1242   // which could reuse the current stride IV.
1243   if (IU->StrideOrder.back() != Stride)
1244     return false;
1245
1246   // Iterate through the uses to find conditions that automatically rule out
1247   // full-lsr mode.
1248   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1249     const SCEV *Base = UsersToProcess[i].Base;
1250     const SCEV *Imm = UsersToProcess[i].Imm;
1251     // If any users have a loop-variant component, they can't be fully
1252     // strength-reduced.
1253     if (Imm && !Imm->isLoopInvariant(L))
1254       return false;
1255     // If there are to users with the same base and the difference between
1256     // the two Imm values can't be folded into the address, full
1257     // strength reduction would increase register pressure.
1258     do {
1259       const SCEV *CurImm = UsersToProcess[i].Imm;
1260       if ((CurImm || Imm) && CurImm != Imm) {
1261         if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1262         if (!Imm)       Imm = SE->getIntegerSCEV(0, Stride->getType());
1263         const Instruction *Inst = UsersToProcess[i].Inst;
1264         const Type *AccessTy = getAccessType(Inst);
1265         SCEVHandle Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1266         if (!Diff->isZero() &&
1267             (!AllUsesAreAddresses ||
1268              !fitsInAddressMode(Diff, AccessTy, TLI, /*HasBaseReg=*/true)))
1269           return false;
1270       }
1271     } while (++i != e && Base == UsersToProcess[i].Base);
1272   }
1273
1274   // If there's exactly one user in this stride, fully strength-reducing it
1275   // won't increase register pressure. If it's starting from a non-zero base,
1276   // it'll be simpler this way.
1277   if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1278     return true;
1279
1280   // Otherwise, if there are any users in this stride that don't require
1281   // a register for their base, full strength-reduction will increase
1282   // register pressure.
1283   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1284     if (UsersToProcess[i].Base->isZero())
1285       return false;
1286
1287   // Otherwise, go for it.
1288   return true;
1289 }
1290
1291 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1292 /// with the specified start and step values in the specified loop.
1293 ///
1294 /// If NegateStride is true, the stride should be negated by using a
1295 /// subtract instead of an add.
1296 ///
1297 /// Return the created phi node.
1298 ///
1299 static PHINode *InsertAffinePhi(SCEVHandle Start, SCEVHandle Step,
1300                                 Instruction *IVIncInsertPt,
1301                                 const Loop *L,
1302                                 SCEVExpander &Rewriter) {
1303   assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1304   assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1305
1306   BasicBlock *Header = L->getHeader();
1307   BasicBlock *Preheader = L->getLoopPreheader();
1308   BasicBlock *LatchBlock = L->getLoopLatch();
1309   const Type *Ty = Start->getType();
1310   Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
1311
1312   PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1313   PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1314                   Preheader);
1315
1316   // If the stride is negative, insert a sub instead of an add for the
1317   // increment.
1318   bool isNegative = isNonConstantNegative(Step);
1319   SCEVHandle IncAmount = Step;
1320   if (isNegative)
1321     IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1322
1323   // Insert an add instruction right before the terminator corresponding
1324   // to the back-edge or just before the only use. The location is determined
1325   // by the caller and passed in as IVIncInsertPt.
1326   Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1327                                         Preheader->getTerminator());
1328   Instruction *IncV;
1329   if (isNegative) {
1330     IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1331                                      IVIncInsertPt);
1332   } else {
1333     IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1334                                      IVIncInsertPt);
1335   }
1336   if (!isa<ConstantInt>(StepV)) ++NumVariable;
1337
1338   PN->addIncoming(IncV, LatchBlock);
1339
1340   ++NumInserted;
1341   return PN;
1342 }
1343
1344 static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1345   // We want to emit code for users inside the loop first.  To do this, we
1346   // rearrange BasedUser so that the entries at the end have
1347   // isUseOfPostIncrementedValue = false, because we pop off the end of the
1348   // vector (so we handle them first).
1349   std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1350                  PartitionByIsUseOfPostIncrementedValue);
1351
1352   // Sort this by base, so that things with the same base are handled
1353   // together.  By partitioning first and stable-sorting later, we are
1354   // guaranteed that within each base we will pop off users from within the
1355   // loop before users outside of the loop with a particular base.
1356   //
1357   // We would like to use stable_sort here, but we can't.  The problem is that
1358   // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1359   // we don't have anything to do a '<' comparison on.  Because we think the
1360   // number of uses is small, do a horrible bubble sort which just relies on
1361   // ==.
1362   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1363     // Get a base value.
1364     SCEVHandle Base = UsersToProcess[i].Base;
1365
1366     // Compact everything with this base to be consecutive with this one.
1367     for (unsigned j = i+1; j != e; ++j) {
1368       if (UsersToProcess[j].Base == Base) {
1369         std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1370         ++i;
1371       }
1372     }
1373   }
1374 }
1375
1376 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1377 /// UsersToProcess, meaning lowering addresses all the way down to direct
1378 /// pointer arithmetic.
1379 ///
1380 void
1381 LoopStrengthReduce::PrepareToStrengthReduceFully(
1382                                         std::vector<BasedUser> &UsersToProcess,
1383                                         SCEVHandle Stride,
1384                                         SCEVHandle CommonExprs,
1385                                         const Loop *L,
1386                                         SCEVExpander &PreheaderRewriter) {
1387   DOUT << "  Fully reducing all users\n";
1388
1389   // Rewrite the UsersToProcess records, creating a separate PHI for each
1390   // unique Base value.
1391   Instruction *IVIncInsertPt = L->getLoopLatch()->getTerminator();
1392   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1393     // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1394     // pick the first Imm value here to start with, and adjust it for the
1395     // other uses.
1396     SCEVHandle Imm = UsersToProcess[i].Imm;
1397     SCEVHandle Base = UsersToProcess[i].Base;
1398     SCEVHandle Start = SE->getAddExpr(CommonExprs, Base, Imm);
1399     PHINode *Phi = InsertAffinePhi(Start, Stride, IVIncInsertPt, L,
1400                                    PreheaderRewriter);
1401     // Loop over all the users with the same base.
1402     do {
1403       UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1404       UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1405       UsersToProcess[i].Phi = Phi;
1406       assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1407              "ShouldUseFullStrengthReductionMode should reject this!");
1408     } while (++i != e && Base == UsersToProcess[i].Base);
1409   }
1410 }
1411
1412 /// FindIVIncInsertPt - Return the location to insert the increment instruction.
1413 /// If the only use if a use of postinc value, (must be the loop termination
1414 /// condition), then insert it just before the use.
1415 static Instruction *FindIVIncInsertPt(std::vector<BasedUser> &UsersToProcess,
1416                                       const Loop *L) {
1417   if (UsersToProcess.size() == 1 &&
1418       UsersToProcess[0].isUseOfPostIncrementedValue &&
1419       L->contains(UsersToProcess[0].Inst->getParent()))
1420     return UsersToProcess[0].Inst;
1421   return L->getLoopLatch()->getTerminator();
1422 }
1423
1424 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1425 /// given users to share.
1426 ///
1427 void
1428 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1429                                          std::vector<BasedUser> &UsersToProcess,
1430                                          SCEVHandle Stride,
1431                                          SCEVHandle CommonExprs,
1432                                          Value *CommonBaseV,
1433                                          Instruction *IVIncInsertPt,
1434                                          const Loop *L,
1435                                          SCEVExpander &PreheaderRewriter) {
1436   DOUT << "  Inserting new PHI:\n";
1437
1438   PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1439                                  Stride, IVIncInsertPt, L,
1440                                  PreheaderRewriter);
1441
1442   // Remember this in case a later stride is multiple of this.
1443   IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1444
1445   // All the users will share this new IV.
1446   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1447     UsersToProcess[i].Phi = Phi;
1448
1449   DOUT << "    IV=";
1450   DEBUG(WriteAsOperand(*DOUT, Phi, /*PrintType=*/false));
1451   DOUT << "\n";
1452 }
1453
1454 /// PrepareToStrengthReduceFromSmallerStride - Prepare for the given users to
1455 /// reuse an induction variable with a stride that is a factor of the current
1456 /// induction variable.
1457 ///
1458 void
1459 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1460                                          std::vector<BasedUser> &UsersToProcess,
1461                                          Value *CommonBaseV,
1462                                          const IVExpr &ReuseIV,
1463                                          Instruction *PreInsertPt) {
1464   DOUT << "  Rewriting in terms of existing IV of STRIDE " << *ReuseIV.Stride
1465        << " and BASE " << *ReuseIV.Base << "\n";
1466
1467   // All the users will share the reused IV.
1468   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1469     UsersToProcess[i].Phi = ReuseIV.PHI;
1470
1471   Constant *C = dyn_cast<Constant>(CommonBaseV);
1472   if (C &&
1473       (!C->isNullValue() &&
1474        !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1475                          TLI, false)))
1476     // We want the common base emitted into the preheader! This is just
1477     // using cast as a copy so BitCast (no-op cast) is appropriate
1478     CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1479                                   "commonbase", PreInsertPt);
1480 }
1481
1482 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1483                                     const Type *AccessTy,
1484                                    std::vector<BasedUser> &UsersToProcess,
1485                                    const TargetLowering *TLI) {
1486   SmallVector<Instruction*, 16> AddrModeInsts;
1487   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1488     if (UsersToProcess[i].isUseOfPostIncrementedValue)
1489       continue;
1490     ExtAddrMode AddrMode =
1491       AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1492                                    AccessTy, UsersToProcess[i].Inst,
1493                                    AddrModeInsts, *TLI);
1494     if (GV && GV != AddrMode.BaseGV)
1495       return false;
1496     if (Offset && !AddrMode.BaseOffs)
1497       // FIXME: How to accurate check it's immediate offset is folded.
1498       return false;
1499     AddrModeInsts.clear();
1500   }
1501   return true;
1502 }
1503
1504 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1505 /// stride of IV.  All of the users may have different starting values, and this
1506 /// may not be the only stride.
1507 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1508                                                       IVUsersOfOneStride &Uses,
1509                                                       Loop *L) {
1510   // If all the users are moved to another stride, then there is nothing to do.
1511   if (Uses.Users.empty())
1512     return;
1513
1514   // Keep track if every use in UsersToProcess is an address. If they all are,
1515   // we may be able to rewrite the entire collection of them in terms of a
1516   // smaller-stride IV.
1517   bool AllUsesAreAddresses = true;
1518
1519   // Keep track if every use of a single stride is outside the loop.  If so,
1520   // we want to be more aggressive about reusing a smaller-stride IV; a
1521   // multiply outside the loop is better than another IV inside.  Well, usually.
1522   bool AllUsesAreOutsideLoop = true;
1523
1524   // Transform our list of users and offsets to a bit more complex table.  In
1525   // this new vector, each 'BasedUser' contains 'Base' the base of the
1526   // strided accessas well as the old information from Uses.  We progressively
1527   // move information from the Base field to the Imm field, until we eventually
1528   // have the full access expression to rewrite the use.
1529   std::vector<BasedUser> UsersToProcess;
1530   SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1531                                           AllUsesAreOutsideLoop,
1532                                           UsersToProcess);
1533
1534   // Sort the UsersToProcess array so that users with common bases are
1535   // next to each other.
1536   SortUsersToProcess(UsersToProcess);
1537
1538   // If we managed to find some expressions in common, we'll need to carry
1539   // their value in a register and add it in for each use. This will take up
1540   // a register operand, which potentially restricts what stride values are
1541   // valid.
1542   bool HaveCommonExprs = !CommonExprs->isZero();
1543   const Type *ReplacedTy = CommonExprs->getType();
1544
1545   // If all uses are addresses, consider sinking the immediate part of the
1546   // common expression back into uses if they can fit in the immediate fields.
1547   if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1548     SCEVHandle NewCommon = CommonExprs;
1549     SCEVHandle Imm = SE->getIntegerSCEV(0, ReplacedTy);
1550     MoveImmediateValues(TLI, Type::VoidTy, NewCommon, Imm, true, L, SE);
1551     if (!Imm->isZero()) {
1552       bool DoSink = true;
1553
1554       // If the immediate part of the common expression is a GV, check if it's
1555       // possible to fold it into the target addressing mode.
1556       GlobalValue *GV = 0;
1557       if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
1558         GV = dyn_cast<GlobalValue>(SU->getValue());
1559       int64_t Offset = 0;
1560       if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
1561         Offset = SC->getValue()->getSExtValue();
1562       if (GV || Offset)
1563         // Pass VoidTy as the AccessTy to be conservative, because
1564         // there could be multiple access types among all the uses.
1565         DoSink = IsImmFoldedIntoAddrMode(GV, Offset, Type::VoidTy,
1566                                          UsersToProcess, TLI);
1567
1568       if (DoSink) {
1569         DOUT << "  Sinking " << *Imm << " back down into uses\n";
1570         for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1571           UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1572         CommonExprs = NewCommon;
1573         HaveCommonExprs = !CommonExprs->isZero();
1574         ++NumImmSunk;
1575       }
1576     }
1577   }
1578
1579   // Now that we know what we need to do, insert the PHI node itself.
1580   //
1581   DOUT << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1582        << *Stride << ":\n"
1583        << "  Common base: " << *CommonExprs << "\n";
1584
1585   SCEVExpander Rewriter(*SE);
1586   SCEVExpander PreheaderRewriter(*SE);
1587
1588   BasicBlock  *Preheader = L->getLoopPreheader();
1589   Instruction *PreInsertPt = Preheader->getTerminator();
1590   BasicBlock *LatchBlock = L->getLoopLatch();
1591   Instruction *IVIncInsertPt = LatchBlock->getTerminator();
1592
1593   Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
1594
1595   SCEVHandle RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1596   IVExpr   ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1597                    SE->getIntegerSCEV(0, Type::Int32Ty),
1598                    0);
1599
1600   /// Choose a strength-reduction strategy and prepare for it by creating
1601   /// the necessary PHIs and adjusting the bookkeeping.
1602   if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1603                                          AllUsesAreAddresses, Stride)) {
1604     PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1605                                  PreheaderRewriter);
1606   } else {
1607     // Emit the initial base value into the loop preheader.
1608     CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1609                                                   PreInsertPt);
1610
1611     // If all uses are addresses, check if it is possible to reuse an IV.  The
1612     // new IV must have a stride that is a multiple of the old stride; the
1613     // multiple must be a number that can be encoded in the scale field of the
1614     // target addressing mode; and we must have a valid instruction after this 
1615     // substitution, including the immediate field, if any.
1616     RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1617                                     AllUsesAreOutsideLoop,
1618                                     Stride, ReuseIV, ReplacedTy,
1619                                     UsersToProcess);
1620     if (!RewriteFactor->isZero())
1621       PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1622                                                ReuseIV, PreInsertPt);
1623     else {
1624       IVIncInsertPt = FindIVIncInsertPt(UsersToProcess, L);
1625       PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1626                                         CommonBaseV, IVIncInsertPt,
1627                                         L, PreheaderRewriter);
1628     }
1629   }
1630
1631   // Process all the users now, replacing their strided uses with
1632   // strength-reduced forms.  This outer loop handles all bases, the inner
1633   // loop handles all users of a particular base.
1634   while (!UsersToProcess.empty()) {
1635     SCEVHandle Base = UsersToProcess.back().Base;
1636     Instruction *Inst = UsersToProcess.back().Inst;
1637
1638     // Emit the code for Base into the preheader.
1639     Value *BaseV = 0;
1640     if (!Base->isZero()) {
1641       BaseV = PreheaderRewriter.expandCodeFor(Base, 0, PreInsertPt);
1642
1643       DOUT << "  INSERTING code for BASE = " << *Base << ":";
1644       if (BaseV->hasName())
1645         DOUT << " Result value name = %" << BaseV->getNameStr();
1646       DOUT << "\n";
1647
1648       // If BaseV is a non-zero constant, make sure that it gets inserted into
1649       // the preheader, instead of being forward substituted into the uses.  We
1650       // do this by forcing a BitCast (noop cast) to be inserted into the
1651       // preheader in this case.
1652       if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false)) {
1653         // We want this constant emitted into the preheader! This is just
1654         // using cast as a copy so BitCast (no-op cast) is appropriate
1655         BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1656                                 PreInsertPt);       
1657       }
1658     }
1659
1660     // Emit the code to add the immediate offset to the Phi value, just before
1661     // the instructions that we identified as using this stride and base.
1662     do {
1663       // FIXME: Use emitted users to emit other users.
1664       BasedUser &User = UsersToProcess.back();
1665
1666       DOUT << "    Examining ";
1667       if (User.isUseOfPostIncrementedValue)
1668         DOUT << "postinc";
1669       else
1670         DOUT << "preinc";
1671       DOUT << " use ";
1672       DEBUG(WriteAsOperand(*DOUT, UsersToProcess.back().OperandValToReplace,
1673                            /*PrintType=*/false));
1674       DOUT << " in Inst: " << *(User.Inst);
1675
1676       // If this instruction wants to use the post-incremented value, move it
1677       // after the post-inc and use its value instead of the PHI.
1678       Value *RewriteOp = User.Phi;
1679       if (User.isUseOfPostIncrementedValue) {
1680         RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1681         // If this user is in the loop, make sure it is the last thing in the
1682         // loop to ensure it is dominated by the increment. In case it's the
1683         // only use of the iv, the increment instruction is already before the
1684         // use.
1685         if (L->contains(User.Inst->getParent()) && User.Inst != IVIncInsertPt)
1686           User.Inst->moveBefore(IVIncInsertPt);
1687       }
1688
1689       SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
1690
1691       if (SE->getEffectiveSCEVType(RewriteOp->getType()) !=
1692           SE->getEffectiveSCEVType(ReplacedTy)) {
1693         assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1694                SE->getTypeSizeInBits(ReplacedTy) &&
1695                "Unexpected widening cast!");
1696         RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1697       }
1698
1699       // If we had to insert new instructions for RewriteOp, we have to
1700       // consider that they may not have been able to end up immediately
1701       // next to RewriteOp, because non-PHI instructions may never precede
1702       // PHI instructions in a block. In this case, remember where the last
1703       // instruction was inserted so that if we're replacing a different
1704       // PHI node, we can use the later point to expand the final
1705       // RewriteExpr.
1706       Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
1707       if (RewriteOp == User.Phi) NewBasePt = 0;
1708
1709       // Clear the SCEVExpander's expression map so that we are guaranteed
1710       // to have the code emitted where we expect it.
1711       Rewriter.clear();
1712
1713       // If we are reusing the iv, then it must be multiplied by a constant
1714       // factor to take advantage of the addressing mode scale component.
1715       if (!RewriteFactor->isZero()) {
1716         // If we're reusing an IV with a nonzero base (currently this happens
1717         // only when all reuses are outside the loop) subtract that base here.
1718         // The base has been used to initialize the PHI node but we don't want
1719         // it here.
1720         if (!ReuseIV.Base->isZero()) {
1721           SCEVHandle typedBase = ReuseIV.Base;
1722           if (SE->getEffectiveSCEVType(RewriteExpr->getType()) !=
1723               SE->getEffectiveSCEVType(ReuseIV.Base->getType())) {
1724             // It's possible the original IV is a larger type than the new IV,
1725             // in which case we have to truncate the Base.  We checked in
1726             // RequiresTypeConversion that this is valid.
1727             assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1728                    SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
1729                    "Unexpected lengthening conversion!");
1730             typedBase = SE->getTruncateExpr(ReuseIV.Base, 
1731                                             RewriteExpr->getType());
1732           }
1733           RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1734         }
1735
1736         // Multiply old variable, with base removed, by new scale factor.
1737         RewriteExpr = SE->getMulExpr(RewriteFactor,
1738                                      RewriteExpr);
1739
1740         // The common base is emitted in the loop preheader. But since we
1741         // are reusing an IV, it has not been used to initialize the PHI node.
1742         // Add it to the expression used to rewrite the uses.
1743         // When this use is outside the loop, we earlier subtracted the
1744         // common base, and are adding it back here.  Use the same expression
1745         // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1746         if (!CommonExprs->isZero()) {
1747           if (L->contains(User.Inst->getParent()))
1748             RewriteExpr = SE->getAddExpr(RewriteExpr,
1749                                        SE->getUnknown(CommonBaseV));
1750           else
1751             RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1752         }
1753       }
1754
1755       // Now that we know what we need to do, insert code before User for the
1756       // immediate and any loop-variant expressions.
1757       if (BaseV)
1758         // Add BaseV to the PHI value if needed.
1759         RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1760
1761       User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1762                                           Rewriter, L, this, *LI,
1763                                           DeadInsts);
1764
1765       // Mark old value we replaced as possibly dead, so that it is eliminated
1766       // if we just replaced the last use of that value.
1767       DeadInsts.push_back(User.OperandValToReplace);
1768
1769       UsersToProcess.pop_back();
1770       ++NumReduced;
1771
1772       // If there are any more users to process with the same base, process them
1773       // now.  We sorted by base above, so we just have to check the last elt.
1774     } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1775     // TODO: Next, find out which base index is the most common, pull it out.
1776   }
1777
1778   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1779   // different starting values, into different PHIs.
1780 }
1781
1782 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1783 /// set the IV user and stride information and return true, otherwise return
1784 /// false.
1785 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
1786                                        const SCEVHandle *&CondStride) {
1787   for (unsigned Stride = 0, e = IU->StrideOrder.size();
1788        Stride != e && !CondUse; ++Stride) {
1789     std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
1790       IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
1791     assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
1792
1793     for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1794          E = SI->second->Users.end(); UI != E; ++UI)
1795       if (UI->getUser() == Cond) {
1796         // NOTE: we could handle setcc instructions with multiple uses here, but
1797         // InstCombine does it as well for simple uses, it's not clear that it
1798         // occurs enough in real life to handle.
1799         CondUse = UI;
1800         CondStride = &SI->first;
1801         return true;
1802       }
1803   }
1804   return false;
1805 }    
1806
1807 namespace {
1808   // Constant strides come first which in turns are sorted by their absolute
1809   // values. If absolute values are the same, then positive strides comes first.
1810   // e.g.
1811   // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1812   struct StrideCompare {
1813     const ScalarEvolution *SE;
1814     explicit StrideCompare(const ScalarEvolution *se) : SE(se) {}
1815
1816     bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1817       const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1818       const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1819       if (LHSC && RHSC) {
1820         int64_t  LV = LHSC->getValue()->getSExtValue();
1821         int64_t  RV = RHSC->getValue()->getSExtValue();
1822         uint64_t ALV = (LV < 0) ? -LV : LV;
1823         uint64_t ARV = (RV < 0) ? -RV : RV;
1824         if (ALV == ARV) {
1825           if (LV != RV)
1826             return LV > RV;
1827         } else {
1828           return ALV < ARV;
1829         }
1830
1831         // If it's the same value but different type, sort by bit width so
1832         // that we emit larger induction variables before smaller
1833         // ones, letting the smaller be re-written in terms of larger ones.
1834         return SE->getTypeSizeInBits(RHS->getType()) <
1835                SE->getTypeSizeInBits(LHS->getType());
1836       }
1837       return LHSC && !RHSC;
1838     }
1839   };
1840 }
1841
1842 /// ChangeCompareStride - If a loop termination compare instruction is the
1843 /// only use of its stride, and the compaison is against a constant value,
1844 /// try eliminate the stride by moving the compare instruction to another
1845 /// stride and change its constant operand accordingly. e.g.
1846 ///
1847 /// loop:
1848 /// ...
1849 /// v1 = v1 + 3
1850 /// v2 = v2 + 1
1851 /// if (v2 < 10) goto loop
1852 /// =>
1853 /// loop:
1854 /// ...
1855 /// v1 = v1 + 3
1856 /// if (v1 < 30) goto loop
1857 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
1858                                                 IVStrideUse* &CondUse,
1859                                                 const SCEVHandle* &CondStride) {
1860   // If there's only one stride in the loop, there's nothing to do here.
1861   if (IU->StrideOrder.size() < 2)
1862     return Cond;
1863   // If there are other users of the condition's stride, don't bother
1864   // trying to change the condition because the stride will still
1865   // remain.
1866   std::map<SCEVHandle, IVUsersOfOneStride *>::iterator I =
1867     IU->IVUsesByStride.find(*CondStride);
1868   if (I == IU->IVUsesByStride.end() ||
1869       I->second->Users.size() != 1)
1870     return Cond;
1871   // Only handle constant strides for now.
1872   const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
1873   if (!SC) return Cond;
1874
1875   ICmpInst::Predicate Predicate = Cond->getPredicate();
1876   int64_t CmpSSInt = SC->getValue()->getSExtValue();
1877   unsigned BitWidth = SE->getTypeSizeInBits((*CondStride)->getType());
1878   uint64_t SignBit = 1ULL << (BitWidth-1);
1879   const Type *CmpTy = Cond->getOperand(0)->getType();
1880   const Type *NewCmpTy = NULL;
1881   unsigned TyBits = SE->getTypeSizeInBits(CmpTy);
1882   unsigned NewTyBits = 0;
1883   SCEVHandle *NewStride = NULL;
1884   Value *NewCmpLHS = NULL;
1885   Value *NewCmpRHS = NULL;
1886   int64_t Scale = 1;
1887   SCEVHandle NewOffset = SE->getIntegerSCEV(0, CmpTy);
1888
1889   if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
1890     int64_t CmpVal = C->getValue().getSExtValue();
1891
1892     // Check stride constant and the comparision constant signs to detect
1893     // overflow.
1894     if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
1895       return Cond;
1896
1897     // Look for a suitable stride / iv as replacement.
1898     for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
1899       std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
1900         IU->IVUsesByStride.find(IU->StrideOrder[i]);
1901       if (!isa<SCEVConstant>(SI->first))
1902         continue;
1903       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1904       if (SSInt == CmpSSInt ||
1905           abs64(SSInt) < abs64(CmpSSInt) ||
1906           (SSInt % CmpSSInt) != 0)
1907         continue;
1908
1909       Scale = SSInt / CmpSSInt;
1910       int64_t NewCmpVal = CmpVal * Scale;
1911       APInt Mul = APInt(BitWidth*2, CmpVal, true);
1912       Mul = Mul * APInt(BitWidth*2, Scale, true);
1913       // Check for overflow.
1914       if (!Mul.isSignedIntN(BitWidth))
1915         continue;
1916       // Check for overflow in the stride's type too.
1917       if (!Mul.isSignedIntN(SE->getTypeSizeInBits(SI->first->getType())))
1918         continue;
1919
1920       // Watch out for overflow.
1921       if (ICmpInst::isSignedPredicate(Predicate) &&
1922           (CmpVal & SignBit) != (NewCmpVal & SignBit))
1923         continue;
1924
1925       if (NewCmpVal == CmpVal)
1926         continue;
1927       // Pick the best iv to use trying to avoid a cast.
1928       NewCmpLHS = NULL;
1929       for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1930              E = SI->second->Users.end(); UI != E; ++UI) {
1931         Value *Op = UI->getOperandValToReplace();
1932
1933         // If the IVStrideUse implies a cast, check for an actual cast which
1934         // can be used to find the original IV expression.
1935         if (SE->getEffectiveSCEVType(Op->getType()) !=
1936             SE->getEffectiveSCEVType(SI->first->getType())) {
1937           CastInst *CI = dyn_cast<CastInst>(Op);
1938           // If it's not a simple cast, it's complicated.
1939           if (!CI)
1940             continue;
1941           // If it's a cast from a type other than the stride type,
1942           // it's complicated.
1943           if (CI->getOperand(0)->getType() != SI->first->getType())
1944             continue;
1945           // Ok, we found the IV expression in the stride's type.
1946           Op = CI->getOperand(0);
1947         }
1948
1949         NewCmpLHS = Op;
1950         if (NewCmpLHS->getType() == CmpTy)
1951           break;
1952       }
1953       if (!NewCmpLHS)
1954         continue;
1955
1956       NewCmpTy = NewCmpLHS->getType();
1957       NewTyBits = SE->getTypeSizeInBits(NewCmpTy);
1958       const Type *NewCmpIntTy = IntegerType::get(NewTyBits);
1959       if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
1960         // Check if it is possible to rewrite it using
1961         // an iv / stride of a smaller integer type.
1962         unsigned Bits = NewTyBits;
1963         if (ICmpInst::isSignedPredicate(Predicate))
1964           --Bits;
1965         uint64_t Mask = (1ULL << Bits) - 1;
1966         if (((uint64_t)NewCmpVal & Mask) != (uint64_t)NewCmpVal)
1967           continue;
1968       }
1969
1970       // Don't rewrite if use offset is non-constant and the new type is
1971       // of a different type.
1972       // FIXME: too conservative?
1973       if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->getOffset()))
1974         continue;
1975
1976       bool AllUsesAreAddresses = true;
1977       bool AllUsesAreOutsideLoop = true;
1978       std::vector<BasedUser> UsersToProcess;
1979       SCEVHandle CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
1980                                               AllUsesAreAddresses,
1981                                               AllUsesAreOutsideLoop,
1982                                               UsersToProcess);
1983       // Avoid rewriting the compare instruction with an iv of new stride
1984       // if it's likely the new stride uses will be rewritten using the
1985       // stride of the compare instruction.
1986       if (AllUsesAreAddresses &&
1987           ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
1988         continue;
1989
1990       // If scale is negative, use swapped predicate unless it's testing
1991       // for equality.
1992       if (Scale < 0 && !Cond->isEquality())
1993         Predicate = ICmpInst::getSwappedPredicate(Predicate);
1994
1995       NewStride = &IU->StrideOrder[i];
1996       if (!isa<PointerType>(NewCmpTy))
1997         NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
1998       else {
1999         ConstantInt *CI = ConstantInt::get(NewCmpIntTy, NewCmpVal);
2000         NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
2001       }
2002       NewOffset = TyBits == NewTyBits
2003         ? SE->getMulExpr(CondUse->getOffset(),
2004                          SE->getConstant(ConstantInt::get(CmpTy, Scale)))
2005         : SE->getConstant(ConstantInt::get(NewCmpIntTy,
2006           cast<SCEVConstant>(CondUse->getOffset())->getValue()
2007             ->getSExtValue()*Scale));
2008       break;
2009     }
2010   }
2011
2012   // Forgo this transformation if it the increment happens to be
2013   // unfortunately positioned after the condition, and the condition
2014   // has multiple uses which prevent it from being moved immediately
2015   // before the branch. See
2016   // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2017   // for an example of this situation.
2018   if (!Cond->hasOneUse()) {
2019     for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2020          I != E; ++I)
2021       if (I == NewCmpLHS)
2022         return Cond;
2023   }
2024
2025   if (NewCmpRHS) {
2026     // Create a new compare instruction using new stride / iv.
2027     ICmpInst *OldCond = Cond;
2028     // Insert new compare instruction.
2029     Cond = new ICmpInst(Predicate, NewCmpLHS, NewCmpRHS,
2030                         L->getHeader()->getName() + ".termcond",
2031                         OldCond);
2032
2033     // Remove the old compare instruction. The old indvar is probably dead too.
2034     DeadInsts.push_back(CondUse->getOperandValToReplace());
2035     OldCond->replaceAllUsesWith(Cond);
2036     OldCond->eraseFromParent();
2037
2038     IU->IVUsesByStride[*NewStride]->addUser(NewOffset, Cond, NewCmpLHS, false);
2039     CondUse = &IU->IVUsesByStride[*NewStride]->Users.back();
2040     CondStride = NewStride;
2041     ++NumEliminated;
2042     Changed = true;
2043   }
2044
2045   return Cond;
2046 }
2047
2048 /// OptimizeSMax - Rewrite the loop's terminating condition if it uses
2049 /// an smax computation.
2050 ///
2051 /// This is a narrow solution to a specific, but acute, problem. For loops
2052 /// like this:
2053 ///
2054 ///   i = 0;
2055 ///   do {
2056 ///     p[i] = 0.0;
2057 ///   } while (++i < n);
2058 ///
2059 /// where the comparison is signed, the trip count isn't just 'n', because
2060 /// 'n' could be negative. And unfortunately this can come up even for loops
2061 /// where the user didn't use a C do-while loop. For example, seemingly
2062 /// well-behaved top-test loops will commonly be lowered like this:
2063 //
2064 ///   if (n > 0) {
2065 ///     i = 0;
2066 ///     do {
2067 ///       p[i] = 0.0;
2068 ///     } while (++i < n);
2069 ///   }
2070 ///
2071 /// and then it's possible for subsequent optimization to obscure the if
2072 /// test in such a way that indvars can't find it.
2073 ///
2074 /// When indvars can't find the if test in loops like this, it creates a
2075 /// signed-max expression, which allows it to give the loop a canonical
2076 /// induction variable:
2077 ///
2078 ///   i = 0;
2079 ///   smax = n < 1 ? 1 : n;
2080 ///   do {
2081 ///     p[i] = 0.0;
2082 ///   } while (++i != smax);
2083 ///
2084 /// Canonical induction variables are necessary because the loop passes
2085 /// are designed around them. The most obvious example of this is the
2086 /// LoopInfo analysis, which doesn't remember trip count values. It
2087 /// expects to be able to rediscover the trip count each time it is
2088 /// needed, and it does this using a simple analyis that only succeeds if
2089 /// the loop has a canonical induction variable.
2090 ///
2091 /// However, when it comes time to generate code, the maximum operation
2092 /// can be quite costly, especially if it's inside of an outer loop.
2093 ///
2094 /// This function solves this problem by detecting this type of loop and
2095 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2096 /// the instructions for the maximum computation.
2097 ///
2098 ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
2099                                            IVStrideUse* &CondUse) {
2100   // Check that the loop matches the pattern we're looking for.
2101   if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2102       Cond->getPredicate() != CmpInst::ICMP_NE)
2103     return Cond;
2104
2105   SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2106   if (!Sel || !Sel->hasOneUse()) return Cond;
2107
2108   SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2109   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2110     return Cond;
2111   SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2112
2113   // Add one to the backedge-taken count to get the trip count.
2114   SCEVHandle IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
2115
2116   // Check for a max calculation that matches the pattern.
2117   const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
2118   if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
2119
2120   SCEVHandle SMaxLHS = SMax->getOperand(0);
2121   SCEVHandle SMaxRHS = SMax->getOperand(1);
2122   if (!SMaxLHS || SMaxLHS != One) return Cond;
2123
2124   // Check the relevant induction variable for conformance to
2125   // the pattern.
2126   SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2127   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2128   if (!AR || !AR->isAffine() ||
2129       AR->getStart() != One ||
2130       AR->getStepRecurrence(*SE) != One)
2131     return Cond;
2132
2133   assert(AR->getLoop() == L &&
2134          "Loop condition operand is an addrec in a different loop!");
2135
2136   // Check the right operand of the select, and remember it, as it will
2137   // be used in the new comparison instruction.
2138   Value *NewRHS = 0;
2139   if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
2140     NewRHS = Sel->getOperand(1);
2141   else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
2142     NewRHS = Sel->getOperand(2);
2143   if (!NewRHS) return Cond;
2144
2145   // Ok, everything looks ok to change the condition into an SLT or SGE and
2146   // delete the max calculation.
2147   ICmpInst *NewCond =
2148     new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
2149                    CmpInst::ICMP_SLT :
2150                    CmpInst::ICMP_SGE,
2151                  Cond->getOperand(0), NewRHS, "scmp", Cond);
2152
2153   // Delete the max calculation instructions.
2154   Cond->replaceAllUsesWith(NewCond);
2155   CondUse->setUser(NewCond);
2156   Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2157   Cond->eraseFromParent();
2158   Sel->eraseFromParent();
2159   if (Cmp->use_empty())
2160     Cmp->eraseFromParent();
2161   return NewCond;
2162 }
2163
2164 /// OptimizeShadowIV - If IV is used in a int-to-float cast
2165 /// inside the loop then try to eliminate the cast opeation.
2166 void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2167
2168   SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2169   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2170     return;
2171
2172   for (unsigned Stride = 0, e = IU->StrideOrder.size(); Stride != e;
2173        ++Stride) {
2174     std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2175       IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2176     assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2177     if (!isa<SCEVConstant>(SI->first))
2178       continue;
2179
2180     for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
2181            E = SI->second->Users.end(); UI != E; /* empty */) {
2182       ilist<IVStrideUse>::iterator CandidateUI = UI;
2183       ++UI;
2184       Instruction *ShadowUse = CandidateUI->getUser();
2185       const Type *DestTy = NULL;
2186
2187       /* If shadow use is a int->float cast then insert a second IV
2188          to eliminate this cast.
2189
2190            for (unsigned i = 0; i < n; ++i) 
2191              foo((double)i);
2192
2193          is transformed into
2194
2195            double d = 0.0;
2196            for (unsigned i = 0; i < n; ++i, ++d) 
2197              foo(d);
2198       */
2199       if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
2200         DestTy = UCast->getDestTy();
2201       else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
2202         DestTy = SCast->getDestTy();
2203       if (!DestTy) continue;
2204
2205       if (TLI) {
2206         // If target does not support DestTy natively then do not apply
2207         // this transformation.
2208         MVT DVT = TLI->getValueType(DestTy);
2209         if (!TLI->isTypeLegal(DVT)) continue;
2210       }
2211
2212       PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2213       if (!PH) continue;
2214       if (PH->getNumIncomingValues() != 2) continue;
2215
2216       const Type *SrcTy = PH->getType();
2217       int Mantissa = DestTy->getFPMantissaWidth();
2218       if (Mantissa == -1) continue; 
2219       if ((int)SE->getTypeSizeInBits(SrcTy) > Mantissa)
2220         continue;
2221
2222       unsigned Entry, Latch;
2223       if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2224         Entry = 0;
2225         Latch = 1;
2226       } else {
2227         Entry = 1;
2228         Latch = 0;
2229       }
2230         
2231       ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2232       if (!Init) continue;
2233       ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2234
2235       BinaryOperator *Incr = 
2236         dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2237       if (!Incr) continue;
2238       if (Incr->getOpcode() != Instruction::Add
2239           && Incr->getOpcode() != Instruction::Sub)
2240         continue;
2241
2242       /* Initialize new IV, double d = 0.0 in above example. */
2243       ConstantInt *C = NULL;
2244       if (Incr->getOperand(0) == PH)
2245         C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2246       else if (Incr->getOperand(1) == PH)
2247         C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2248       else
2249         continue;
2250
2251       if (!C) continue;
2252
2253       /* Add new PHINode. */
2254       PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2255
2256       /* create new increment. '++d' in above example. */
2257       ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2258       BinaryOperator *NewIncr = 
2259         BinaryOperator::Create(Incr->getOpcode(),
2260                                NewPH, CFP, "IV.S.next.", Incr);
2261
2262       NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2263       NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2264
2265       /* Remove cast operation */
2266       ShadowUse->replaceAllUsesWith(NewPH);
2267       ShadowUse->eraseFromParent();
2268       NumShadow++;
2269       break;
2270     }
2271   }
2272 }
2273
2274 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2275 // uses in the loop, look to see if we can eliminate some, in favor of using
2276 // common indvars for the different uses.
2277 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2278   // TODO: implement optzns here.
2279
2280   OptimizeShadowIV(L);
2281 }
2282
2283 /// OptimizeLoopTermCond - Change loop terminating condition to use the 
2284 /// postinc iv when possible.
2285 void LoopStrengthReduce::OptimizeLoopTermCond(Loop *L) {
2286   // Finally, get the terminating condition for the loop if possible.  If we
2287   // can, we want to change it to use a post-incremented version of its
2288   // induction variable, to allow coalescing the live ranges for the IV into
2289   // one register value.
2290   BasicBlock *LatchBlock = L->getLoopLatch();
2291   BasicBlock *ExitBlock = L->getExitingBlock();
2292   if (!ExitBlock)
2293     // Multiple exits, just look at the exit in the latch block if there is one.
2294     ExitBlock = LatchBlock;
2295   BranchInst *TermBr = dyn_cast<BranchInst>(ExitBlock->getTerminator());
2296   if (!TermBr)
2297     return;
2298   if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2299     return;
2300
2301   // Search IVUsesByStride to find Cond's IVUse if there is one.
2302   IVStrideUse *CondUse = 0;
2303   const SCEVHandle *CondStride = 0;
2304   ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2305   if (!FindIVUserForCond(Cond, CondUse, CondStride))
2306     return; // setcc doesn't use the IV.
2307
2308   if (ExitBlock != LatchBlock) {
2309     if (!Cond->hasOneUse())
2310       // See below, we don't want the condition to be cloned.
2311       return;
2312
2313     // If exiting block is the latch block, we know it's safe and profitable to
2314     // transform the icmp to use post-inc iv. Otherwise do so only if it would
2315     // not reuse another iv and its iv would be reused by other uses. We are
2316     // optimizing for the case where the icmp is the only use of the iv.
2317     IVUsersOfOneStride &StrideUses = *IU->IVUsesByStride[*CondStride];
2318     for (ilist<IVStrideUse>::iterator I = StrideUses.Users.begin(),
2319          E = StrideUses.Users.end(); I != E; ++I) {
2320       if (I->getUser() == Cond)
2321         continue;
2322       if (!I->isUseOfPostIncrementedValue())
2323         return;
2324     }
2325
2326     // FIXME: This is expensive, and worse still ChangeCompareStride does a
2327     // similar check. Can we perform all the icmp related transformations after
2328     // StrengthReduceStridedIVUsers?
2329     if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride)) {
2330       int64_t SInt = SC->getValue()->getSExtValue();
2331       for (unsigned NewStride = 0, ee = IU->StrideOrder.size(); NewStride != ee;
2332            ++NewStride) {
2333         std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2334           IU->IVUsesByStride.find(IU->StrideOrder[NewStride]);
2335         if (!isa<SCEVConstant>(SI->first) || SI->first == *CondStride)
2336           continue;
2337         int64_t SSInt =
2338           cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2339         if (SSInt == SInt)
2340           return; // This can definitely be reused.
2341         if (unsigned(abs64(SSInt)) < SInt || (SSInt % SInt) != 0)
2342           continue;
2343         int64_t Scale = SSInt / SInt;
2344         bool AllUsesAreAddresses = true;
2345         bool AllUsesAreOutsideLoop = true;
2346         std::vector<BasedUser> UsersToProcess;
2347         SCEVHandle CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
2348                                                 AllUsesAreAddresses,
2349                                                 AllUsesAreOutsideLoop,
2350                                                 UsersToProcess);
2351         // Avoid rewriting the compare instruction with an iv of new stride
2352         // if it's likely the new stride uses will be rewritten using the
2353         // stride of the compare instruction.
2354         if (AllUsesAreAddresses &&
2355             ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
2356           return;
2357       }
2358     }
2359
2360     StrideNoReuse.insert(*CondStride);
2361   }
2362
2363   // If the trip count is computed in terms of an smax (due to ScalarEvolution
2364   // being unable to find a sufficient guard, for example), change the loop
2365   // comparison to use SLT instead of NE.
2366   Cond = OptimizeSMax(L, Cond, CondUse);
2367
2368   // If possible, change stride and operands of the compare instruction to
2369   // eliminate one stride.
2370   if (ExitBlock == LatchBlock)
2371     Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
2372
2373   // It's possible for the setcc instruction to be anywhere in the loop, and
2374   // possible for it to have multiple users.  If it is not immediately before
2375   // the latch block branch, move it.
2376   if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2377     if (Cond->hasOneUse()) {   // Condition has a single use, just move it.
2378       Cond->moveBefore(TermBr);
2379     } else {
2380       // Otherwise, clone the terminating condition and insert into the loopend.
2381       Cond = cast<ICmpInst>(Cond->clone());
2382       Cond->setName(L->getHeader()->getName() + ".termcond");
2383       LatchBlock->getInstList().insert(TermBr, Cond);
2384       
2385       // Clone the IVUse, as the old use still exists!
2386       IU->IVUsesByStride[*CondStride]->addUser(CondUse->getOffset(), Cond,
2387                                               CondUse->getOperandValToReplace(),
2388                                                false);
2389       CondUse = &IU->IVUsesByStride[*CondStride]->Users.back();
2390     }
2391   }
2392
2393   // If we get to here, we know that we can transform the setcc instruction to
2394   // use the post-incremented version of the IV, allowing us to coalesce the
2395   // live ranges for the IV correctly.
2396   CondUse->setOffset(SE->getMinusSCEV(CondUse->getOffset(), *CondStride));
2397   CondUse->setIsUseOfPostIncrementedValue(true);
2398   Changed = true;
2399
2400   ++NumLoopCond;
2401 }
2402
2403 // OptimizeLoopCountIV - If, after all sharing of IVs, the IV used for deciding
2404 // when to exit the loop is used only for that purpose, try to rearrange things
2405 // so it counts down to a test against zero.
2406 void LoopStrengthReduce::OptimizeLoopCountIV(Loop *L) {
2407
2408   // If the number of times the loop is executed isn't computable, give up.
2409   SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2410   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2411     return;
2412
2413   // Get the terminating condition for the loop if possible (this isn't
2414   // necessarily in the latch, or a block that's a predecessor of the header).
2415   SmallVector<BasicBlock*, 8> ExitBlocks;
2416   L->getExitBlocks(ExitBlocks);
2417   if (ExitBlocks.size() != 1) return;
2418
2419   // Okay, there is one exit block.  Try to find the condition that causes the
2420   // loop to be exited.
2421   BasicBlock *ExitBlock = ExitBlocks[0];
2422
2423   BasicBlock *ExitingBlock = 0;
2424   for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2425        PI != E; ++PI)
2426     if (L->contains(*PI)) {
2427       if (ExitingBlock == 0)
2428         ExitingBlock = *PI;
2429       else
2430         return; // More than one block exiting!
2431     }
2432   assert(ExitingBlock && "No exits from loop, something is broken!");
2433
2434   // Okay, we've computed the exiting block.  See what condition causes us to
2435   // exit.
2436   //
2437   // FIXME: we should be able to handle switch instructions (with a single exit)
2438   BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2439   if (TermBr == 0) return;
2440   assert(TermBr->isConditional() && "If unconditional, it can't be in loop!");
2441   if (!isa<ICmpInst>(TermBr->getCondition()))
2442     return;
2443   ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2444
2445   // Handle only tests for equality for the moment, and only stride 1.
2446   if (Cond->getPredicate() != CmpInst::ICMP_EQ)
2447     return;
2448   SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2449   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2450   SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2451   if (!AR || !AR->isAffine() || AR->getStepRecurrence(*SE) != One)
2452     return;
2453
2454   // Make sure the IV is only used for counting.  Value may be preinc or
2455   // postinc; 2 uses in either case.
2456   if (!Cond->getOperand(0)->hasNUses(2))
2457     return;
2458   PHINode *phi = dyn_cast<PHINode>(Cond->getOperand(0));
2459   Instruction *incr;
2460   if (phi && phi->getParent()==L->getHeader()) {
2461     // value tested is preinc.  Find the increment.
2462     // A CmpInst is not a BinaryOperator; we depend on this.
2463     Instruction::use_iterator UI = phi->use_begin();
2464     incr = dyn_cast<BinaryOperator>(UI);
2465     if (!incr)
2466       incr = dyn_cast<BinaryOperator>(++UI);
2467     // 1 use for postinc value, the phi.  Unnecessarily conservative?
2468     if (!incr || !incr->hasOneUse() || incr->getOpcode()!=Instruction::Add)
2469       return;
2470   } else {
2471     // Value tested is postinc.  Find the phi node.
2472     incr = dyn_cast<BinaryOperator>(Cond->getOperand(0));
2473     if (!incr || incr->getOpcode()!=Instruction::Add)
2474       return;
2475
2476     Instruction::use_iterator UI = Cond->getOperand(0)->use_begin();
2477     phi = dyn_cast<PHINode>(UI);
2478     if (!phi)
2479       phi = dyn_cast<PHINode>(++UI);
2480     // 1 use for preinc value, the increment.
2481     if (!phi || phi->getParent()!=L->getHeader() || !phi->hasOneUse())
2482       return;
2483   }
2484
2485   // Replace the increment with a decrement.
2486   BinaryOperator *decr = 
2487     BinaryOperator::Create(Instruction::Sub, incr->getOperand(0),
2488                            incr->getOperand(1), "tmp", incr);
2489   incr->replaceAllUsesWith(decr);
2490   incr->eraseFromParent();
2491
2492   // Substitute endval-startval for the original startval, and 0 for the
2493   // original endval.  Since we're only testing for equality this is OK even 
2494   // if the computation wraps around.
2495   BasicBlock  *Preheader = L->getLoopPreheader();
2496   Instruction *PreInsertPt = Preheader->getTerminator();
2497   int inBlock = L->contains(phi->getIncomingBlock(0)) ? 1 : 0;
2498   Value *startVal = phi->getIncomingValue(inBlock);
2499   Value *endVal = Cond->getOperand(1);
2500   // FIXME check for case where both are constant
2501   ConstantInt* Zero = ConstantInt::get(Cond->getOperand(1)->getType(), 0);
2502   BinaryOperator *NewStartVal = 
2503     BinaryOperator::Create(Instruction::Sub, endVal, startVal,
2504                            "tmp", PreInsertPt);
2505   phi->setIncomingValue(inBlock, NewStartVal);
2506   Cond->setOperand(1, Zero);
2507
2508   Changed = true;
2509 }
2510
2511 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
2512
2513   IU = &getAnalysis<IVUsers>();
2514   LI = &getAnalysis<LoopInfo>();
2515   DT = &getAnalysis<DominatorTree>();
2516   SE = &getAnalysis<ScalarEvolution>();
2517   Changed = false;
2518
2519   if (!IU->IVUsesByStride.empty()) {
2520 #ifndef NDEBUG
2521     DOUT << "\nLSR on \"" << L->getHeader()->getParent()->getNameStart()
2522          << "\" ";
2523     DEBUG(L->dump());
2524 #endif
2525
2526     // Sort the StrideOrder so we process larger strides first.
2527     std::stable_sort(IU->StrideOrder.begin(), IU->StrideOrder.end(),
2528                      StrideCompare(SE));
2529
2530     // Optimize induction variables.  Some indvar uses can be transformed to use
2531     // strides that will be needed for other purposes.  A common example of this
2532     // is the exit test for the loop, which can often be rewritten to use the
2533     // computation of some other indvar to decide when to terminate the loop.
2534     OptimizeIndvars(L);
2535
2536     // Change loop terminating condition to use the postinc iv when possible
2537     // and optimize loop terminating compare. FIXME: Move this after
2538     // StrengthReduceStridedIVUsers?
2539     OptimizeLoopTermCond(L);
2540
2541     // FIXME: We can shrink overlarge IV's here.  e.g. if the code has
2542     // computation in i64 values and the target doesn't support i64, demote
2543     // the computation to 32-bit if safe.
2544
2545     // FIXME: Attempt to reuse values across multiple IV's.  In particular, we
2546     // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2547     // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2548     // Need to be careful that IV's are all the same type.  Only works for
2549     // intptr_t indvars.
2550
2551     // IVsByStride keeps IVs for one particular loop.
2552     assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
2553
2554     // Note: this processes each stride/type pair individually.  All users
2555     // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2556     // Also, note that we iterate over IVUsesByStride indirectly by using
2557     // StrideOrder. This extra layer of indirection makes the ordering of
2558     // strides deterministic - not dependent on map order.
2559     for (unsigned Stride = 0, e = IU->StrideOrder.size();
2560          Stride != e; ++Stride) {
2561       std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2562         IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2563       assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2564       // FIXME: Generalize to non-affine IV's.
2565       if (!SI->first->isLoopInvariant(L))
2566         continue;
2567       StrengthReduceStridedIVUsers(SI->first, *SI->second, L);
2568     }
2569   }
2570
2571   // After all sharing is done, see if we can adjust the loop to test against
2572   // zero instead of counting up to a maximum.  This is usually faster.
2573   OptimizeLoopCountIV(L);
2574
2575   // We're done analyzing this loop; release all the state we built up for it.
2576   IVsByStride.clear();
2577   StrideNoReuse.clear();
2578
2579   // Clean up after ourselves
2580   if (!DeadInsts.empty())
2581     DeleteTriviallyDeadInstructions();
2582
2583   // At this point, it is worth checking to see if any recurrence PHIs are also
2584   // dead, so that we can remove them as well.
2585   DeleteDeadPHIs(L->getHeader());
2586
2587   return Changed;
2588 }