ScalarEvolutionExpander.cpp revision 53b73a283e0a0339f7a273775ee21ebcc220b089
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/IntrinsicInst.h"
19#include "llvm/LLVMContext.h"
20#include "llvm/Target/TargetData.h"
21#include "llvm/ADT/STLExtras.h"
22using namespace llvm;
23
24/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
25/// which must be possible with a noop cast, doing what we can to share
26/// the casts.
27Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
28  Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
29  assert((Op == Instruction::BitCast ||
30          Op == Instruction::PtrToInt ||
31          Op == Instruction::IntToPtr) &&
32         "InsertNoopCastOfTo cannot perform non-noop casts!");
33  assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
34         "InsertNoopCastOfTo cannot change sizes!");
35
36  // Short-circuit unnecessary bitcasts.
37  if (Op == Instruction::BitCast && V->getType() == Ty)
38    return V;
39
40  // Short-circuit unnecessary inttoptr<->ptrtoint casts.
41  if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
42      SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
43    if (CastInst *CI = dyn_cast<CastInst>(V))
44      if ((CI->getOpcode() == Instruction::PtrToInt ||
45           CI->getOpcode() == Instruction::IntToPtr) &&
46          SE.getTypeSizeInBits(CI->getType()) ==
47          SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
48        return CI->getOperand(0);
49    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
50      if ((CE->getOpcode() == Instruction::PtrToInt ||
51           CE->getOpcode() == Instruction::IntToPtr) &&
52          SE.getTypeSizeInBits(CE->getType()) ==
53          SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
54        return CE->getOperand(0);
55  }
56
57  if (Constant *C = dyn_cast<Constant>(V))
58    return ConstantExpr::getCast(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    rememberInstruction(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 after the user.
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            rememberInstruction(NewCI);
109            return NewCI;
110          }
111          rememberInstruction(CI);
112          return CI;
113        }
114  }
115  BasicBlock::iterator IP = I; ++IP;
116  if (InvokeInst *II = dyn_cast<InvokeInst>(I))
117    IP = II->getNormalDest()->begin();
118  while (isa<PHINode>(IP)) ++IP;
119  Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
120  rememberInstruction(CI);
121  return CI;
122}
123
124/// InsertBinop - Insert the specified binary operator, doing a small amount
125/// of work to avoid inserting an obviously redundant operation.
126Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
127                                 Value *LHS, Value *RHS) {
128  // Fold a binop with constant operands.
129  if (Constant *CLHS = dyn_cast<Constant>(LHS))
130    if (Constant *CRHS = dyn_cast<Constant>(RHS))
131      return ConstantExpr::get(Opcode, CLHS, CRHS);
132
133  // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
134  unsigned ScanLimit = 6;
135  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
136  // Scanning starts from the last instruction before the insertion point.
137  BasicBlock::iterator IP = Builder.GetInsertPoint();
138  if (IP != BlockBegin) {
139    --IP;
140    for (; ScanLimit; --IP, --ScanLimit) {
141      // Don't count dbg.value against the ScanLimit, to avoid perturbing the
142      // generated code.
143      if (isa<DbgInfoIntrinsic>(IP))
144        ScanLimit++;
145      if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
146          IP->getOperand(1) == RHS)
147        return IP;
148      if (IP == BlockBegin) break;
149    }
150  }
151
152  // Save the original insertion point so we can restore it when we're done.
153  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
154  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
155
156  // Move the insertion point out of as many loops as we can.
157  while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
158    if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
159    BasicBlock *Preheader = L->getLoopPreheader();
160    if (!Preheader) break;
161
162    // Ok, move up a level.
163    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
164  }
165
166  // If we haven't found this binop, insert it.
167  Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
168  rememberInstruction(BO);
169
170  // Restore the original insert point.
171  if (SaveInsertBB)
172    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
173
174  return BO;
175}
176
177/// FactorOutConstant - Test if S is divisible by Factor, using signed
178/// division. If so, update S with Factor divided out and return true.
179/// S need not be evenly divisible if a reasonable remainder can be
180/// computed.
181/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
182/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
183/// check to see if the divide was folded.
184static bool FactorOutConstant(const SCEV *&S,
185                              const SCEV *&Remainder,
186                              const SCEV *Factor,
187                              ScalarEvolution &SE,
188                              const TargetData *TD) {
189  // Everything is divisible by one.
190  if (Factor->isOne())
191    return true;
192
193  // x/x == 1.
194  if (S == Factor) {
195    S = SE.getIntegerSCEV(1, S->getType());
196    return true;
197  }
198
199  // For a Constant, check for a multiple of the given factor.
200  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
201    // 0/x == 0.
202    if (C->isZero())
203      return true;
204    // Check for divisibility.
205    if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
206      ConstantInt *CI =
207        ConstantInt::get(SE.getContext(),
208                         C->getValue()->getValue().sdiv(
209                                                   FC->getValue()->getValue()));
210      // If the quotient is zero and the remainder is non-zero, reject
211      // the value at this scale. It will be considered for subsequent
212      // smaller scales.
213      if (!CI->isZero()) {
214        const SCEV *Div = SE.getConstant(CI);
215        S = Div;
216        Remainder =
217          SE.getAddExpr(Remainder,
218                        SE.getConstant(C->getValue()->getValue().srem(
219                                                  FC->getValue()->getValue())));
220        return true;
221      }
222    }
223  }
224
225  // In a Mul, check if there is a constant operand which is a multiple
226  // of the given factor.
227  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
228    if (TD) {
229      // With TargetData, the size is known. Check if there is a constant
230      // operand which is a multiple of the given factor. If so, we can
231      // factor it.
232      const SCEVConstant *FC = cast<SCEVConstant>(Factor);
233      if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
234        if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
235          SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
236          NewMulOps[0] =
237            SE.getConstant(C->getValue()->getValue().sdiv(
238                                                   FC->getValue()->getValue()));
239          S = SE.getMulExpr(NewMulOps);
240          return true;
241        }
242    } else {
243      // Without TargetData, check if Factor can be factored out of any of the
244      // Mul's operands. If so, we can just remove it.
245      for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
246        const SCEV *SOp = M->getOperand(i);
247        const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType());
248        if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
249            Remainder->isZero()) {
250          SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
251          NewMulOps[i] = SOp;
252          S = SE.getMulExpr(NewMulOps);
253          return true;
254        }
255      }
256    }
257  }
258
259  // In an AddRec, check if both start and step are divisible.
260  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
261    const SCEV *Step = A->getStepRecurrence(SE);
262    const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType());
263    if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
264      return false;
265    if (!StepRem->isZero())
266      return false;
267    const SCEV *Start = A->getStart();
268    if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
269      return false;
270    S = SE.getAddRecExpr(Start, Step, A->getLoop());
271    return true;
272  }
273
274  return false;
275}
276
277/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
278/// is the number of SCEVAddRecExprs present, which are kept at the end of
279/// the list.
280///
281static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
282                                const Type *Ty,
283                                ScalarEvolution &SE) {
284  unsigned NumAddRecs = 0;
285  for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
286    ++NumAddRecs;
287  // Group Ops into non-addrecs and addrecs.
288  SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
289  SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
290  // Let ScalarEvolution sort and simplify the non-addrecs list.
291  const SCEV *Sum = NoAddRecs.empty() ?
292                    SE.getIntegerSCEV(0, Ty) :
293                    SE.getAddExpr(NoAddRecs);
294  // If it returned an add, use the operands. Otherwise it simplified
295  // the sum into a single value, so just use that.
296  Ops.clear();
297  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
298    Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
299  else if (!Sum->isZero())
300    Ops.push_back(Sum);
301  // Then append the addrecs.
302  Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
303}
304
305/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
306/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
307/// This helps expose more opportunities for folding parts of the expressions
308/// into GEP indices.
309///
310static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
311                         const Type *Ty,
312                         ScalarEvolution &SE) {
313  // Find the addrecs.
314  SmallVector<const SCEV *, 8> AddRecs;
315  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
316    while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
317      const SCEV *Start = A->getStart();
318      if (Start->isZero()) break;
319      const SCEV *Zero = SE.getIntegerSCEV(0, Ty);
320      AddRecs.push_back(SE.getAddRecExpr(Zero,
321                                         A->getStepRecurrence(SE),
322                                         A->getLoop()));
323      if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
324        Ops[i] = Zero;
325        Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
326        e += Add->getNumOperands();
327      } else {
328        Ops[i] = Start;
329      }
330    }
331  if (!AddRecs.empty()) {
332    // Add the addrecs onto the end of the list.
333    Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
334    // Resort the operand list, moving any constants to the front.
335    SimplifyAddOperands(Ops, Ty, SE);
336  }
337}
338
339/// expandAddToGEP - Expand an addition expression with a pointer type into
340/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
341/// BasicAliasAnalysis and other passes analyze the result. See the rules
342/// for getelementptr vs. inttoptr in
343/// http://llvm.org/docs/LangRef.html#pointeraliasing
344/// for details.
345///
346/// Design note: The correctness of using getelementptr here depends on
347/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
348/// they may introduce pointer arithmetic which may not be safely converted
349/// into getelementptr.
350///
351/// Design note: It might seem desirable for this function to be more
352/// loop-aware. If some of the indices are loop-invariant while others
353/// aren't, it might seem desirable to emit multiple GEPs, keeping the
354/// loop-invariant portions of the overall computation outside the loop.
355/// However, there are a few reasons this is not done here. Hoisting simple
356/// arithmetic is a low-level optimization that often isn't very
357/// important until late in the optimization process. In fact, passes
358/// like InstructionCombining will combine GEPs, even if it means
359/// pushing loop-invariant computation down into loops, so even if the
360/// GEPs were split here, the work would quickly be undone. The
361/// LoopStrengthReduction pass, which is usually run quite late (and
362/// after the last InstructionCombining pass), takes care of hoisting
363/// loop-invariant portions of expressions, after considering what
364/// can be folded using target addressing modes.
365///
366Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
367                                    const SCEV *const *op_end,
368                                    const PointerType *PTy,
369                                    const Type *Ty,
370                                    Value *V) {
371  const Type *ElTy = PTy->getElementType();
372  SmallVector<Value *, 4> GepIndices;
373  SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
374  bool AnyNonZeroIndices = false;
375
376  // Split AddRecs up into parts as either of the parts may be usable
377  // without the other.
378  SplitAddRecs(Ops, Ty, SE);
379
380  // Descend down the pointer's type and attempt to convert the other
381  // operands into GEP indices, at each level. The first index in a GEP
382  // indexes into the array implied by the pointer operand; the rest of
383  // the indices index into the element or field type selected by the
384  // preceding index.
385  for (;;) {
386    // If the scale size is not 0, attempt to factor out a scale for
387    // array indexing.
388    SmallVector<const SCEV *, 8> ScaledOps;
389    if (ElTy->isSized()) {
390      const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
391      if (!ElSize->isZero()) {
392        SmallVector<const SCEV *, 8> NewOps;
393        for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
394          const SCEV *Op = Ops[i];
395          const SCEV *Remainder = SE.getIntegerSCEV(0, Ty);
396          if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
397            // Op now has ElSize factored out.
398            ScaledOps.push_back(Op);
399            if (!Remainder->isZero())
400              NewOps.push_back(Remainder);
401            AnyNonZeroIndices = true;
402          } else {
403            // The operand was not divisible, so add it to the list of operands
404            // we'll scan next iteration.
405            NewOps.push_back(Ops[i]);
406          }
407        }
408        // If we made any changes, update Ops.
409        if (!ScaledOps.empty()) {
410          Ops = NewOps;
411          SimplifyAddOperands(Ops, Ty, SE);
412        }
413      }
414    }
415
416    // Record the scaled array index for this level of the type. If
417    // we didn't find any operands that could be factored, tentatively
418    // assume that element zero was selected (since the zero offset
419    // would obviously be folded away).
420    Value *Scaled = ScaledOps.empty() ?
421                    Constant::getNullValue(Ty) :
422                    expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
423    GepIndices.push_back(Scaled);
424
425    // Collect struct field index operands.
426    while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
427      bool FoundFieldNo = false;
428      // An empty struct has no fields.
429      if (STy->getNumElements() == 0) break;
430      if (SE.TD) {
431        // With TargetData, field offsets are known. See if a constant offset
432        // falls within any of the struct fields.
433        if (Ops.empty()) break;
434        if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
435          if (SE.getTypeSizeInBits(C->getType()) <= 64) {
436            const StructLayout &SL = *SE.TD->getStructLayout(STy);
437            uint64_t FullOffset = C->getValue()->getZExtValue();
438            if (FullOffset < SL.getSizeInBytes()) {
439              unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
440              GepIndices.push_back(
441                  ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
442              ElTy = STy->getTypeAtIndex(ElIdx);
443              Ops[0] =
444                SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
445              AnyNonZeroIndices = true;
446              FoundFieldNo = true;
447            }
448          }
449      } else {
450        // Without TargetData, just check for an offsetof expression of the
451        // appropriate struct type.
452        for (unsigned i = 0, e = Ops.size(); i != e; ++i)
453          if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
454            const Type *CTy;
455            Constant *FieldNo;
456            if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
457              GepIndices.push_back(FieldNo);
458              ElTy =
459                STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
460              Ops[i] = SE.getConstant(Ty, 0);
461              AnyNonZeroIndices = true;
462              FoundFieldNo = true;
463              break;
464            }
465          }
466      }
467      // If no struct field offsets were found, tentatively assume that
468      // field zero was selected (since the zero offset would obviously
469      // be folded away).
470      if (!FoundFieldNo) {
471        ElTy = STy->getTypeAtIndex(0u);
472        GepIndices.push_back(
473          Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
474      }
475    }
476
477    if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
478      ElTy = ATy->getElementType();
479    else
480      break;
481  }
482
483  // If none of the operands were convertible to proper GEP indices, cast
484  // the base to i8* and do an ugly getelementptr with that. It's still
485  // better than ptrtoint+arithmetic+inttoptr at least.
486  if (!AnyNonZeroIndices) {
487    // Cast the base to i8*.
488    V = InsertNoopCastOfTo(V,
489       Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
490
491    // Expand the operands for a plain byte offset.
492    Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
493
494    // Fold a GEP with constant operands.
495    if (Constant *CLHS = dyn_cast<Constant>(V))
496      if (Constant *CRHS = dyn_cast<Constant>(Idx))
497        return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
498
499    // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
500    unsigned ScanLimit = 6;
501    BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
502    // Scanning starts from the last instruction before the insertion point.
503    BasicBlock::iterator IP = Builder.GetInsertPoint();
504    if (IP != BlockBegin) {
505      --IP;
506      for (; ScanLimit; --IP, --ScanLimit) {
507        // Don't count dbg.value against the ScanLimit, to avoid perturbing the
508        // generated code.
509        if (isa<DbgInfoIntrinsic>(IP))
510          ScanLimit++;
511        if (IP->getOpcode() == Instruction::GetElementPtr &&
512            IP->getOperand(0) == V && IP->getOperand(1) == Idx)
513          return IP;
514        if (IP == BlockBegin) break;
515      }
516    }
517
518    // Save the original insertion point so we can restore it when we're done.
519    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
520    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
521
522    // Move the insertion point out of as many loops as we can.
523    while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
524      if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
525      BasicBlock *Preheader = L->getLoopPreheader();
526      if (!Preheader) break;
527
528      // Ok, move up a level.
529      Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
530    }
531
532    // Emit a GEP.
533    Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
534    rememberInstruction(GEP);
535
536    // Restore the original insert point.
537    if (SaveInsertBB)
538      restoreInsertPoint(SaveInsertBB, SaveInsertPt);
539
540    return GEP;
541  }
542
543  // Save the original insertion point so we can restore it when we're done.
544  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
545  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
546
547  // Move the insertion point out of as many loops as we can.
548  while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
549    if (!L->isLoopInvariant(V)) break;
550
551    bool AnyIndexNotLoopInvariant = false;
552    for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
553         E = GepIndices.end(); I != E; ++I)
554      if (!L->isLoopInvariant(*I)) {
555        AnyIndexNotLoopInvariant = true;
556        break;
557      }
558    if (AnyIndexNotLoopInvariant)
559      break;
560
561    BasicBlock *Preheader = L->getLoopPreheader();
562    if (!Preheader) break;
563
564    // Ok, move up a level.
565    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
566  }
567
568  // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
569  // because ScalarEvolution may have changed the address arithmetic to
570  // compute a value which is beyond the end of the allocated object.
571  Value *Casted = V;
572  if (V->getType() != PTy)
573    Casted = InsertNoopCastOfTo(Casted, PTy);
574  Value *GEP = Builder.CreateGEP(Casted,
575                                 GepIndices.begin(),
576                                 GepIndices.end(),
577                                 "scevgep");
578  Ops.push_back(SE.getUnknown(GEP));
579  rememberInstruction(GEP);
580
581  // Restore the original insert point.
582  if (SaveInsertBB)
583    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
584
585  return expand(SE.getAddExpr(Ops));
586}
587
588/// isNonConstantNegative - Return true if the specified scev is negated, but
589/// not a constant.
590static bool isNonConstantNegative(const SCEV *F) {
591  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
592  if (!Mul) return false;
593
594  // If there is a constant factor, it will be first.
595  const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
596  if (!SC) return false;
597
598  // Return true if the value is negative, this matches things like (-42 * V).
599  return SC->getValue()->getValue().isNegative();
600}
601
602/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
603/// SCEV expansion. If they are nested, this is the most nested. If they are
604/// neighboring, pick the later.
605static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
606                                        DominatorTree &DT) {
607  if (!A) return B;
608  if (!B) return A;
609  if (A->contains(B)) return B;
610  if (B->contains(A)) return A;
611  if (DT.dominates(A->getHeader(), B->getHeader())) return B;
612  if (DT.dominates(B->getHeader(), A->getHeader())) return A;
613  return A; // Arbitrarily break the tie.
614}
615
616/// GetRelevantLoop - Get the most relevant loop associated with the given
617/// expression, according to PickMostRelevantLoop.
618static const Loop *GetRelevantLoop(const SCEV *S, LoopInfo &LI,
619                                   DominatorTree &DT) {
620  if (isa<SCEVConstant>(S))
621    return 0;
622  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
623    if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
624      return LI.getLoopFor(I->getParent());
625    return 0;
626  }
627  if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
628    const Loop *L = 0;
629    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
630      L = AR->getLoop();
631    for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
632         I != E; ++I)
633      L = PickMostRelevantLoop(L, GetRelevantLoop(*I, LI, DT), DT);
634    return L;
635  }
636  if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
637    return GetRelevantLoop(C->getOperand(), LI, DT);
638  if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S))
639    return PickMostRelevantLoop(GetRelevantLoop(D->getLHS(), LI, DT),
640                                GetRelevantLoop(D->getRHS(), LI, DT),
641                                DT);
642  llvm_unreachable("Unexpected SCEV type!");
643}
644
645/// LoopCompare - Compare loops by PickMostRelevantLoop.
646class LoopCompare {
647  DominatorTree &DT;
648public:
649  explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
650
651  bool operator()(std::pair<const Loop *, const SCEV *> LHS,
652                  std::pair<const Loop *, const SCEV *> RHS) const {
653    // Compare loops with PickMostRelevantLoop.
654    if (LHS.first != RHS.first)
655      return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
656
657    // If one operand is a non-constant negative and the other is not,
658    // put the non-constant negative on the right so that a sub can
659    // be used instead of a negate and add.
660    if (isNonConstantNegative(LHS.second)) {
661      if (!isNonConstantNegative(RHS.second))
662        return false;
663    } else if (isNonConstantNegative(RHS.second))
664      return true;
665
666    // Otherwise they are equivalent according to this comparison.
667    return false;
668  }
669};
670
671Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
672  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
673
674  // Collect all the add operands in a loop, along with their associated loops.
675  // Iterate in reverse so that constants are emitted last, all else equal, and
676  // so that pointer operands are inserted first, which the code below relies on
677  // to form more involved GEPs.
678  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
679  for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
680       E(S->op_begin()); I != E; ++I)
681    OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
682                                         *I));
683
684  // Sort by loop. Use a stable sort so that constants follow non-constants and
685  // pointer operands precede non-pointer operands.
686  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
687
688  // Emit instructions to add all the operands. Hoist as much as possible
689  // out of loops, and form meaningful getelementptrs where possible.
690  Value *Sum = 0;
691  for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
692       I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
693    const Loop *CurLoop = I->first;
694    const SCEV *Op = I->second;
695    if (!Sum) {
696      // This is the first operand. Just expand it.
697      Sum = expand(Op);
698      ++I;
699    } else if (const PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
700      // The running sum expression is a pointer. Try to form a getelementptr
701      // at this level with that as the base.
702      SmallVector<const SCEV *, 4> NewOps;
703      for (; I != E && I->first == CurLoop; ++I)
704        NewOps.push_back(I->second);
705      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
706    } else if (const PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
707      // The running sum is an integer, and there's a pointer at this level.
708      // Try to form a getelementptr. Use a SCEVUnknown so that we don't
709      // re-analyze the instructions that we just emitted.
710      SmallVector<const SCEV *, 4> NewOps;
711      NewOps.push_back(SE.getUnknown(Sum));
712      for (++I; I != E && I->first == CurLoop; ++I)
713        NewOps.push_back(I->second);
714      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
715    } else if (isNonConstantNegative(Op)) {
716      // Instead of doing a negate and add, just do a subtract.
717      Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
718      Sum = InsertNoopCastOfTo(Sum, Ty);
719      Sum = InsertBinop(Instruction::Sub, Sum, W);
720      ++I;
721    } else {
722      // A simple add.
723      Value *W = expandCodeFor(Op, Ty);
724      Sum = InsertNoopCastOfTo(Sum, Ty);
725      // Canonicalize a constant to the RHS.
726      if (isa<Constant>(Sum)) std::swap(Sum, W);
727      Sum = InsertBinop(Instruction::Add, Sum, W);
728      ++I;
729    }
730  }
731
732  return Sum;
733}
734
735Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
736  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
737
738  // Collect all the mul operands in a loop, along with their associated loops.
739  // Iterate in reverse so that constants are emitted last, all else equal.
740  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
741  for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
742       E(S->op_begin()); I != E; ++I)
743    OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
744                                         *I));
745
746  // Sort by loop. Use a stable sort so that constants follow non-constants.
747  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
748
749  // Emit instructions to mul all the operands. Hoist as much as possible
750  // out of loops.
751  Value *Prod = 0;
752  for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
753       I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
754    const SCEV *Op = I->second;
755    if (!Prod) {
756      // This is the first operand. Just expand it.
757      Prod = expand(Op);
758      ++I;
759    } else if (Op->isAllOnesValue()) {
760      // Instead of doing a multiply by negative one, just do a negate.
761      Prod = InsertNoopCastOfTo(Prod, Ty);
762      Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
763      ++I;
764    } else {
765      // A simple mul.
766      Value *W = expandCodeFor(Op, Ty);
767      Prod = InsertNoopCastOfTo(Prod, Ty);
768      // Canonicalize a constant to the RHS.
769      if (isa<Constant>(Prod)) std::swap(Prod, W);
770      Prod = InsertBinop(Instruction::Mul, Prod, W);
771      ++I;
772    }
773  }
774
775  return Prod;
776}
777
778Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
779  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
780
781  Value *LHS = expandCodeFor(S->getLHS(), Ty);
782  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
783    const APInt &RHS = SC->getValue()->getValue();
784    if (RHS.isPowerOf2())
785      return InsertBinop(Instruction::LShr, LHS,
786                         ConstantInt::get(Ty, RHS.logBase2()));
787  }
788
789  Value *RHS = expandCodeFor(S->getRHS(), Ty);
790  return InsertBinop(Instruction::UDiv, LHS, RHS);
791}
792
793/// Move parts of Base into Rest to leave Base with the minimal
794/// expression that provides a pointer operand suitable for a
795/// GEP expansion.
796static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
797                              ScalarEvolution &SE) {
798  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
799    Base = A->getStart();
800    Rest = SE.getAddExpr(Rest,
801                         SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
802                                          A->getStepRecurrence(SE),
803                                          A->getLoop()));
804  }
805  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
806    Base = A->getOperand(A->getNumOperands()-1);
807    SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
808    NewAddOps.back() = Rest;
809    Rest = SE.getAddExpr(NewAddOps);
810    ExposePointerBase(Base, Rest, SE);
811  }
812}
813
814/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
815/// the base addrec, which is the addrec without any non-loop-dominating
816/// values, and return the PHI.
817PHINode *
818SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
819                                        const Loop *L,
820                                        const Type *ExpandTy,
821                                        const Type *IntTy) {
822  // Reuse a previously-inserted PHI, if present.
823  for (BasicBlock::iterator I = L->getHeader()->begin();
824       PHINode *PN = dyn_cast<PHINode>(I); ++I)
825    if (SE.isSCEVable(PN->getType()) &&
826        (SE.getEffectiveSCEVType(PN->getType()) ==
827         SE.getEffectiveSCEVType(Normalized->getType())) &&
828        SE.getSCEV(PN) == Normalized)
829      if (BasicBlock *LatchBlock = L->getLoopLatch()) {
830        Instruction *IncV =
831          cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
832
833        // Determine if this is a well-behaved chain of instructions leading
834        // back to the PHI. It probably will be, if we're scanning an inner
835        // loop already visited by LSR for example, but it wouldn't have
836        // to be.
837        do {
838          if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV)) {
839            IncV = 0;
840            break;
841          }
842          // If any of the operands don't dominate the insert position, bail.
843          // Addrec operands are always loop-invariant, so this can only happen
844          // if there are instructions which haven't been hoisted.
845          for (User::op_iterator OI = IncV->op_begin()+1,
846               OE = IncV->op_end(); OI != OE; ++OI)
847            if (Instruction *OInst = dyn_cast<Instruction>(OI))
848              if (!SE.DT->dominates(OInst, IVIncInsertPos)) {
849                IncV = 0;
850                break;
851              }
852          if (!IncV)
853            break;
854          // Advance to the next instruction.
855          IncV = dyn_cast<Instruction>(IncV->getOperand(0));
856          if (!IncV)
857            break;
858          if (IncV->mayHaveSideEffects()) {
859            IncV = 0;
860            break;
861          }
862        } while (IncV != PN);
863
864        if (IncV) {
865          // Ok, the add recurrence looks usable.
866          // Remember this PHI, even in post-inc mode.
867          InsertedValues.insert(PN);
868          // Remember the increment.
869          IncV = cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
870          rememberInstruction(IncV);
871          if (L == IVIncInsertLoop)
872            do {
873              if (SE.DT->dominates(IncV, IVIncInsertPos))
874                break;
875              // Make sure the increment is where we want it. But don't move it
876              // down past a potential existing post-inc user.
877              IncV->moveBefore(IVIncInsertPos);
878              IVIncInsertPos = IncV;
879              IncV = cast<Instruction>(IncV->getOperand(0));
880            } while (IncV != PN);
881          return PN;
882        }
883      }
884
885  // Save the original insertion point so we can restore it when we're done.
886  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
887  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
888
889  // Expand code for the start value.
890  Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
891                                L->getHeader()->begin());
892
893  // Expand code for the step value. Insert instructions right before the
894  // terminator corresponding to the back-edge. Do this before creating the PHI
895  // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
896  // negative, insert a sub instead of an add for the increment (unless it's a
897  // constant, because subtracts of constants are canonicalized to adds).
898  const SCEV *Step = Normalized->getStepRecurrence(SE);
899  bool isPointer = ExpandTy->isPointerTy();
900  bool isNegative = !isPointer && isNonConstantNegative(Step);
901  if (isNegative)
902    Step = SE.getNegativeSCEV(Step);
903  Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
904
905  // Create the PHI.
906  Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin());
907  PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv");
908  rememberInstruction(PN);
909
910  // Create the step instructions and populate the PHI.
911  BasicBlock *Header = L->getHeader();
912  for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
913       HPI != HPE; ++HPI) {
914    BasicBlock *Pred = *HPI;
915
916    // Add a start value.
917    if (!L->contains(Pred)) {
918      PN->addIncoming(StartV, Pred);
919      continue;
920    }
921
922    // Create a step value and add it to the PHI. If IVIncInsertLoop is
923    // non-null and equal to the addrec's loop, insert the instructions
924    // at IVIncInsertPos.
925    Instruction *InsertPos = L == IVIncInsertLoop ?
926      IVIncInsertPos : Pred->getTerminator();
927    Builder.SetInsertPoint(InsertPos->getParent(), InsertPos);
928    Value *IncV;
929    // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
930    if (isPointer) {
931      const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
932      // If the step isn't constant, don't use an implicitly scaled GEP, because
933      // that would require a multiply inside the loop.
934      if (!isa<ConstantInt>(StepV))
935        GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
936                                    GEPPtrTy->getAddressSpace());
937      const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
938      IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
939      if (IncV->getType() != PN->getType()) {
940        IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
941        rememberInstruction(IncV);
942      }
943    } else {
944      IncV = isNegative ?
945        Builder.CreateSub(PN, StepV, "lsr.iv.next") :
946        Builder.CreateAdd(PN, StepV, "lsr.iv.next");
947      rememberInstruction(IncV);
948    }
949    PN->addIncoming(IncV, Pred);
950  }
951
952  // Restore the original insert point.
953  if (SaveInsertBB)
954    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
955
956  // Remember this PHI, even in post-inc mode.
957  InsertedValues.insert(PN);
958
959  return PN;
960}
961
962Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
963  const Type *STy = S->getType();
964  const Type *IntTy = SE.getEffectiveSCEVType(STy);
965  const Loop *L = S->getLoop();
966
967  // Determine a normalized form of this expression, which is the expression
968  // before any post-inc adjustment is made.
969  const SCEVAddRecExpr *Normalized = S;
970  if (PostIncLoops.count(L)) {
971    PostIncLoopSet Loops;
972    Loops.insert(L);
973    Normalized =
974      cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
975                                                  Loops, SE, *SE.DT));
976  }
977
978  // Strip off any non-loop-dominating component from the addrec start.
979  const SCEV *Start = Normalized->getStart();
980  const SCEV *PostLoopOffset = 0;
981  if (!Start->properlyDominates(L->getHeader(), SE.DT)) {
982    PostLoopOffset = Start;
983    Start = SE.getIntegerSCEV(0, Normalized->getType());
984    Normalized =
985      cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start,
986                                            Normalized->getStepRecurrence(SE),
987                                            Normalized->getLoop()));
988  }
989
990  // Strip off any non-loop-dominating component from the addrec step.
991  const SCEV *Step = Normalized->getStepRecurrence(SE);
992  const SCEV *PostLoopScale = 0;
993  if (!Step->hasComputableLoopEvolution(L) &&
994      !Step->dominates(L->getHeader(), SE.DT)) {
995    PostLoopScale = Step;
996    Step = SE.getIntegerSCEV(1, Normalized->getType());
997    Normalized =
998      cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
999                                            Normalized->getLoop()));
1000  }
1001
1002  // Expand the core addrec. If we need post-loop scaling, force it to
1003  // expand to an integer type to avoid the need for additional casting.
1004  const Type *ExpandTy = PostLoopScale ? IntTy : STy;
1005  PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1006
1007  // Accommodate post-inc mode, if necessary.
1008  Value *Result;
1009  if (!PostIncLoops.count(L))
1010    Result = PN;
1011  else {
1012    // In PostInc mode, use the post-incremented value.
1013    BasicBlock *LatchBlock = L->getLoopLatch();
1014    assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1015    Result = PN->getIncomingValueForBlock(LatchBlock);
1016  }
1017
1018  // Re-apply any non-loop-dominating scale.
1019  if (PostLoopScale) {
1020    Result = InsertNoopCastOfTo(Result, IntTy);
1021    Result = Builder.CreateMul(Result,
1022                               expandCodeFor(PostLoopScale, IntTy));
1023    rememberInstruction(Result);
1024  }
1025
1026  // Re-apply any non-loop-dominating offset.
1027  if (PostLoopOffset) {
1028    if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1029      const SCEV *const OffsetArray[1] = { PostLoopOffset };
1030      Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1031    } else {
1032      Result = InsertNoopCastOfTo(Result, IntTy);
1033      Result = Builder.CreateAdd(Result,
1034                                 expandCodeFor(PostLoopOffset, IntTy));
1035      rememberInstruction(Result);
1036    }
1037  }
1038
1039  return Result;
1040}
1041
1042Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1043  if (!CanonicalMode) return expandAddRecExprLiterally(S);
1044
1045  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1046  const Loop *L = S->getLoop();
1047
1048  // First check for an existing canonical IV in a suitable type.
1049  PHINode *CanonicalIV = 0;
1050  if (PHINode *PN = L->getCanonicalInductionVariable())
1051    if (SE.isSCEVable(PN->getType()) &&
1052        SE.getEffectiveSCEVType(PN->getType())->isIntegerTy() &&
1053        SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1054      CanonicalIV = PN;
1055
1056  // Rewrite an AddRec in terms of the canonical induction variable, if
1057  // its type is more narrow.
1058  if (CanonicalIV &&
1059      SE.getTypeSizeInBits(CanonicalIV->getType()) >
1060      SE.getTypeSizeInBits(Ty)) {
1061    SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1062    for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1063      NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1064    Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop()));
1065    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1066    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1067    BasicBlock::iterator NewInsertPt =
1068      llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
1069    while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
1070    V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1071                      NewInsertPt);
1072    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1073    return V;
1074  }
1075
1076  // {X,+,F} --> X + {0,+,F}
1077  if (!S->getStart()->isZero()) {
1078    SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1079    NewOps[0] = SE.getIntegerSCEV(0, Ty);
1080    const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
1081
1082    // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1083    // comments on expandAddToGEP for details.
1084    const SCEV *Base = S->getStart();
1085    const SCEV *RestArray[1] = { Rest };
1086    // Dig into the expression to find the pointer base for a GEP.
1087    ExposePointerBase(Base, RestArray[0], SE);
1088    // If we found a pointer, expand the AddRec with a GEP.
1089    if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1090      // Make sure the Base isn't something exotic, such as a multiplied
1091      // or divided pointer value. In those cases, the result type isn't
1092      // actually a pointer type.
1093      if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1094        Value *StartV = expand(Base);
1095        assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1096        return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1097      }
1098    }
1099
1100    // Just do a normal add. Pre-expand the operands to suppress folding.
1101    return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1102                                SE.getUnknown(expand(Rest))));
1103  }
1104
1105  // {0,+,1} --> Insert a canonical induction variable into the loop!
1106  if (S->isAffine() &&
1107      S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
1108    // If there's a canonical IV, just use it.
1109    if (CanonicalIV) {
1110      assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1111             "IVs with types different from the canonical IV should "
1112             "already have been handled!");
1113      return CanonicalIV;
1114    }
1115
1116    // Create and insert the PHI node for the induction variable in the
1117    // specified loop.
1118    BasicBlock *Header = L->getHeader();
1119    PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
1120    rememberInstruction(PN);
1121
1122    Constant *One = ConstantInt::get(Ty, 1);
1123    for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
1124         HPI != HPE; ++HPI)
1125      if (L->contains(*HPI)) {
1126        // Insert a unit add instruction right before the terminator
1127        // corresponding to the back-edge.
1128        Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
1129                                                     (*HPI)->getTerminator());
1130        rememberInstruction(Add);
1131        PN->addIncoming(Add, *HPI);
1132      } else {
1133        PN->addIncoming(Constant::getNullValue(Ty), *HPI);
1134      }
1135  }
1136
1137  // {0,+,F} --> {0,+,1} * F
1138  // Get the canonical induction variable I for this loop.
1139  Value *I = CanonicalIV ?
1140             CanonicalIV :
1141             getOrInsertCanonicalInductionVariable(L, Ty);
1142
1143  // If this is a simple linear addrec, emit it now as a special case.
1144  if (S->isAffine())    // {0,+,F} --> i*F
1145    return
1146      expand(SE.getTruncateOrNoop(
1147        SE.getMulExpr(SE.getUnknown(I),
1148                      SE.getNoopOrAnyExtend(S->getOperand(1),
1149                                            I->getType())),
1150        Ty));
1151
1152  // If this is a chain of recurrences, turn it into a closed form, using the
1153  // folders, then expandCodeFor the closed form.  This allows the folders to
1154  // simplify the expression without having to build a bunch of special code
1155  // into this folder.
1156  const SCEV *IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
1157
1158  // Promote S up to the canonical IV type, if the cast is foldable.
1159  const SCEV *NewS = S;
1160  const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
1161  if (isa<SCEVAddRecExpr>(Ext))
1162    NewS = Ext;
1163
1164  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1165  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
1166
1167  // Truncate the result down to the original type, if needed.
1168  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1169  return expand(T);
1170}
1171
1172Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1173  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1174  Value *V = expandCodeFor(S->getOperand(),
1175                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1176  Value *I = Builder.CreateTrunc(V, Ty, "tmp");
1177  rememberInstruction(I);
1178  return I;
1179}
1180
1181Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1182  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1183  Value *V = expandCodeFor(S->getOperand(),
1184                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1185  Value *I = Builder.CreateZExt(V, Ty, "tmp");
1186  rememberInstruction(I);
1187  return I;
1188}
1189
1190Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1191  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1192  Value *V = expandCodeFor(S->getOperand(),
1193                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1194  Value *I = Builder.CreateSExt(V, Ty, "tmp");
1195  rememberInstruction(I);
1196  return I;
1197}
1198
1199Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1200  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1201  const Type *Ty = LHS->getType();
1202  for (int i = S->getNumOperands()-2; i >= 0; --i) {
1203    // In the case of mixed integer and pointer types, do the
1204    // rest of the comparisons as integer.
1205    if (S->getOperand(i)->getType() != Ty) {
1206      Ty = SE.getEffectiveSCEVType(Ty);
1207      LHS = InsertNoopCastOfTo(LHS, Ty);
1208    }
1209    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1210    Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
1211    rememberInstruction(ICmp);
1212    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1213    rememberInstruction(Sel);
1214    LHS = Sel;
1215  }
1216  // In the case of mixed integer and pointer types, cast the
1217  // final result back to the pointer type.
1218  if (LHS->getType() != S->getType())
1219    LHS = InsertNoopCastOfTo(LHS, S->getType());
1220  return LHS;
1221}
1222
1223Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1224  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1225  const Type *Ty = LHS->getType();
1226  for (int i = S->getNumOperands()-2; i >= 0; --i) {
1227    // In the case of mixed integer and pointer types, do the
1228    // rest of the comparisons as integer.
1229    if (S->getOperand(i)->getType() != Ty) {
1230      Ty = SE.getEffectiveSCEVType(Ty);
1231      LHS = InsertNoopCastOfTo(LHS, Ty);
1232    }
1233    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1234    Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
1235    rememberInstruction(ICmp);
1236    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1237    rememberInstruction(Sel);
1238    LHS = Sel;
1239  }
1240  // In the case of mixed integer and pointer types, cast the
1241  // final result back to the pointer type.
1242  if (LHS->getType() != S->getType())
1243    LHS = InsertNoopCastOfTo(LHS, S->getType());
1244  return LHS;
1245}
1246
1247Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty,
1248                                   Instruction *I) {
1249  BasicBlock::iterator IP = I;
1250  while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
1251    ++IP;
1252  Builder.SetInsertPoint(IP->getParent(), IP);
1253  return expandCodeFor(SH, Ty);
1254}
1255
1256Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
1257  // Expand the code for this SCEV.
1258  Value *V = expand(SH);
1259  if (Ty) {
1260    assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1261           "non-trivial casts should be done with the SCEVs directly!");
1262    V = InsertNoopCastOfTo(V, Ty);
1263  }
1264  return V;
1265}
1266
1267Value *SCEVExpander::expand(const SCEV *S) {
1268  // Compute an insertion point for this SCEV object. Hoist the instructions
1269  // as far out in the loop nest as possible.
1270  Instruction *InsertPt = Builder.GetInsertPoint();
1271  for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
1272       L = L->getParentLoop())
1273    if (S->isLoopInvariant(L)) {
1274      if (!L) break;
1275      if (BasicBlock *Preheader = L->getLoopPreheader())
1276        InsertPt = Preheader->getTerminator();
1277    } else {
1278      // If the SCEV is computable at this level, insert it into the header
1279      // after the PHIs (and after any other instructions that we've inserted
1280      // there) so that it is guaranteed to dominate any user inside the loop.
1281      if (L && S->hasComputableLoopEvolution(L) && !PostIncLoops.count(L))
1282        InsertPt = L->getHeader()->getFirstNonPHI();
1283      while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
1284        InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
1285      break;
1286    }
1287
1288  // Check to see if we already expanded this here.
1289  std::map<std::pair<const SCEV *, Instruction *>,
1290           AssertingVH<Value> >::iterator I =
1291    InsertedExpressions.find(std::make_pair(S, InsertPt));
1292  if (I != InsertedExpressions.end())
1293    return I->second;
1294
1295  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1296  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1297  Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1298
1299  // Expand the expression into instructions.
1300  Value *V = visit(S);
1301
1302  // Remember the expanded value for this SCEV at this location.
1303  if (PostIncLoops.empty())
1304    InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1305
1306  restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1307  return V;
1308}
1309
1310void SCEVExpander::rememberInstruction(Value *I) {
1311  if (PostIncLoops.empty())
1312    InsertedValues.insert(I);
1313
1314  // If we just claimed an existing instruction and that instruction had
1315  // been the insert point, adjust the insert point forward so that
1316  // subsequently inserted code will be dominated.
1317  if (Builder.GetInsertPoint() == I) {
1318    BasicBlock::iterator It = cast<Instruction>(I);
1319    do { ++It; } while (isInsertedInstruction(It) ||
1320                        isa<DbgInfoIntrinsic>(It));
1321    Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
1322  }
1323}
1324
1325void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
1326  // If we acquired more instructions since the old insert point was saved,
1327  // advance past them.
1328  while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
1329
1330  Builder.SetInsertPoint(BB, I);
1331}
1332
1333/// getOrInsertCanonicalInductionVariable - This method returns the
1334/// canonical induction variable of the specified type for the specified
1335/// loop (inserting one if there is none).  A canonical induction variable
1336/// starts at zero and steps by one on each iteration.
1337Value *
1338SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1339                                                    const Type *Ty) {
1340  assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1341  const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
1342                                   SE.getIntegerSCEV(1, Ty), L);
1343  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1344  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1345  Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
1346  if (SaveInsertBB)
1347    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1348  return V;
1349}
1350