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