ScalarEvolutionExpander.cpp revision 92fcdcac543653a62949fe9e5a7bd008500c1380
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"
19using namespace llvm;
20
21/// InsertCastOfTo - Insert a cast of V to the specified type, doing what
22/// we can to share the casts.
23Value *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.
106Value *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.
119Value *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.
154static 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///
234Value *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 = expandCodeFor(SE.getAddExpr(Ops), Ty);
323
324    // Fold a GEP with constant operands.
325    if (Constant *CLHS = dyn_cast<Constant>(V))
326      if (Constant *CRHS = dyn_cast<Constant>(Idx))
327        return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
328
329    // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
330    unsigned ScanLimit = 6;
331    BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
332    if (InsertPt != BlockBegin) {
333      // Scanning starts from the last instruction before InsertPt.
334      BasicBlock::iterator IP = InsertPt;
335      --IP;
336      for (; ScanLimit; --IP, --ScanLimit) {
337        if (IP->getOpcode() == Instruction::GetElementPtr &&
338            IP->getOperand(0) == V && IP->getOperand(1) == Idx)
339          return IP;
340        if (IP == BlockBegin) break;
341      }
342    }
343
344    Value *GEP = GetElementPtrInst::Create(V, Idx, "scevgep", InsertPt);
345    InsertedValues.insert(GEP);
346    return GEP;
347  }
348
349  // Insert a pretty getelementptr.
350  Value *GEP = GetElementPtrInst::Create(V,
351                                         GepIndices.begin(),
352                                         GepIndices.end(),
353                                         "scevgep", InsertPt);
354  Ops.push_back(SE.getUnknown(GEP));
355  InsertedValues.insert(GEP);
356  return expand(SE.getAddExpr(Ops));
357}
358
359Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
360  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
361  Value *V = expand(S->getOperand(S->getNumOperands()-1));
362
363  // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
364  // comments on expandAddToGEP for details.
365  if (SE.TD)
366    if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
367      const std::vector<SCEVHandle> &Ops = S->getOperands();
368      return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1],
369                            PTy, Ty, V);
370    }
371
372  V = InsertNoopCastOfTo(V, Ty);
373
374  // Emit a bunch of add instructions
375  for (int i = S->getNumOperands()-2; i >= 0; --i) {
376    Value *W = expandCodeFor(S->getOperand(i), Ty);
377    V = InsertBinop(Instruction::Add, V, W, InsertPt);
378  }
379  return V;
380}
381
382Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
383  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
384  int FirstOp = 0;  // Set if we should emit a subtract.
385  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
386    if (SC->getValue()->isAllOnesValue())
387      FirstOp = 1;
388
389  int i = S->getNumOperands()-2;
390  Value *V = expandCodeFor(S->getOperand(i+1), Ty);
391
392  // Emit a bunch of multiply instructions
393  for (; i >= FirstOp; --i) {
394    Value *W = expandCodeFor(S->getOperand(i), Ty);
395    V = InsertBinop(Instruction::Mul, V, W, InsertPt);
396  }
397
398  // -1 * ...  --->  0 - ...
399  if (FirstOp == 1)
400    V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
401  return V;
402}
403
404Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
405  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
406
407  Value *LHS = expandCodeFor(S->getLHS(), Ty);
408  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
409    const APInt &RHS = SC->getValue()->getValue();
410    if (RHS.isPowerOf2())
411      return InsertBinop(Instruction::LShr, LHS,
412                         ConstantInt::get(Ty, RHS.logBase2()),
413                         InsertPt);
414  }
415
416  Value *RHS = expandCodeFor(S->getRHS(), Ty);
417  return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
418}
419
420/// Move parts of Base into Rest to leave Base with the minimal
421/// expression that provides a pointer operand suitable for a
422/// GEP expansion.
423static void ExposePointerBase(SCEVHandle &Base, SCEVHandle &Rest,
424                              ScalarEvolution &SE) {
425  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
426    Base = A->getStart();
427    Rest = SE.getAddExpr(Rest,
428                         SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
429                                          A->getStepRecurrence(SE),
430                                          A->getLoop()));
431  }
432  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
433    Base = A->getOperand(A->getNumOperands()-1);
434    std::vector<SCEVHandle> NewAddOps(A->op_begin(), A->op_end());
435    NewAddOps.back() = Rest;
436    Rest = SE.getAddExpr(NewAddOps);
437    ExposePointerBase(Base, Rest, SE);
438  }
439}
440
441Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
442  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
443  const Loop *L = S->getLoop();
444
445  // {X,+,F} --> X + {0,+,F}
446  if (!S->getStart()->isZero()) {
447    std::vector<SCEVHandle> NewOps(S->getOperands());
448    NewOps[0] = SE.getIntegerSCEV(0, Ty);
449    SCEVHandle Rest = SE.getAddRecExpr(NewOps, L);
450
451    // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
452    // comments on expandAddToGEP for details.
453    if (SE.TD) {
454      SCEVHandle Base = S->getStart();
455      SCEVHandle RestArray[1] = { Rest };
456      // Dig into the expression to find the pointer base for a GEP.
457      ExposePointerBase(Base, RestArray[0], SE);
458      // If we found a pointer, expand the AddRec with a GEP.
459      if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
460        // Make sure the Base isn't something exotic, such as a multiplied
461        // or divided pointer value. In those cases, the result type isn't
462        // actually a pointer type.
463        if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
464          Value *StartV = expand(Base);
465          assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
466          return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
467        }
468      }
469    }
470
471    Value *RestV = expand(Rest);
472    return expand(SE.getAddExpr(S->getStart(), SE.getUnknown(RestV)));
473  }
474
475  // {0,+,1} --> Insert a canonical induction variable into the loop!
476  if (S->isAffine() &&
477      S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
478    // Create and insert the PHI node for the induction variable in the
479    // specified loop.
480    BasicBlock *Header = L->getHeader();
481    PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
482    InsertedValues.insert(PN);
483    PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
484
485    pred_iterator HPI = pred_begin(Header);
486    assert(HPI != pred_end(Header) && "Loop with zero preds???");
487    if (!L->contains(*HPI)) ++HPI;
488    assert(HPI != pred_end(Header) && L->contains(*HPI) &&
489           "No backedge in loop?");
490
491    // Insert a unit add instruction right before the terminator corresponding
492    // to the back-edge.
493    Constant *One = ConstantInt::get(Ty, 1);
494    Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
495                                                 (*HPI)->getTerminator());
496    InsertedValues.insert(Add);
497
498    pred_iterator PI = pred_begin(Header);
499    if (*PI == L->getLoopPreheader())
500      ++PI;
501    PN->addIncoming(Add, *PI);
502    return PN;
503  }
504
505  // Get the canonical induction variable I for this loop.
506  Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
507
508  // If this is a simple linear addrec, emit it now as a special case.
509  if (S->isAffine()) {   // {0,+,F} --> i*F
510    Value *F = expandCodeFor(S->getOperand(1), Ty);
511
512    // If the step is by one, just return the inserted IV.
513    if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
514      if (CI->getValue() == 1)
515        return I;
516
517    // If the insert point is directly inside of the loop, emit the multiply at
518    // the insert point.  Otherwise, L is a loop that is a parent of the insert
519    // point loop.  If we can, move the multiply to the outer most loop that it
520    // is safe to be in.
521    BasicBlock::iterator MulInsertPt = getInsertionPoint();
522    Loop *InsertPtLoop = SE.LI->getLoopFor(MulInsertPt->getParent());
523    if (InsertPtLoop != L && InsertPtLoop &&
524        L->contains(InsertPtLoop->getHeader())) {
525      do {
526        // If we cannot hoist the multiply out of this loop, don't.
527        if (!InsertPtLoop->isLoopInvariant(F)) break;
528
529        BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
530
531        // If this loop hasn't got a preheader, we aren't able to hoist the
532        // multiply.
533        if (!InsertPtLoopPH)
534          break;
535
536        // Otherwise, move the insert point to the preheader.
537        MulInsertPt = InsertPtLoopPH->getTerminator();
538        InsertPtLoop = InsertPtLoop->getParentLoop();
539      } while (InsertPtLoop != L);
540    }
541
542    return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
543  }
544
545  // If this is a chain of recurrences, turn it into a closed form, using the
546  // folders, then expandCodeFor the closed form.  This allows the folders to
547  // simplify the expression without having to build a bunch of special code
548  // into this folder.
549  SCEVHandle IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
550
551  SCEVHandle V = S->evaluateAtIteration(IH, SE);
552  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
553
554  return expand(V);
555}
556
557Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
558  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
559  Value *V = expandCodeFor(S->getOperand(),
560                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
561  Instruction *I = new TruncInst(V, Ty, "tmp.", InsertPt);
562  InsertedValues.insert(I);
563  return I;
564}
565
566Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
567  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
568  Value *V = expandCodeFor(S->getOperand(),
569                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
570  Instruction *I = new ZExtInst(V, Ty, "tmp.", InsertPt);
571  InsertedValues.insert(I);
572  return I;
573}
574
575Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
576  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
577  Value *V = expandCodeFor(S->getOperand(),
578                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
579  Instruction *I = new SExtInst(V, Ty, "tmp.", InsertPt);
580  InsertedValues.insert(I);
581  return I;
582}
583
584Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
585  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
586  Value *LHS = expandCodeFor(S->getOperand(0), Ty);
587  for (unsigned i = 1; i < S->getNumOperands(); ++i) {
588    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
589    Instruction *ICmp =
590      new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
591    InsertedValues.insert(ICmp);
592    Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
593    InsertedValues.insert(Sel);
594    LHS = Sel;
595  }
596  return LHS;
597}
598
599Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
600  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
601  Value *LHS = expandCodeFor(S->getOperand(0), Ty);
602  for (unsigned i = 1; i < S->getNumOperands(); ++i) {
603    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
604    Instruction *ICmp =
605      new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
606    InsertedValues.insert(ICmp);
607    Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
608    InsertedValues.insert(Sel);
609    LHS = Sel;
610  }
611  return LHS;
612}
613
614Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty) {
615  // Expand the code for this SCEV.
616  Value *V = expand(SH);
617  if (Ty) {
618    assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
619           "non-trivial casts should be done with the SCEVs directly!");
620    V = InsertNoopCastOfTo(V, Ty);
621  }
622  return V;
623}
624
625Value *SCEVExpander::expand(const SCEV *S) {
626  // Check to see if we already expanded this.
627  std::map<SCEVHandle, AssertingVH<Value> >::iterator I =
628    InsertedExpressions.find(S);
629  if (I != InsertedExpressions.end())
630    return I->second;
631
632  Value *V = visit(S);
633  InsertedExpressions[S] = V;
634  return V;
635}
636
637/// getOrInsertCanonicalInductionVariable - This method returns the
638/// canonical induction variable of the specified type for the specified
639/// loop (inserting one if there is none).  A canonical induction variable
640/// starts at zero and steps by one on each iteration.
641Value *
642SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
643                                                    const Type *Ty) {
644  assert(Ty->isInteger() && "Can only insert integer induction variables!");
645  SCEVHandle H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
646                                  SE.getIntegerSCEV(1, Ty), L);
647  return expand(H);
648}
649