Teach SCEVExpander to avoid creating over-indexed GEP indices when
[oota-llvm.git] / lib / Analysis / ScalarEvolutionExpander.cpp
1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
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 file contains the implementation of the scalar evolution expander,
11 // which is used to generate the code corresponding to a given scalar evolution
12 // expression.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Analysis/ScalarEvolutionExpander.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Target/TargetData.h"
19 using namespace llvm;
20
21 /// InsertCastOfTo - Insert a cast of V to the specified type, doing what
22 /// we can to share the casts.
23 Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V, 
24                                     const Type *Ty) {
25   // Short-circuit unnecessary bitcasts.
26   if (opcode == Instruction::BitCast && V->getType() == Ty)
27     return V;
28
29   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
30   if ((opcode == Instruction::PtrToInt || opcode == Instruction::IntToPtr) &&
31       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
32     if (CastInst *CI = dyn_cast<CastInst>(V))
33       if ((CI->getOpcode() == Instruction::PtrToInt ||
34            CI->getOpcode() == Instruction::IntToPtr) &&
35           SE.getTypeSizeInBits(CI->getType()) ==
36           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
37         return CI->getOperand(0);
38     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
39       if ((CE->getOpcode() == Instruction::PtrToInt ||
40            CE->getOpcode() == Instruction::IntToPtr) &&
41           SE.getTypeSizeInBits(CE->getType()) ==
42           SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
43         return CE->getOperand(0);
44   }
45
46   // FIXME: keep track of the cast instruction.
47   if (Constant *C = dyn_cast<Constant>(V))
48     return ConstantExpr::getCast(opcode, C, Ty);
49   
50   if (Argument *A = dyn_cast<Argument>(V)) {
51     // Check to see if there is already a cast!
52     for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
53          UI != E; ++UI) {
54       if ((*UI)->getType() == Ty)
55         if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
56           if (CI->getOpcode() == opcode) {
57             // If the cast isn't the first instruction of the function, move it.
58             if (BasicBlock::iterator(CI) != 
59                 A->getParent()->getEntryBlock().begin()) {
60               // If the CastInst is the insert point, change the insert point.
61               if (CI == InsertPt) ++InsertPt;
62               // Splice the cast at the beginning of the entry block.
63               CI->moveBefore(A->getParent()->getEntryBlock().begin());
64             }
65             return CI;
66           }
67     }
68     Instruction *I = CastInst::Create(opcode, V, Ty, V->getName(),
69                                       A->getParent()->getEntryBlock().begin());
70     InsertedValues.insert(I);
71     return I;
72   }
73
74   Instruction *I = cast<Instruction>(V);
75
76   // Check to see if there is already a cast.  If there is, use it.
77   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
78        UI != E; ++UI) {
79     if ((*UI)->getType() == Ty)
80       if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
81         if (CI->getOpcode() == opcode) {
82           BasicBlock::iterator It = I; ++It;
83           if (isa<InvokeInst>(I))
84             It = cast<InvokeInst>(I)->getNormalDest()->begin();
85           while (isa<PHINode>(It)) ++It;
86           if (It != BasicBlock::iterator(CI)) {
87             // If the CastInst is the insert point, change the insert point.
88             if (CI == InsertPt) ++InsertPt;
89             // Splice the cast immediately after the operand in question.
90             CI->moveBefore(It);
91           }
92           return CI;
93         }
94   }
95   BasicBlock::iterator IP = I; ++IP;
96   if (InvokeInst *II = dyn_cast<InvokeInst>(I))
97     IP = II->getNormalDest()->begin();
98   while (isa<PHINode>(IP)) ++IP;
99   Instruction *CI = CastInst::Create(opcode, V, Ty, V->getName(), IP);
100   InsertedValues.insert(CI);
101   return CI;
102 }
103
104 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
105 /// which must be possible with a noop cast.
106 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
107   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
108   assert((Op == Instruction::BitCast ||
109           Op == Instruction::PtrToInt ||
110           Op == Instruction::IntToPtr) &&
111          "InsertNoopCastOfTo cannot perform non-noop casts!");
112   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
113          "InsertNoopCastOfTo cannot change sizes!");
114   return InsertCastOfTo(Op, V, Ty);
115 }
116
117 /// InsertBinop - Insert the specified binary operator, doing a small amount
118 /// of work to avoid inserting an obviously redundant operation.
119 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
120                                  Value *RHS, BasicBlock::iterator InsertPt) {
121   // Fold a binop with constant operands.
122   if (Constant *CLHS = dyn_cast<Constant>(LHS))
123     if (Constant *CRHS = dyn_cast<Constant>(RHS))
124       return ConstantExpr::get(Opcode, CLHS, CRHS);
125
126   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
127   unsigned ScanLimit = 6;
128   BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
129   if (InsertPt != BlockBegin) {
130     // Scanning starts from the last instruction before InsertPt.
131     BasicBlock::iterator IP = InsertPt;
132     --IP;
133     for (; ScanLimit; --IP, --ScanLimit) {
134       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
135           IP->getOperand(1) == RHS)
136         return IP;
137       if (IP == BlockBegin) break;
138     }
139   }
140   
141   // If we haven't found this binop, insert it.
142   Instruction *BO = BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
143   InsertedValues.insert(BO);
144   return BO;
145 }
146
147 /// FactorOutConstant - Test if S is divisible by Factor, using signed
148 /// division. If so, update S with Factor divided out and return true.
149 /// S need not be evenly divisble if a reasonable remainder can be
150 /// computed.
151 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
152 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
153 /// check to see if the divide was folded.
154 static bool FactorOutConstant(SCEVHandle &S,
155                               SCEVHandle &Remainder,
156                               const APInt &Factor,
157                               ScalarEvolution &SE) {
158   // Everything is divisible by one.
159   if (Factor == 1)
160     return true;
161
162   // For a Constant, check for a multiple of the given factor.
163   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
164     ConstantInt *CI =
165       ConstantInt::get(C->getValue()->getValue().sdiv(Factor));
166     // If the quotient is zero and the remainder is non-zero, reject
167     // the value at this scale. It will be considered for subsequent
168     // smaller scales.
169     if (C->isZero() || !CI->isZero()) {
170       SCEVHandle Div = SE.getConstant(CI);
171       S = Div;
172       Remainder =
173         SE.getAddExpr(Remainder,
174                       SE.getConstant(C->getValue()->getValue().srem(Factor)));
175       return true;
176     }
177   }
178
179   // In a Mul, check if there is a constant operand which is a multiple
180   // of the given factor.
181   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S))
182     if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
183       if (!C->getValue()->getValue().srem(Factor)) {
184         std::vector<SCEVHandle> NewMulOps(M->getOperands());
185         NewMulOps[0] =
186           SE.getConstant(C->getValue()->getValue().sdiv(Factor));
187         S = SE.getMulExpr(NewMulOps);
188         return true;
189       }
190
191   // In an AddRec, check if both start and step are divisible.
192   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
193     SCEVHandle Step = A->getStepRecurrence(SE);
194     SCEVHandle StepRem = SE.getIntegerSCEV(0, Step->getType());
195     if (!FactorOutConstant(Step, StepRem, Factor, SE))
196       return false;
197     if (!StepRem->isZero())
198       return false;
199     SCEVHandle Start = A->getStart();
200     if (!FactorOutConstant(Start, Remainder, Factor, SE))
201       return false;
202     S = SE.getAddRecExpr(Start, Step, A->getLoop());
203     return true;
204   }
205
206   return false;
207 }
208
209 /// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
210 /// instead of using ptrtoint+arithmetic+inttoptr. This helps
211 /// BasicAliasAnalysis analyze the result. However, it suffers from the
212 /// underlying bug described in PR2831. Addition in LLVM currently always
213 /// has two's complement wrapping guaranteed. However, the semantics for
214 /// getelementptr overflow are ambiguous. In the common case though, this
215 /// expansion gets used when a GEP in the original code has been converted
216 /// into integer arithmetic, in which case the resulting code will be no
217 /// more undefined than it was originally.
218 ///
219 /// Design note: It might seem desirable for this function to be more
220 /// loop-aware. If some of the indices are loop-invariant while others
221 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
222 /// loop-invariant portions of the overall computation outside the loop.
223 /// However, there are a few reasons this is not done here. Hoisting simple
224 /// arithmetic is a low-level optimization that often isn't very
225 /// important until late in the optimization process. In fact, passes
226 /// like InstructionCombining will combine GEPs, even if it means
227 /// pushing loop-invariant computation down into loops, so even if the
228 /// GEPs were split here, the work would quickly be undone. The
229 /// LoopStrengthReduction pass, which is usually run quite late (and
230 /// after the last InstructionCombining pass), takes care of hoisting
231 /// loop-invariant portions of expressions, after considering what
232 /// can be folded using target addressing modes.
233 ///
234 Value *SCEVExpander::expandAddToGEP(const SCEVHandle *op_begin,
235                                     const SCEVHandle *op_end,
236                                     const PointerType *PTy,
237                                     const Type *Ty,
238                                     Value *V) {
239   const Type *ElTy = PTy->getElementType();
240   SmallVector<Value *, 4> GepIndices;
241   std::vector<SCEVHandle> Ops(op_begin, op_end);
242   bool AnyNonZeroIndices = false;
243
244   // Decend down the pointer's type and attempt to convert the other
245   // operands into GEP indices, at each level. The first index in a GEP
246   // indexes into the array implied by the pointer operand; the rest of
247   // the indices index into the element or field type selected by the
248   // preceding index.
249   for (;;) {
250     APInt ElSize = APInt(SE.getTypeSizeInBits(Ty),
251                          ElTy->isSized() ?  SE.TD->getTypeAllocSize(ElTy) : 0);
252     std::vector<SCEVHandle> NewOps;
253     std::vector<SCEVHandle> ScaledOps;
254     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
255       // Split AddRecs up into parts as either of the parts may be usable
256       // without the other.
257       if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i]))
258         if (!A->getStart()->isZero()) {
259           SCEVHandle Start = A->getStart();
260           Ops.push_back(SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
261                                          A->getStepRecurrence(SE),
262                                          A->getLoop()));
263           Ops[i] = Start;
264           ++e;
265         }
266       // If the scale size is not 0, attempt to factor out a scale.
267       if (ElSize != 0) {
268         SCEVHandle Op = Ops[i];
269         SCEVHandle Remainder = SE.getIntegerSCEV(0, Op->getType());
270         if (FactorOutConstant(Op, Remainder, ElSize, SE)) {
271           ScaledOps.push_back(Op); // Op now has ElSize factored out.
272           NewOps.push_back(Remainder);
273           continue;
274         }
275       }
276       // If the operand was not divisible, add it to the list of operands
277       // we'll scan next iteration.
278       NewOps.push_back(Ops[i]);
279     }
280     Ops = NewOps;
281     AnyNonZeroIndices |= !ScaledOps.empty();
282     Value *Scaled = ScaledOps.empty() ?
283                     Constant::getNullValue(Ty) :
284                     expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
285     GepIndices.push_back(Scaled);
286
287     // Collect struct field index operands.
288     if (!Ops.empty())
289       while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
290         if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
291           if (SE.getTypeSizeInBits(C->getType()) <= 64) {
292             const StructLayout &SL = *SE.TD->getStructLayout(STy);
293             uint64_t FullOffset = C->getValue()->getZExtValue();
294             if (FullOffset < SL.getSizeInBytes()) {
295               unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
296               GepIndices.push_back(ConstantInt::get(Type::Int32Ty, ElIdx));
297               ElTy = STy->getTypeAtIndex(ElIdx);
298               Ops[0] =
299                 SE.getConstant(ConstantInt::get(Ty,
300                                                 FullOffset -
301                                                   SL.getElementOffset(ElIdx)));
302               AnyNonZeroIndices = true;
303               continue;
304             }
305           }
306         break;
307       }
308
309     if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
310       ElTy = ATy->getElementType();
311       continue;
312     }
313     break;
314   }
315
316   // If none of the operands were convertable to proper GEP indices, cast
317   // the base to i8* and do an ugly getelementptr with that. It's still
318   // better than ptrtoint+arithmetic+inttoptr at least.
319   if (!AnyNonZeroIndices) {
320     V = InsertNoopCastOfTo(V,
321                            Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
322     Value *Idx = expand(SE.getAddExpr(Ops));
323     Idx = InsertNoopCastOfTo(Idx, Ty);
324
325     // Fold a GEP with constant operands.
326     if (Constant *CLHS = dyn_cast<Constant>(V))
327       if (Constant *CRHS = dyn_cast<Constant>(Idx))
328         return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
329
330     // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
331     unsigned ScanLimit = 6;
332     BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
333     if (InsertPt != BlockBegin) {
334       // Scanning starts from the last instruction before InsertPt.
335       BasicBlock::iterator IP = InsertPt;
336       --IP;
337       for (; ScanLimit; --IP, --ScanLimit) {
338         if (IP->getOpcode() == Instruction::GetElementPtr &&
339             IP->getOperand(0) == V && IP->getOperand(1) == Idx)
340           return IP;
341         if (IP == BlockBegin) break;
342       }
343     }
344
345     Value *GEP = GetElementPtrInst::Create(V, Idx, "scevgep", InsertPt);
346     InsertedValues.insert(GEP);
347     return GEP;
348   }
349
350   // Insert a pretty getelementptr.
351   Value *GEP = GetElementPtrInst::Create(V,
352                                          GepIndices.begin(),
353                                          GepIndices.end(),
354                                          "scevgep", InsertPt);
355   Ops.push_back(SE.getUnknown(GEP));
356   InsertedValues.insert(GEP);
357   return expand(SE.getAddExpr(Ops));
358 }
359
360 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
361   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
362   Value *V = expand(S->getOperand(S->getNumOperands()-1));
363
364   // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
365   // comments on expandAddToGEP for details.
366   if (SE.TD)
367     if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
368       const std::vector<SCEVHandle> &Ops = S->getOperands();
369       return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1],
370                             PTy, Ty, V);
371     }
372
373   V = InsertNoopCastOfTo(V, Ty);
374
375   // Emit a bunch of add instructions
376   for (int i = S->getNumOperands()-2; i >= 0; --i) {
377     Value *W = expand(S->getOperand(i));
378     W = InsertNoopCastOfTo(W, Ty);
379     V = InsertBinop(Instruction::Add, V, W, InsertPt);
380   }
381   return V;
382 }
383
384 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
385   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
386   int FirstOp = 0;  // Set if we should emit a subtract.
387   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
388     if (SC->getValue()->isAllOnesValue())
389       FirstOp = 1;
390
391   int i = S->getNumOperands()-2;
392   Value *V = expand(S->getOperand(i+1));
393   V = InsertNoopCastOfTo(V, Ty);
394
395   // Emit a bunch of multiply instructions
396   for (; i >= FirstOp; --i) {
397     Value *W = expand(S->getOperand(i));
398     W = InsertNoopCastOfTo(W, Ty);
399     V = InsertBinop(Instruction::Mul, V, W, InsertPt);
400   }
401
402   // -1 * ...  --->  0 - ...
403   if (FirstOp == 1)
404     V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
405   return V;
406 }
407
408 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
409   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
410
411   Value *LHS = expand(S->getLHS());
412   LHS = InsertNoopCastOfTo(LHS, Ty);
413   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
414     const APInt &RHS = SC->getValue()->getValue();
415     if (RHS.isPowerOf2())
416       return InsertBinop(Instruction::LShr, LHS,
417                          ConstantInt::get(Ty, RHS.logBase2()),
418                          InsertPt);
419   }
420
421   Value *RHS = expand(S->getRHS());
422   RHS = InsertNoopCastOfTo(RHS, Ty);
423   return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
424 }
425
426 /// Move parts of Base into Rest to leave Base with the minimal
427 /// expression that provides a pointer operand suitable for a
428 /// GEP expansion.
429 static void ExposePointerBase(SCEVHandle &Base, SCEVHandle &Rest,
430                               ScalarEvolution &SE) {
431   while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
432     Base = A->getStart();
433     Rest = SE.getAddExpr(Rest,
434                          SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
435                                           A->getStepRecurrence(SE),
436                                           A->getLoop()));
437   }
438   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
439     Base = A->getOperand(A->getNumOperands()-1);
440     std::vector<SCEVHandle> NewAddOps(A->op_begin(), A->op_end());
441     NewAddOps.back() = Rest;
442     Rest = SE.getAddExpr(NewAddOps);
443     ExposePointerBase(Base, Rest, SE);
444   }
445 }
446
447 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
448   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
449   const Loop *L = S->getLoop();
450
451   // {X,+,F} --> X + {0,+,F}
452   if (!S->getStart()->isZero()) {
453     std::vector<SCEVHandle> NewOps(S->getOperands());
454     NewOps[0] = SE.getIntegerSCEV(0, Ty);
455     SCEVHandle Rest = SE.getAddRecExpr(NewOps, L);
456
457     // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
458     // comments on expandAddToGEP for details.
459     if (SE.TD) {
460       SCEVHandle Base = S->getStart();
461       SCEVHandle RestArray[1] = Rest;
462       // Dig into the expression to find the pointer base for a GEP.
463       ExposePointerBase(Base, RestArray[0], SE);
464       // If we found a pointer, expand the AddRec with a GEP.
465       if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
466         // Make sure the Base isn't something exotic, such as a multiplied
467         // or divided pointer value. In those cases, the result type isn't
468         // actually a pointer type.
469         if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
470           Value *StartV = expand(Base);
471           assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
472           return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
473         }
474       }
475     }
476
477     Value *RestV = expand(Rest);
478     return expand(SE.getAddExpr(S->getStart(), SE.getUnknown(RestV)));
479   }
480
481   // {0,+,1} --> Insert a canonical induction variable into the loop!
482   if (S->isAffine() &&
483       S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
484     // Create and insert the PHI node for the induction variable in the
485     // specified loop.
486     BasicBlock *Header = L->getHeader();
487     PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
488     InsertedValues.insert(PN);
489     PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
490
491     pred_iterator HPI = pred_begin(Header);
492     assert(HPI != pred_end(Header) && "Loop with zero preds???");
493     if (!L->contains(*HPI)) ++HPI;
494     assert(HPI != pred_end(Header) && L->contains(*HPI) &&
495            "No backedge in loop?");
496
497     // Insert a unit add instruction right before the terminator corresponding
498     // to the back-edge.
499     Constant *One = ConstantInt::get(Ty, 1);
500     Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
501                                                  (*HPI)->getTerminator());
502     InsertedValues.insert(Add);
503
504     pred_iterator PI = pred_begin(Header);
505     if (*PI == L->getLoopPreheader())
506       ++PI;
507     PN->addIncoming(Add, *PI);
508     return PN;
509   }
510
511   // Get the canonical induction variable I for this loop.
512   Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
513
514   // If this is a simple linear addrec, emit it now as a special case.
515   if (S->isAffine()) {   // {0,+,F} --> i*F
516     Value *F = expand(S->getOperand(1));
517     F = InsertNoopCastOfTo(F, Ty);
518     
519     // IF the step is by one, just return the inserted IV.
520     if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
521       if (CI->getValue() == 1)
522         return I;
523     
524     // If the insert point is directly inside of the loop, emit the multiply at
525     // the insert point.  Otherwise, L is a loop that is a parent of the insert
526     // point loop.  If we can, move the multiply to the outer most loop that it
527     // is safe to be in.
528     BasicBlock::iterator MulInsertPt = getInsertionPoint();
529     Loop *InsertPtLoop = SE.LI->getLoopFor(MulInsertPt->getParent());
530     if (InsertPtLoop != L && InsertPtLoop &&
531         L->contains(InsertPtLoop->getHeader())) {
532       do {
533         // If we cannot hoist the multiply out of this loop, don't.
534         if (!InsertPtLoop->isLoopInvariant(F)) break;
535
536         BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
537
538         // If this loop hasn't got a preheader, we aren't able to hoist the
539         // multiply.
540         if (!InsertPtLoopPH)
541           break;
542
543         // Otherwise, move the insert point to the preheader.
544         MulInsertPt = InsertPtLoopPH->getTerminator();
545         InsertPtLoop = InsertPtLoop->getParentLoop();
546       } while (InsertPtLoop != L);
547     }
548     
549     return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
550   }
551
552   // If this is a chain of recurrences, turn it into a closed form, using the
553   // folders, then expandCodeFor the closed form.  This allows the folders to
554   // simplify the expression without having to build a bunch of special code
555   // into this folder.
556   SCEVHandle IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
557
558   SCEVHandle V = S->evaluateAtIteration(IH, SE);
559   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
560
561   return expand(V);
562 }
563
564 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
565   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
566   Value *V = expand(S->getOperand());
567   V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
568   Instruction *I = new TruncInst(V, Ty, "tmp.", InsertPt);
569   InsertedValues.insert(I);
570   return I;
571 }
572
573 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
574   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
575   Value *V = expand(S->getOperand());
576   V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
577   Instruction *I = new ZExtInst(V, Ty, "tmp.", InsertPt);
578   InsertedValues.insert(I);
579   return I;
580 }
581
582 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
583   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
584   Value *V = expand(S->getOperand());
585   V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
586   Instruction *I = new SExtInst(V, Ty, "tmp.", InsertPt);
587   InsertedValues.insert(I);
588   return I;
589 }
590
591 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
592   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
593   Value *LHS = expand(S->getOperand(0));
594   LHS = InsertNoopCastOfTo(LHS, Ty);
595   for (unsigned i = 1; i < S->getNumOperands(); ++i) {
596     Value *RHS = expand(S->getOperand(i));
597     RHS = InsertNoopCastOfTo(RHS, Ty);
598     Instruction *ICmp =
599       new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
600     InsertedValues.insert(ICmp);
601     Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
602     InsertedValues.insert(Sel);
603     LHS = Sel;
604   }
605   return LHS;
606 }
607
608 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
609   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
610   Value *LHS = expand(S->getOperand(0));
611   LHS = InsertNoopCastOfTo(LHS, Ty);
612   for (unsigned i = 1; i < S->getNumOperands(); ++i) {
613     Value *RHS = expand(S->getOperand(i));
614     RHS = InsertNoopCastOfTo(RHS, Ty);
615     Instruction *ICmp =
616       new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
617     InsertedValues.insert(ICmp);
618     Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
619     InsertedValues.insert(Sel);
620     LHS = Sel;
621   }
622   return LHS;
623 }
624
625 Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty) {
626   // Expand the code for this SCEV.
627   Value *V = expand(SH);
628   if (Ty) {
629     assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
630            "non-trivial casts should be done with the SCEVs directly!");
631     V = InsertNoopCastOfTo(V, Ty);
632   }
633   return V;
634 }
635
636 Value *SCEVExpander::expand(const SCEV *S) {
637   // Check to see if we already expanded this.
638   std::map<SCEVHandle, AssertingVH<Value> >::iterator I =
639     InsertedExpressions.find(S);
640   if (I != InsertedExpressions.end())
641     return I->second;
642   
643   Value *V = visit(S);
644   InsertedExpressions[S] = V;
645   return V;
646 }