ScalarEvolutionExpander.cpp revision a4c86ab073d4b7a36477fc7c54c9d52499f04586
136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//                     The LLVM Compiler Infrastructure
436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
54ee451de366474b9c228b4e5fa573795a715216dChris Lattner// This file is distributed under the University of Illinois Open Source
64ee451de366474b9c228b4e5fa573795a715216dChris Lattner// License. See LICENSE.TXT for details.
736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//===----------------------------------------------------------------------===//
936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
1036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman// This file contains the implementation of the scalar evolution expander,
1136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman// which is used to generate the code corresponding to a given scalar evolution
1236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman// expression.
1336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
1436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//===----------------------------------------------------------------------===//
1536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman#include "llvm/Analysis/ScalarEvolutionExpander.h"
17e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling#include "llvm/Analysis/LoopInfo.h"
188d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen#include "llvm/IntrinsicInst.h"
1976f600b205606a055ec35e7d3fd1a99602329d67Owen Anderson#include "llvm/LLVMContext.h"
205be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman#include "llvm/Target/TargetData.h"
214d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman#include "llvm/ADT/STLExtras.h"
22d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
2336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begemanusing namespace llvm;
2436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
2519e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
26485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman/// reusing an existing cast if a suitable one exists, moving an existing
27485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman/// cast if a suitable one exists but isn't in the right place, or
2819e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif/// creating a new one.
29db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
30485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman                                       Instruction::CastOps Op,
31485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman                                       BasicBlock::iterator IP) {
32485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Check to see if there is already a cast!
33485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
34f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif       UI != E; ++UI) {
35f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif    User *U = *UI;
36f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif    if (U->getType() == Ty)
3719e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif      if (CastInst *CI = dyn_cast<CastInst>(U))
38485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman        if (CI->getOpcode() == Op) {
39485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman          // If the cast isn't where we want it, fix it.
40485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman          if (BasicBlock::iterator(CI) != IP) {
41485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // Create a new cast, and leave the old cast in place in case
42485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // it is being used as an insert point. Clear its operand
43485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // so that it doesn't hold anything live.
44485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
45485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            NewCI->takeName(CI);
46485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            CI->replaceAllUsesWith(NewCI);
47485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            CI->setOperand(0, UndefValue::get(V->getType()));
48485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            rememberInstruction(NewCI);
49485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            return NewCI;
50485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman          }
516f5fed253f58645bf45448893a585ffbd9914989Dan Gohman          rememberInstruction(CI);
52485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman          return CI;
53485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman        }
54f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif  }
55485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman
56485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Create a new cast.
57485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
58485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  rememberInstruction(I);
59485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  return I;
60485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman}
61485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman
62267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
63267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// which must be possible with a noop cast, doing what we can to share
64267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// the casts.
65db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
66267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
67267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert((Op == Instruction::BitCast ||
68267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::PtrToInt ||
69267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::IntToPtr) &&
70267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot perform non-noop casts!");
71267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
72267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot change sizes!");
73267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
742d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  // Short-circuit unnecessary bitcasts.
75267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (Op == Instruction::BitCast && V->getType() == Ty)
762d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman    return V;
772d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
78f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman  // Short-circuit unnecessary inttoptr<->ptrtoint casts.
79267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
8080dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
81af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman    if (CastInst *CI = dyn_cast<CastInst>(V))
82af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman      if ((CI->getOpcode() == Instruction::PtrToInt ||
83af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman           CI->getOpcode() == Instruction::IntToPtr) &&
84af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getType()) ==
85af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
86af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman        return CI->getOperand(0);
8780dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
8880dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      if ((CE->getOpcode() == Instruction::PtrToInt ||
8980dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman           CE->getOpcode() == Instruction::IntToPtr) &&
9080dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getType()) ==
9180dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
9280dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman        return CE->getOperand(0);
9380dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman  }
94f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman
95485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Fold a cast of a constant.
96ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Constant *C = dyn_cast<Constant>(V))
97baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getCast(Op, C, Ty);
984c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman
99485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Cast the argument at the beginning of the entry block, after
100485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // any bitcasts of other arguments.
101ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Argument *A = dyn_cast<Argument>(V)) {
102485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
103485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    while ((isa<BitCastInst>(IP) &&
104485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
105485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            cast<BitCastInst>(IP)->getOperand(0) != A) ||
106a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling           isa<DbgInfoIntrinsic>(IP) ||
107a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling           isa<LandingPadInst>(IP))
108485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman      ++IP;
109485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    return ReuseOrCreateCast(A, Ty, Op, IP);
110ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  }
1113913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz
112485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Cast the instruction immediately after the instruction.
113ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  Instruction *I = cast<Instruction>(V);
114ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  BasicBlock::iterator IP = I; ++IP;
115ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(I))
116ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    IP = II->getNormalDest()->begin();
117a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling  while (isa<PHINode>(IP) || isa<DbgInfoIntrinsic>(IP) ||
118a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling         isa<LandingPadInst>(IP))
119a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling    ++IP;
120485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  return ReuseOrCreateCast(I, Ty, Op, IP);
121ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner}
122ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner
1237fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// InsertBinop - Insert the specified binary operator, doing a small amount
1247fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// of work to avoid inserting an obviously redundant operation.
125267a385342f2e7388f178b327dd87c5f29afd51bDan GohmanValue *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
126267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 Value *LHS, Value *RHS) {
1270f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  // Fold a binop with constant operands.
1280f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  if (Constant *CLHS = dyn_cast<Constant>(LHS))
1290f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman    if (Constant *CRHS = dyn_cast<Constant>(RHS))
130baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson      return ConstantExpr::get(Opcode, CLHS, CRHS);
1310f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman
1327fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
1337fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  unsigned ScanLimit = 6;
134267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
135267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  // Scanning starts from the last instruction before the insertion point.
136267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator IP = Builder.GetInsertPoint();
137267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (IP != BlockBegin) {
1388a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    --IP;
1398a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    for (; ScanLimit; --IP, --ScanLimit) {
1408d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // Don't count dbg.value against the ScanLimit, to avoid perturbing the
1418d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // generated code.
1428d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      if (isa<DbgInfoIntrinsic>(IP))
1438d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        ScanLimit++;
1445be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
1455be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          IP->getOperand(1) == RHS)
1465be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        return IP;
1478a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz      if (IP == BlockBegin) break;
1488a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    }
1497fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  }
150267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
151087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Save the original insertion point so we can restore it when we're done.
152087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
153087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
154087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
155087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Move the insertion point out of as many loops as we can.
156087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
157087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
158087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
159087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Preheader) break;
160087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
161087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Ok, move up a level.
162087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
163087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
164087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
1658a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz  // If we haven't found this binop, insert it.
166df3ad6697bb849e514c0881ca8700ea36678cbdaDevang Patel  Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS, "tmp"));
167df3ad6697bb849e514c0881ca8700ea36678cbdaDevang Patel  BO->setDebugLoc(SaveInsertPt->getDebugLoc());
168a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(BO);
169087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
170087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Restore the original insert point.
171087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (SaveInsertBB)
172087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
173087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
174cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return BO;
1757fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner}
1767fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner
1774a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// FactorOutConstant - Test if S is divisible by Factor, using signed
178453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// division. If so, update S with Factor divided out and return true.
1793f46a3abeedba8d517b4182de34c821d752db058Dan Gohman/// S need not be evenly divisible if a reasonable remainder can be
1804a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// computed.
181453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
182453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
183453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// check to see if the divide was folded.
1840bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic bool FactorOutConstant(const SCEV *&S,
1850bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                              const SCEV *&Remainder,
186c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const SCEV *Factor,
187c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              ScalarEvolution &SE,
188c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const TargetData *TD) {
189453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // Everything is divisible by one.
190c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (Factor->isOne())
191c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    return true;
192c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
193c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // x/x == 1.
194c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (S == Factor) {
195deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    S = SE.getConstant(S->getType(), 1);
196453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
197c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
198453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
199453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // For a Constant, check for a multiple of the given factor.
2004a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
201c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // 0/x == 0.
202c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (C->isZero())
203453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return true;
204c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Check for divisibility.
205c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
206c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      ConstantInt *CI =
207c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ConstantInt::get(SE.getContext(),
208c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         C->getValue()->getValue().sdiv(
209c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
210c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If the quotient is zero and the remainder is non-zero, reject
211c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // the value at this scale. It will be considered for subsequent
212c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // smaller scales.
213c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!CI->isZero()) {
214c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Div = SE.getConstant(CI);
215c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        S = Div;
216c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Remainder =
217c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          SE.getAddExpr(Remainder,
218c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                        SE.getConstant(C->getValue()->getValue().srem(
219c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                  FC->getValue()->getValue())));
220c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return true;
221c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
222453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
2234a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  }
224453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
225453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In a Mul, check if there is a constant operand which is a multiple
226453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // of the given factor.
227c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
228c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (TD) {
229c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // With TargetData, the size is known. Check if there is a constant
230c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // operand which is a multiple of the given factor. If so, we can
231c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // factor it.
232c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEVConstant *FC = cast<SCEVConstant>(Factor);
233c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
234c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
235f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
236c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[0] =
237c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            SE.getConstant(C->getValue()->getValue().sdiv(
238c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
239c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
240c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
241c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
242c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    } else {
243c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Without TargetData, check if Factor can be factored out of any of the
244c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Mul's operands. If so, we can just remove it.
245c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
246c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *SOp = M->getOperand(i);
247deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman        const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
248c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
249c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            Remainder->isZero()) {
250f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
251c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[i] = SOp;
252c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
253c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
254c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
255453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
256c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
257c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
258453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
259453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In an AddRec, check if both start and step are divisible.
260453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2610bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Step = A->getStepRecurrence(SE);
262deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
263c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
2644a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2654a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman    if (!StepRem->isZero())
2664a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2670bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Start = A->getStart();
268c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
269453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return false;
2703228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    // FIXME: can use A->getNoWrapFlags(FlagNW)
2713228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    S = SE.getAddRecExpr(Start, Step, A->getLoop(), SCEV::FlagAnyWrap);
272453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
273453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
274453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
275453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  return false;
276453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
277453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
278c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
279c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// is the number of SCEVAddRecExprs present, which are kept at the end of
280c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// the list.
281c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
282c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
283db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                Type *Ty,
284c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                ScalarEvolution &SE) {
285c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  unsigned NumAddRecs = 0;
286c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
287c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ++NumAddRecs;
288c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Group Ops into non-addrecs and addrecs.
289c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
290c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
291c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Let ScalarEvolution sort and simplify the non-addrecs list.
292c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  const SCEV *Sum = NoAddRecs.empty() ?
293deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman                    SE.getConstant(Ty, 0) :
294c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                    SE.getAddExpr(NoAddRecs);
295c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // If it returned an add, use the operands. Otherwise it simplified
296c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // the sum into a single value, so just use that.
297f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  Ops.clear();
298c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
299403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman    Ops.append(Add->op_begin(), Add->op_end());
300f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  else if (!Sum->isZero())
301f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    Ops.push_back(Sum);
302c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Then append the addrecs.
303403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman  Ops.append(AddRecs.begin(), AddRecs.end());
304c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
305c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
306c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
307c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
308c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// This helps expose more opportunities for folding parts of the expressions
309c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// into GEP indices.
310c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
311c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
312db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                         Type *Ty,
313c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         ScalarEvolution &SE) {
314c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Find the addrecs.
315c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs;
316c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
317c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
318c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEV *Start = A->getStart();
319c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (Start->isZero()) break;
320deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman      const SCEV *Zero = SE.getConstant(Ty, 0);
321c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      AddRecs.push_back(SE.getAddRecExpr(Zero,
322c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                         A->getStepRecurrence(SE),
3233228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                         A->getLoop(),
3243228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                         // FIXME: A->getNoWrapFlags(FlagNW)
3253228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                         SCEV::FlagAnyWrap));
326c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
327c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Zero;
328403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman        Ops.append(Add->op_begin(), Add->op_end());
329c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        e += Add->getNumOperands();
330c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
331c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Start;
332c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
333c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
334c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (!AddRecs.empty()) {
335c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Add the addrecs onto the end of the list.
336403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman    Ops.append(AddRecs.begin(), AddRecs.end());
337c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Resort the operand list, moving any constants to the front.
338c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    SimplifyAddOperands(Ops, Ty, SE);
339c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
340c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
341c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
3424c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// expandAddToGEP - Expand an addition expression with a pointer type into
3434c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
3444c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// BasicAliasAnalysis and other passes analyze the result. See the rules
3454c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for getelementptr vs. inttoptr in
3464c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// http://llvm.org/docs/LangRef.html#pointeraliasing
3474c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for details.
34813c5e35222afe0895f0c5e68aa9f22f134ea437aDan Gohman///
3493abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman/// Design note: The correctness of using getelementptr here depends on
3504c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
3514c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// they may introduce pointer arithmetic which may not be safely converted
3524c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// into getelementptr.
353453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
354453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Design note: It might seem desirable for this function to be more
355453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-aware. If some of the indices are loop-invariant while others
356453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// aren't, it might seem desirable to emit multiple GEPs, keeping the
357453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of the overall computation outside the loop.
358453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// However, there are a few reasons this is not done here. Hoisting simple
359453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// arithmetic is a low-level optimization that often isn't very
360453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// important until late in the optimization process. In fact, passes
361453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// like InstructionCombining will combine GEPs, even if it means
362453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// pushing loop-invariant computation down into loops, so even if the
363453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEPs were split here, the work would quickly be undone. The
364453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// LoopStrengthReduction pass, which is usually run quite late (and
365453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// after the last InstructionCombining pass), takes care of hoisting
366453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of expressions, after considering what
367453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// can be folded using target addressing modes.
368453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
3690bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan GohmanValue *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
3700bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                                    const SCEV *const *op_end,
371db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                    PointerType *PTy,
372db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                    Type *Ty,
3735be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    Value *V) {
374db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *ElTy = PTy->getElementType();
3755be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  SmallVector<Value *, 4> GepIndices;
3760bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
3775be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  bool AnyNonZeroIndices = false;
3785be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
379c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Split AddRecs up into parts as either of the parts may be usable
380c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // without the other.
381c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SplitAddRecs(Ops, Ty, SE);
382c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
383eb35699e642f2c021f04154bdb4bd90a1afb3baaBob Wilson  // Descend down the pointer's type and attempt to convert the other
3845be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // operands into GEP indices, at each level. The first index in a GEP
3855be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // indexes into the array implied by the pointer operand; the rest of
3865be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the indices index into the element or field type selected by the
3875be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // preceding index.
3885be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  for (;;) {
389c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If the scale size is not 0, attempt to factor out a scale for
390c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // array indexing.
3910bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> ScaledOps;
392150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman    if (ElTy->isSized()) {
3934f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman      const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
394150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman      if (!ElSize->isZero()) {
395150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        SmallVector<const SCEV *, 8> NewOps;
396150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
397150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          const SCEV *Op = Ops[i];
398deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman          const SCEV *Remainder = SE.getConstant(Ty, 0);
399150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
400150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // Op now has ElSize factored out.
401150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            ScaledOps.push_back(Op);
402150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            if (!Remainder->isZero())
403150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman              NewOps.push_back(Remainder);
404150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            AnyNonZeroIndices = true;
405150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          } else {
406150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // The operand was not divisible, so add it to the list of operands
407150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // we'll scan next iteration.
408150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            NewOps.push_back(Ops[i]);
409150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          }
410150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        }
411150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        // If we made any changes, update Ops.
412150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        if (!ScaledOps.empty()) {
413150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          Ops = NewOps;
414150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          SimplifyAddOperands(Ops, Ty, SE);
4155be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        }
416c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
4175be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
418c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
419c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Record the scaled array index for this level of the type. If
420c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // we didn't find any operands that could be factored, tentatively
421c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // assume that element zero was selected (since the zero offset
422c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // would obviously be folded away).
4235be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    Value *Scaled = ScaledOps.empty() ?
424a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson                    Constant::getNullValue(Ty) :
4255be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                    expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
4265be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    GepIndices.push_back(Scaled);
4275be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4285be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Collect struct field index operands.
429db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    while (StructType *STy = dyn_cast<StructType>(ElTy)) {
430c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      bool FoundFieldNo = false;
431c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // An empty struct has no fields.
432c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (STy->getNumElements() == 0) break;
433c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (SE.TD) {
434c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // With TargetData, field offsets are known. See if a constant offset
435c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // falls within any of the struct fields.
436c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (Ops.empty()) break;
4375be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
4385be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          if (SE.getTypeSizeInBits(C->getType()) <= 64) {
4395be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            const StructLayout &SL = *SE.TD->getStructLayout(STy);
4405be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            uint64_t FullOffset = C->getValue()->getZExtValue();
4415be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            if (FullOffset < SL.getSizeInBytes()) {
4425be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
4431d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson              GepIndices.push_back(
4441d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                  ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
4455be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              ElTy = STy->getTypeAtIndex(ElIdx);
4465be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              Ops[0] =
4476de29f8d960505421d61c80cdb738e16720b6c0eDan Gohman                SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
4485be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              AnyNonZeroIndices = true;
449c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
4505be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            }
4515be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          }
452c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
4530f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman        // Without TargetData, just check for an offsetof expression of the
454c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // appropriate struct type.
455c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4560f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
457db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner            Type *CTy;
4580f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman            Constant *FieldNo;
4594f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman            if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
4600f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman              GepIndices.push_back(FieldNo);
4610f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman              ElTy =
4620f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman                STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
463c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              Ops[i] = SE.getConstant(Ty, 0);
464c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              AnyNonZeroIndices = true;
465c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
466c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              break;
467c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            }
4680f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          }
4695be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
470c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If no struct field offsets were found, tentatively assume that
471c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // field zero was selected (since the zero offset would obviously
472c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // be folded away).
473c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!FoundFieldNo) {
474c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ElTy = STy->getTypeAtIndex(0u);
475c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        GepIndices.push_back(
476c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
477c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
478c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
4795be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
480db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
4815be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      ElTy = ATy->getElementType();
482c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    else
483c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      break;
4845be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
4855be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4863f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // If none of the operands were convertible to proper GEP indices, cast
4875be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the base to i8* and do an ugly getelementptr with that. It's still
4885be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // better than ptrtoint+arithmetic+inttoptr at least.
4895be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (!AnyNonZeroIndices) {
490c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Cast the base to i8*.
4915be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V,
492ac53a0b272452013124bfc70480aea5e41b60f40Duncan Sands       Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
493c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
494c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Expand the operands for a plain byte offset.
49592fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
4965be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4975be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Fold a GEP with constant operands.
4985be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    if (Constant *CLHS = dyn_cast<Constant>(V))
4995be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (Constant *CRHS = dyn_cast<Constant>(Idx))
500dab3d29605a5c83db41b28176273ef55961120c1Jay Foad        return ConstantExpr::getGetElementPtr(CLHS, CRHS);
5015be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
5025be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
5035be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    unsigned ScanLimit = 6;
504267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
505267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    // Scanning starts from the last instruction before the insertion point.
506267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator IP = Builder.GetInsertPoint();
507267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    if (IP != BlockBegin) {
5085be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      --IP;
5095be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      for (; ScanLimit; --IP, --ScanLimit) {
5108d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        // Don't count dbg.value against the ScanLimit, to avoid perturbing the
5118d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        // generated code.
5128d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        if (isa<DbgInfoIntrinsic>(IP))
5138d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen          ScanLimit++;
5145be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP->getOpcode() == Instruction::GetElementPtr &&
5155be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            IP->getOperand(0) == V && IP->getOperand(1) == Idx)
5165be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          return IP;
5175be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP == BlockBegin) break;
5185be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
5195be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
5205be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
521087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Save the original insertion point so we can restore it when we're done.
522087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
523087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
524087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
525087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Move the insertion point out of as many loops as we can.
526087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
527087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
528087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      BasicBlock *Preheader = L->getLoopPreheader();
529087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!Preheader) break;
530087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
531087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Ok, move up a level.
532087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
533087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
534087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
535c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Emit a GEP.
536c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
537a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(GEP);
538087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
539087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Restore the original insert point.
540087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (SaveInsertBB)
541087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      restoreInsertPoint(SaveInsertBB, SaveInsertPt);
542087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
5435be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    return GEP;
5445be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
5455be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
546087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Save the original insertion point so we can restore it when we're done.
547087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
548087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
549087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
550087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Move the insertion point out of as many loops as we can.
551087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
552087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!L->isLoopInvariant(V)) break;
553087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
554087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    bool AnyIndexNotLoopInvariant = false;
555087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
556087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman         E = GepIndices.end(); I != E; ++I)
557087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!L->isLoopInvariant(*I)) {
558087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        AnyIndexNotLoopInvariant = true;
559087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        break;
560087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      }
561087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (AnyIndexNotLoopInvariant)
562087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      break;
563087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
564087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
565087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Preheader) break;
566087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
567087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Ok, move up a level.
568087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
569087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
570087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
571d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
572d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // because ScalarEvolution may have changed the address arithmetic to
573d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // compute a value which is beyond the end of the allocated object.
574a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Casted = V;
575a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (V->getType() != PTy)
576a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Casted = InsertNoopCastOfTo(Casted, PTy);
577a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *GEP = Builder.CreateGEP(Casted,
5780a2a60ace9b79164b71794ce7ff981171c61e442Jay Foad                                 GepIndices,
579267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 "scevgep");
5805be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  Ops.push_back(SE.getUnknown(GEP));
581a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(GEP);
582087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
583087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Restore the original insert point.
584087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (SaveInsertBB)
585087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
586087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
5875be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return expand(SE.getAddExpr(Ops));
5885be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman}
5895be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
590a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// isNonConstantNegative - Return true if the specified scev is negated, but
591a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// not a constant.
592a10756ee657a4d43a48cca5c166919093930ed6bDan Gohmanstatic bool isNonConstantNegative(const SCEV *F) {
593a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
594a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!Mul) return false;
595a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
596a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // If there is a constant factor, it will be first.
597a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
598a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!SC) return false;
599a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
600a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Return true if the value is negative, this matches things like (-42 * V).
601a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return SC->getValue()->getValue().isNegative();
602a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
603a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
604087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
605087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// SCEV expansion. If they are nested, this is the most nested. If they are
606087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// neighboring, pick the later.
607087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanstatic const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
608087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                                        DominatorTree &DT) {
609087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!A) return B;
610087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!B) return A;
611087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (A->contains(B)) return B;
612087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (B->contains(A)) return A;
613087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(A->getHeader(), B->getHeader())) return B;
614087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(B->getHeader(), A->getHeader())) return A;
615087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return A; // Arbitrarily break the tie.
616087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
617087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
6189c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman/// getRelevantLoop - Get the most relevant loop associated with the given
619087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// expression, according to PickMostRelevantLoop.
6209c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohmanconst Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
6219c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  // Test whether we've already computed the most relevant loop for this SCEV.
6229c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
6239c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
6249c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (!Pair.second)
6259c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return Pair.first->second;
6269c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman
627087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (isa<SCEVConstant>(S))
6289c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    // A constant has no relevant loops.
629087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return 0;
630087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
631087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
6329c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman      return Pair.first->second = SE.LI->getLoopFor(I->getParent());
6339c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    // A non-instruction has no relevant loops.
634087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return 0;
635087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
636087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
637087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const Loop *L = 0;
638087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
639087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      L = AR->getLoop();
640087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
641087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman         I != E; ++I)
6429c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman      L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
6439c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[N] = L;
6449c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  }
6459c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
6469c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    const Loop *Result = getRelevantLoop(C->getOperand());
6479c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[C] = Result;
6489c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  }
6499c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
6509c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    const Loop *Result =
6519c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman      PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
6529c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman                           getRelevantLoop(D->getRHS()),
6539c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman                           *SE.DT);
6549c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[D] = Result;
655087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
656087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  llvm_unreachable("Unexpected SCEV type!");
6579c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  return 0;
658087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
659c4f7ec85ecb760fff2b702c6deb06506b968ba4fDan Gohman
660b35798347ea87b8b6d36155b211016a7769f01abDan Gohmannamespace {
661b35798347ea87b8b6d36155b211016a7769f01abDan Gohman
662087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// LoopCompare - Compare loops by PickMostRelevantLoop.
663087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanclass LoopCompare {
664087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  DominatorTree &DT;
665087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanpublic:
666087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
667087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
668087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  bool operator()(std::pair<const Loop *, const SCEV *> LHS,
669087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                  std::pair<const Loop *, const SCEV *> RHS) const {
670bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman    // Keep pointer operands sorted at the end.
671bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman    if (LHS.second->getType()->isPointerTy() !=
672bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        RHS.second->getType()->isPointerTy())
673bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      return LHS.second->getType()->isPointerTy();
674bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman
675087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Compare loops with PickMostRelevantLoop.
676087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (LHS.first != RHS.first)
677087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
678087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
679087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // If one operand is a non-constant negative and the other is not,
680087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // put the non-constant negative on the right so that a sub can
681087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // be used instead of a negate and add.
682087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (isNonConstantNegative(LHS.second)) {
683087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!isNonConstantNegative(RHS.second))
684087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        return false;
685087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (isNonConstantNegative(RHS.second))
686087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return true;
687087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
688087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Otherwise they are equivalent according to this comparison.
689087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return false;
690c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
691087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman};
6925be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
693b35798347ea87b8b6d36155b211016a7769f01abDan Gohman}
694b35798347ea87b8b6d36155b211016a7769f01abDan Gohman
695087bd1e3a12893873761736bf0f905a350e9e708Dan GohmanValue *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
696db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
697e24fa64d52330626553298f56ba5aa702624c282Dan Gohman
698087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the add operands in a loop, along with their associated loops.
699087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal, and
700087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // so that pointer operands are inserted first, which the code below relies on
701087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // to form more involved GEPs.
702087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
703087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
704087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
7059c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
706087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
707087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants and
708087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // pointer operands precede non-pointer operands.
709087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
710087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
711087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to add all the operands. Hoist as much as possible
712087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops, and form meaningful getelementptrs where possible.
713087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  Value *Sum = 0;
714087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
715087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
716087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const Loop *CurLoop = I->first;
717087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const SCEV *Op = I->second;
718087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Sum) {
719087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
720087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expand(Op);
721087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
722db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
723087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum expression is a pointer. Try to form a getelementptr
724087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // at this level with that as the base.
725087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
726bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      for (; I != E && I->first == CurLoop; ++I) {
727bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        // If the operand is SCEVUnknown and not instructions, peek through
728bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        // it, to enable more of it to be folded into the GEP.
729bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        const SCEV *X = I->second;
730bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
731bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman          if (!isa<Instruction>(U->getValue()))
732bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman            X = SE.getSCEV(U->getValue());
733bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        NewOps.push_back(X);
734bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      }
735087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
736db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
737087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum is an integer, and there's a pointer at this level.
738f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // Try to form a getelementptr. If the running sum is instructions,
739f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // use a SCEVUnknown to avoid re-analyzing them.
740087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
741f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
742f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman                                               SE.getSCEV(Sum));
743087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      for (++I; I != E && I->first == CurLoop; ++I)
744087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        NewOps.push_back(I->second);
745087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
746087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (isNonConstantNegative(Op)) {
747087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a negate and add, just do a subtract.
748a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
749087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
750087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Sub, Sum, W);
751087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
752a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
753087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple add.
754a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(Op, Ty);
755087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
756087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
757087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Sum)) std::swap(Sum, W);
758087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Add, Sum, W);
759087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
760a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
7612d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
762087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
763087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Sum;
764e24fa64d52330626553298f56ba5aa702624c282Dan Gohman}
7655be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
766890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
767db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
768087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
769087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the mul operands in a loop, along with their associated loops.
770087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal.
771087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
772087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
773087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
7749c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
775087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
776087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants.
777087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
778087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
779087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to mul all the operands. Hoist as much as possible
780087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops.
781087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  Value *Prod = 0;
782087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
783087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
784087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const SCEV *Op = I->second;
785087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Prod) {
786087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
787087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = expand(Op);
788087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
789087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (Op->isAllOnesValue()) {
790087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a multiply by negative one, just do a negate.
791087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
792087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
793087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
794087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else {
795087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple mul.
796087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Value *W = expandCodeFor(Op, Ty);
797087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
798087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
799087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Prod)) std::swap(Prod, W);
800087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertBinop(Instruction::Mul, Prod, W);
801087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
802087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
8032d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
8042d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
805087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Prod;
80636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
80736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
808890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
809db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
8102d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
81192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *LHS = expandCodeFor(S->getLHS(), Ty);
812890f92b744fb074465bc2b7006ee753a181f62a4Dan Gohman  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
8136177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    const APInt &RHS = SC->getValue()->getValue();
8146177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    if (RHS.isPowerOf2())
8156177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky      return InsertBinop(Instruction::LShr, LHS,
816eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson                         ConstantInt::get(Ty, RHS.logBase2()));
8176177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky  }
8186177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
81992fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *RHS = expandCodeFor(S->getRHS(), Ty);
820267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  return InsertBinop(Instruction::UDiv, LHS, RHS);
8216177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky}
8226177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
823453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Move parts of Base into Rest to leave Base with the minimal
824453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// expression that provides a pointer operand suitable for a
825453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEP expansion.
8260bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
827453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                              ScalarEvolution &SE) {
828453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
829453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getStart();
830453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(Rest,
831deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman                         SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
832453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                                          A->getStepRecurrence(SE),
8333228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                          A->getLoop(),
8343228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                          // FIXME: A->getNoWrapFlags(FlagNW)
8353228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                          SCEV::FlagAnyWrap));
836453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
837453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
838453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getOperand(A->getNumOperands()-1);
8390bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
840453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    NewAddOps.back() = Rest;
841453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(NewAddOps);
842453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    ExposePointerBase(Base, Rest, SE);
843453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
844453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
845453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
846a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
847a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// the base addrec, which is the addrec without any non-loop-dominating
848a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// values, and return the PHI.
849a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanPHINode *
850a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanSCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
851a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                        const Loop *L,
852db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                        Type *ExpandTy,
853db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                        Type *IntTy) {
85493a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer  assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
855d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
856a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Reuse a previously-inserted PHI, if present.
857a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  for (BasicBlock::iterator I = L->getHeader()->begin();
858a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman       PHINode *PN = dyn_cast<PHINode>(I); ++I)
859572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman    if (SE.isSCEVable(PN->getType()) &&
860572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        (SE.getEffectiveSCEVType(PN->getType()) ==
861572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman         SE.getEffectiveSCEVType(Normalized->getType())) &&
862572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        SE.getSCEV(PN) == Normalized)
863572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman      if (BasicBlock *LatchBlock = L->getLoopLatch()) {
864572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        Instruction *IncV =
86522e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
86622e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman
86722e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        // Determine if this is a well-behaved chain of instructions leading
86822e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        // back to the PHI. It probably will be, if we're scanning an inner
86922e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        // loop already visited by LSR for example, but it wouldn't have
87022e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        // to be.
87122e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        do {
8720cbe91ba3bd84a5ef68a1d0de5df6e955690b0a4Dan Gohman          if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
873a7a841adb89efa6ad3b35e9d4bcccccfb8ca146aDan Gohman              (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV))) {
87422e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            IncV = 0;
87522e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            break;
87622e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          }
8779feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman          // If any of the operands don't dominate the insert position, bail.
8789feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman          // Addrec operands are always loop-invariant, so this can only happen
8799feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman          // if there are instructions which haven't been hoisted.
880d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick          if (L == IVIncInsertLoop) {
881d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick            for (User::op_iterator OI = IncV->op_begin()+1,
882d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick                   OE = IncV->op_end(); OI != OE; ++OI)
883d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick              if (Instruction *OInst = dyn_cast<Instruction>(OI))
884d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick                if (!SE.DT->dominates(OInst, IVIncInsertPos)) {
885d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick                  IncV = 0;
886d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick                  break;
887d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick                }
888d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick          }
8899feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman          if (!IncV)
8909feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman            break;
8919feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman          // Advance to the next instruction.
89222e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          IncV = dyn_cast<Instruction>(IncV->getOperand(0));
89322e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          if (!IncV)
89422e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            break;
89522e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          if (IncV->mayHaveSideEffects()) {
89622e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            IncV = 0;
89722e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            break;
89822e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          }
89922e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        } while (IncV != PN);
90022e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman
90122e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        if (IncV) {
90222e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          // Ok, the add recurrence looks usable.
90322e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          // Remember this PHI, even in post-inc mode.
90422e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          InsertedValues.insert(PN);
90522e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          // Remember the increment.
90622e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          IncV = cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
90722e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          rememberInstruction(IncV);
90822e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          if (L == IVIncInsertLoop)
90922e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            do {
91022e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              if (SE.DT->dominates(IncV, IVIncInsertPos))
91122e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman                break;
91222e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              // Make sure the increment is where we want it. But don't move it
91322e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              // down past a potential existing post-inc user.
91422e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              IncV->moveBefore(IVIncInsertPos);
91522e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              IVIncInsertPos = IncV;
91622e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              IncV = cast<Instruction>(IncV->getOperand(0));
91722e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            } while (IncV != PN);
91822e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          return PN;
91922e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        }
920572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman      }
921a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
922a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Save the original insertion point so we can restore it when we're done.
923a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
924a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
925a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
926a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand code for the start value.
927a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
928a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                L->getHeader()->begin());
929a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
930d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick  // StartV must be hoisted into L's preheader to dominate the new phi.
93193a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer  assert(!isa<Instruction>(StartV) ||
93293a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer         SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
93393a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer                                  L->getHeader()));
934d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
935a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand code for the step value. Insert instructions right before the
936a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // terminator corresponding to the back-edge. Do this before creating the PHI
937a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
938a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // negative, insert a sub instead of an add for the increment (unless it's a
939a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // constant, because subtracts of constants are canonicalized to adds).
940a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
9411df9859c40492511b8aa4321eb76496005d3b75bDuncan Sands  bool isPointer = ExpandTy->isPointerTy();
942a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  bool isNegative = !isPointer && isNonConstantNegative(Step);
943a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (isNegative)
944a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Step = SE.getNegativeSCEV(Step);
945a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
946a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
947a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the PHI.
948d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  BasicBlock *Header = L->getHeader();
949d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  Builder.SetInsertPoint(Header, Header->begin());
950d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
9515e7645be4c9dd2193add44d30b5fef8036d7a3ceAndrew Trick  PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
952dc8e546048db2f7ff5656742b2b26975098a11a0Andrew Trick                                  Twine(IVName) + ".iv");
953a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(PN);
954a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
955a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the step instructions and populate the PHI.
956d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
957a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *Pred = *HPI;
958a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
959a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // Add a start value.
960a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (!L->contains(Pred)) {
961a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      PN->addIncoming(StartV, Pred);
962a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      continue;
963a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
964a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
965a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // Create a step value and add it to the PHI. If IVIncInsertLoop is
966a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // non-null and equal to the addrec's loop, insert the instructions
967a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // at IVIncInsertPos.
968a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Instruction *InsertPos = L == IVIncInsertLoop ?
969a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IVIncInsertPos : Pred->getTerminator();
970c5ecbdc1896f1cc089372feef3191ace2f840898Devang Patel    Builder.SetInsertPoint(InsertPos);
971a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Value *IncV;
972a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
973a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (isPointer) {
974db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner      PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
975a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      // If the step isn't constant, don't use an implicitly scaled GEP, because
976a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      // that would require a multiply inside the loop.
977a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      if (!isa<ConstantInt>(StepV))
978a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
979a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                    GEPPtrTy->getAddressSpace());
980a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
981a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
982a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      if (IncV->getType() != PN->getType()) {
983a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
984a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        rememberInstruction(IncV);
985a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      }
986a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
987a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IncV = isNegative ?
988dc8e546048db2f7ff5656742b2b26975098a11a0Andrew Trick        Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
989dc8e546048db2f7ff5656742b2b26975098a11a0Andrew Trick        Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
990a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      rememberInstruction(IncV);
991a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
992a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PN->addIncoming(IncV, Pred);
993a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
994a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
995a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Restore the original insert point.
996a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (SaveInsertBB)
997455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
998a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
999a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Remember this PHI, even in post-inc mode.
1000a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  InsertedValues.insert(PN);
1001a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1002a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return PN;
1003a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
1004a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1005a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanValue *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1006db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *STy = S->getType();
1007db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *IntTy = SE.getEffectiveSCEVType(STy);
1008a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Loop *L = S->getLoop();
1009a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1010a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Determine a normalized form of this expression, which is the expression
1011a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // before any post-inc adjustment is made.
1012a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVAddRecExpr *Normalized = S;
1013448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (PostIncLoops.count(L)) {
1014448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    PostIncLoopSet Loops;
1015448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    Loops.insert(L);
1016448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    Normalized =
1017448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman      cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1018448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman                                                  Loops, SE, *SE.DT));
1019a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1020a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1021a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec start.
1022a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Start = Normalized->getStart();
1023a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *PostLoopOffset = 0;
1024dc0e8fb9f9512622f55f73e1a434caa5c0915694Dan Gohman  if (!SE.properlyDominates(Start, L->getHeader())) {
1025a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopOffset = Start;
1026deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    Start = SE.getConstant(Normalized->getType(), 0);
10273228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    Normalized = cast<SCEVAddRecExpr>(
10283228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick      SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
10293228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                       Normalized->getLoop(),
10303228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                       // FIXME: Normalized->getNoWrapFlags(FlagNW)
10313228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                       SCEV::FlagAnyWrap));
1032a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1033a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1034a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec step.
1035a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
1036a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *PostLoopScale = 0;
1037dc0e8fb9f9512622f55f73e1a434caa5c0915694Dan Gohman  if (!SE.dominates(Step, L->getHeader())) {
1038a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopScale = Step;
1039deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    Step = SE.getConstant(Normalized->getType(), 1);
1040a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Normalized =
1041a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
10423228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            Normalized->getLoop(),
10433228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            // FIXME: Normalized
10443228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            // ->getNoWrapFlags(FlagNW)
10453228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            SCEV::FlagAnyWrap));
1046a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1047a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1048a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand the core addrec. If we need post-loop scaling, force it to
1049a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // expand to an integer type to avoid the need for additional casting.
1050db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *ExpandTy = PostLoopScale ? IntTy : STy;
1051a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1052a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
10533f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // Accommodate post-inc mode, if necessary.
1054a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Result;
1055448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (!PostIncLoops.count(L))
1056a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN;
1057a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  else {
1058a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // In PostInc mode, use the post-incremented value.
1059a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *LatchBlock = L->getLoopLatch();
1060a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1061a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN->getIncomingValueForBlock(LatchBlock);
1062a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1063a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1064a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating scale.
1065a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopScale) {
10660a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman    Result = InsertNoopCastOfTo(Result, IntTy);
1067a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = Builder.CreateMul(Result,
1068a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                               expandCodeFor(PostLoopScale, IntTy));
1069a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Result);
1070a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1071a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1072a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating offset.
1073a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopOffset) {
1074db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1075a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const SCEV *const OffsetArray[1] = { PostLoopOffset };
1076a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1077a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
10780a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman      Result = InsertNoopCastOfTo(Result, IntTy);
1079a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = Builder.CreateAdd(Result,
1080a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                 expandCodeFor(PostLoopOffset, IntTy));
1081a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      rememberInstruction(Result);
1082a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
1083a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1084a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1085a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return Result;
1086a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
1087a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1088890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1089a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!CanonicalMode) return expandAddRecExprLiterally(S);
1090a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1091db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
109236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  const Loop *L = S->getLoop();
109336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
10944d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // First check for an existing canonical IV in a suitable type.
10954d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  PHINode *CanonicalIV = 0;
10964d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (PHINode *PN = L->getCanonicalInductionVariable())
1097133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman    if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
10984d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      CanonicalIV = PN;
10994d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
11004d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Rewrite an AddRec in terms of the canonical induction variable, if
11014d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // its type is more narrow.
11024d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (CanonicalIV &&
11034d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(CanonicalIV->getType()) >
11044d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(Ty)) {
1105f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1106f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1107f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman      NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
11083228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
11093228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                       // FIXME: S->getNoWrapFlags(FlagNW)
11103228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                       SCEV::FlagAnyWrap));
1111267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1112267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
11134d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    BasicBlock::iterator NewInsertPt =
11147896c9f436a4eda5ec15e882a7505ba482a2fcd0Chris Lattner      llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
1115a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling    while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1116a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling           isa<LandingPadInst>(NewInsertPt))
111708f55d02da2cd24f3b4297259ef6429b8bf1ef97Jim Grosbach      ++NewInsertPt;
11184d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
11194d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman                      NewInsertPt);
1120455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
11214d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    return V;
11224d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  }
11234d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
112436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // {X,+,F} --> X + {0,+,F}
1125cfeb6a450632f2a6cd05302633c8c2b8c90cfdfdDan Gohman  if (!S->getStart()->isZero()) {
1126f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1127deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    NewOps[0] = SE.getConstant(Ty, 0);
11283228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    // FIXME: can use S->getNoWrapFlags()
11293228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    const SCEV *Rest = SE.getAddRecExpr(NewOps, L, SCEV::FlagAnyWrap);
1130453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
1131453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1132453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // comments on expandAddToGEP for details.
1133c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *Base = S->getStart();
1134c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *RestArray[1] = { Rest };
1135c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Dig into the expression to find the pointer base for a GEP.
1136c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ExposePointerBase(Base, RestArray[0], SE);
1137c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If we found a pointer, expand the AddRec with a GEP.
1138db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1139c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Make sure the Base isn't something exotic, such as a multiplied
1140c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // or divided pointer value. In those cases, the result type isn't
1141c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // actually a pointer type.
1142c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1143c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Value *StartV = expand(Base);
1144c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1145c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1146453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
1147453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
1148453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
114940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    // Just do a normal add. Pre-expand the operands to suppress folding.
115040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
115140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                SE.getUnknown(expand(Rest))));
115236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
115336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
11546ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  // If we don't yet have a canonical IV, create one.
11556ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  if (!CanonicalIV) {
115636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // Create and insert the PHI node for the induction variable in the
115736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // specified loop.
115836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    BasicBlock *Header = L->getHeader();
1159d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad    pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
11603ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad    CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
11613ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad                                  Header->begin());
11626ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    rememberInstruction(CanonicalIV);
116336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1164eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson    Constant *One = ConstantInt::get(Ty, 1);
1165d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad    for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
11667656018c2268285907cfdc106071462a01a73878Gabor Greif      BasicBlock *HP = *HPI;
11677656018c2268285907cfdc106071462a01a73878Gabor Greif      if (L->contains(HP)) {
11683abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // Insert a unit add instruction right before the terminator
11693abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // corresponding to the back-edge.
11706ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
11716ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                                     "indvar.next",
11726ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                                     HP->getTerminator());
1173df3ad6697bb849e514c0881ca8700ea36678cbdaDevang Patel        Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1174a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        rememberInstruction(Add);
11756ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        CanonicalIV->addIncoming(Add, HP);
117683d577490b1473213b6973236110c28e59127956Dan Gohman      } else {
11776ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
117883d577490b1473213b6973236110c28e59127956Dan Gohman      }
11797656018c2268285907cfdc106071462a01a73878Gabor Greif    }
118036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
118136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
11826ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  // {0,+,1} --> Insert a canonical induction variable into the loop!
11836ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  if (S->isAffine() && S->getOperand(1)->isOne()) {
11846ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
11856ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman           "IVs with types different from the canonical IV should "
11866ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman           "already have been handled!");
11876ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    return CanonicalIV;
11886ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  }
11896ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman
11904d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // {0,+,F} --> {0,+,1} * F
119136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1192df14a04b5ccbbe6a46c2ccb93e27b12a36ff163eChris Lattner  // If this is a simple linear addrec, emit it now as a special case.
119340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  if (S->isAffine())    // {0,+,F} --> i*F
119440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return
119540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      expand(SE.getTruncateOrNoop(
11966ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        SE.getMulExpr(SE.getUnknown(CanonicalIV),
119740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                      SE.getNoopOrAnyExtend(S->getOperand(1),
11986ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                            CanonicalIV->getType())),
119940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        Ty));
120036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
120136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // If this is a chain of recurrences, turn it into a closed form, using the
120236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // folders, then expandCodeFor the closed form.  This allows the folders to
120336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // simplify the expression without having to build a bunch of special code
120436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // into this folder.
12056ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
120636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
12074d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Promote S up to the canonical IV type, if the cast is foldable.
12080bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *NewS = S;
12096ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
12104d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (isa<SCEVAddRecExpr>(Ext))
12114d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    NewS = Ext;
12124d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
12130bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1214e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
121536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
12164d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Truncate the result down to the original type, if needed.
12170bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1218469f3cdc13851914f3a766cbd8f701cf8431cacaDan Gohman  return expand(T);
121936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
122096fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov
1221890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1222db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
122392fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
122492fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1225267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateTrunc(V, Ty, "tmp");
1226a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1227cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
122811f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
122911f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1230890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1231db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
123292fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
123392fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1234267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateZExt(V, Ty, "tmp");
1235a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1236cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
123711f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
123811f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1239890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1240db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
124192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
124292fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1243267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateSExt(V, Ty, "tmp");
1244a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1245cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
124611f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
124711f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1248890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
12490196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1250db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = LHS->getType();
12510196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
12520196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
12530196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
12540196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
12550196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
12560196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
12570196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
125892fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1259267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
1260a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1261267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1262a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1263cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
1264c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  }
12650196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
12660196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
12670196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
12680196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
1269c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  return LHS;
1270c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky}
1271c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky
1272890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
12730196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1274db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = LHS->getType();
12750196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
12760196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
12770196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
12780196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
12790196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
12800196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
12810196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
128292fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1283267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
1284a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1285267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1286a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1287cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
12883e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  }
12890196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
12900196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
12910196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
12920196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
12933e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  return LHS;
12943e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky}
12953e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky
1296db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
12976c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman                                   Instruction *I) {
12986c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  BasicBlock::iterator IP = I;
12996c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
13006c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman    ++IP;
13016c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  Builder.SetInsertPoint(IP->getParent(), IP);
13026c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  return expandCodeFor(SH, Ty);
13036c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman}
13046c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman
1305db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
130611f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman  // Expand the code for this SCEV.
13072d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  Value *V = expand(SH);
13085be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (Ty) {
13095be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
13105be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman           "non-trivial casts should be done with the SCEVs directly!");
13115be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V, Ty);
13125be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
13135be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return V;
131411f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
131511f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1316890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::expand(const SCEV *S) {
131740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // Compute an insertion point for this SCEV object. Hoist the instructions
131840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // as far out in the loop nest as possible.
1319267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction *InsertPt = Builder.GetInsertPoint();
1320267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
132140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman       L = L->getParentLoop())
132217ead4ff4baceb2c5503f233d0288d363ae44165Dan Gohman    if (SE.isLoopInvariant(S, L)) {
132340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (!L) break;
1324e059ee832ca36d65a5fb87b0ac5bcdb0490b15cbDan Gohman      if (BasicBlock *Preheader = L->getLoopPreheader())
132540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        InsertPt = Preheader->getTerminator();
132640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    } else {
132740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // If the SCEV is computable at this level, insert it into the header
132840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // after the PHIs (and after any other instructions that we've inserted
132940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // there) so that it is guaranteed to dominate any user inside the loop.
13305b6f42f57e730c2d968c313a27fa505a3c3e5efaBill Wendling      if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
13315b6f42f57e730c2d968c313a27fa505a3c3e5efaBill Wendling        InsertPt = L->getHeader()->getFirstInsertionPt();
13326c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman      while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
13337896c9f436a4eda5ec15e882a7505ba482a2fcd0Chris Lattner        InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
133440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      break;
133540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    }
133640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1337667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Check to see if we already expanded this here.
1338667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  std::map<std::pair<const SCEV *, Instruction *>,
1339667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman           AssertingVH<Value> >::iterator I =
1340667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    InsertedExpressions.find(std::make_pair(S, InsertPt));
1341267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (I != InsertedExpressions.end())
1342667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    return I->second;
1343267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
1344267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1345267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1346267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1347667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1348667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Expand the expression into instructions.
134996fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  Value *V = visit(S);
135040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1351667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Remember the expanded value for this SCEV at this location.
1352448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (PostIncLoops.empty())
1353a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1354667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1355455985501381777db03534c925a35e261e356395Dan Gohman  restoreInsertPoint(SaveInsertBB, SaveInsertPt);
135696fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  return V;
135796fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov}
13581d09de3eca23267855e28297fcb40de3632ea47bDan Gohman
13591d826a76f591afea445489b9a5485c345e66bf87Dan Gohmanvoid SCEVExpander::rememberInstruction(Value *I) {
136025fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman  if (!PostIncLoops.empty())
136125fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman    InsertedPostIncValues.insert(I);
136225fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman  else
13631d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    InsertedValues.insert(I);
13641d826a76f591afea445489b9a5485c345e66bf87Dan Gohman
13651d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  // If we just claimed an existing instruction and that instruction had
13663228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick  // been the insert point, adjust the insert point forward so that
13671d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  // subsequently inserted code will be dominated.
13681d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  if (Builder.GetInsertPoint() == I) {
13691d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    BasicBlock::iterator It = cast<Instruction>(I);
13706c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman    do { ++It; } while (isInsertedInstruction(It) ||
13716c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman                        isa<DbgInfoIntrinsic>(It));
13721d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
13731d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  }
13741d826a76f591afea445489b9a5485c345e66bf87Dan Gohman}
13751d826a76f591afea445489b9a5485c345e66bf87Dan Gohman
1376455985501381777db03534c925a35e261e356395Dan Gohmanvoid SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
13773f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // If we acquired more instructions since the old insert point was saved,
1378455985501381777db03534c925a35e261e356395Dan Gohman  // advance past them.
13796c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
1380455985501381777db03534c925a35e261e356395Dan Gohman
1381455985501381777db03534c925a35e261e356395Dan Gohman  Builder.SetInsertPoint(BB, I);
1382455985501381777db03534c925a35e261e356395Dan Gohman}
1383455985501381777db03534c925a35e261e356395Dan Gohman
13841d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// getOrInsertCanonicalInductionVariable - This method returns the
13851d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// canonical induction variable of the specified type for the specified
13861d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// loop (inserting one if there is none).  A canonical induction variable
13871d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// starts at zero and steps by one on each iteration.
13887c58dbd88c36c5d6c411ea6c046ddcff4c5841e9Dan GohmanPHINode *
13891d09de3eca23267855e28297fcb40de3632ea47bDan GohmanSCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1390db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                                    Type *Ty) {
1391b0bc6c361da9009e8414efde317d9bbff755f6c0Duncan Sands  assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1392133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
1393133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman  // Build a SCEV for {0,+,1}<L>.
13943228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick  // Conservatively use FlagAnyWrap for now.
1395deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman  const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
13963228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                   SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1397133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
1398133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman  // Emit code for it.
1399267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1400267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
14017c58dbd88c36c5d6c411ea6c046ddcff4c5841e9Dan Gohman  PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
1402267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (SaveInsertBB)
1403455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1404133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
140540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  return V;
14061d09de3eca23267855e28297fcb40de3632ea47bDan Gohman}
1407