ScalarEvolutionExpander.cpp revision 0a799ab15801d4ebf68eeb151d6375a799c87d9a
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"
1876f600b205606a055ec35e7d3fd1a99602329d67Owen Anderson#include "llvm/LLVMContext.h"
195be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman#include "llvm/Target/TargetData.h"
204d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman#include "llvm/ADT/STLExtras.h"
2136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begemanusing namespace llvm;
2236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
23267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
24267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// which must be possible with a noop cast, doing what we can to share
25267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// the casts.
26267a385342f2e7388f178b327dd87c5f29afd51bDan GohmanValue *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
27267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
28267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert((Op == Instruction::BitCast ||
29267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::PtrToInt ||
30267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::IntToPtr) &&
31267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot perform non-noop casts!");
32267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
33267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot change sizes!");
34267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
352d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  // Short-circuit unnecessary bitcasts.
36267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (Op == Instruction::BitCast && V->getType() == Ty)
372d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman    return V;
382d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
39f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman  // Short-circuit unnecessary inttoptr<->ptrtoint casts.
40267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
4180dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
42af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman    if (CastInst *CI = dyn_cast<CastInst>(V))
43af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman      if ((CI->getOpcode() == Instruction::PtrToInt ||
44af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman           CI->getOpcode() == Instruction::IntToPtr) &&
45af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getType()) ==
46af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
47af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman        return CI->getOperand(0);
4880dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
4980dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      if ((CE->getOpcode() == Instruction::PtrToInt ||
5080dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman           CE->getOpcode() == Instruction::IntToPtr) &&
5180dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getType()) ==
5280dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
5380dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman        return CE->getOperand(0);
5480dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman  }
55f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman
56ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Constant *C = dyn_cast<Constant>(V))
57baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getCast(Op, C, Ty);
584c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman
59ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Argument *A = dyn_cast<Argument>(V)) {
60ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    // Check to see if there is already a cast!
61ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
6240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman         UI != E; ++UI)
63ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner      if ((*UI)->getType() == Ty)
643913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz        if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
65267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          if (CI->getOpcode() == Op) {
663913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz            // If the cast isn't the first instruction of the function, move it.
6740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            if (BasicBlock::iterator(CI) !=
683913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz                A->getParent()->getEntryBlock().begin()) {
6940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              // Recreate the cast at the beginning of the entry block.
7040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              // The old cast is left in place in case it is being used
7140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              // as an insert point.
7240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              Instruction *NewCI =
73267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                CastInst::Create(Op, V, Ty, "",
7440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                 A->getParent()->getEntryBlock().begin());
7540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              NewCI->takeName(CI);
7640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              CI->replaceAllUsesWith(NewCI);
7740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              return NewCI;
783913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz            }
793913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz            return CI;
80ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner          }
8140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
82267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Instruction *I = CastInst::Create(Op, V, Ty, V->getName(),
83cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman                                      A->getParent()->getEntryBlock().begin());
84a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(I);
85cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    return I;
86ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  }
873913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz
88ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  Instruction *I = cast<Instruction>(V);
893913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz
90ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  // Check to see if there is already a cast.  If there is, use it.
91ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
92ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner       UI != E; ++UI) {
93ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    if ((*UI)->getType() == Ty)
943913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz      if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
95267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman        if (CI->getOpcode() == Op) {
963913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          BasicBlock::iterator It = I; ++It;
973913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          if (isa<InvokeInst>(I))
983913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz            It = cast<InvokeInst>(I)->getNormalDest()->begin();
993913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          while (isa<PHINode>(It)) ++It;
1003913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          if (It != BasicBlock::iterator(CI)) {
101c37e3d5d7cd9576711204dfd0240edefba2df4c7Dan Gohman            // Recreate the cast after the user.
10240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            // The old cast is left in place in case it is being used
10340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            // as an insert point.
104267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman            Instruction *NewCI = CastInst::Create(Op, V, Ty, "", It);
10540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            NewCI->takeName(CI);
10640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            CI->replaceAllUsesWith(NewCI);
107c37e3d5d7cd9576711204dfd0240edefba2df4c7Dan Gohman            rememberInstruction(NewCI);
10840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            return NewCI;
1093913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          }
110c37e3d5d7cd9576711204dfd0240edefba2df4c7Dan Gohman          rememberInstruction(CI);
1113913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          return CI;
112ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner        }
113ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  }
114ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  BasicBlock::iterator IP = I; ++IP;
115ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(I))
116ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    IP = II->getNormalDest()->begin();
117ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  while (isa<PHINode>(IP)) ++IP;
118267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
119a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(CI);
120cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return CI;
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) {
1405be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
1415be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          IP->getOperand(1) == RHS)
1425be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        return IP;
1438a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz      if (IP == BlockBegin) break;
1448a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    }
1457fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  }
146267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
1478a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz  // If we haven't found this binop, insert it.
148267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
149a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(BO);
150cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return BO;
1517fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner}
1527fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner
1534a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// FactorOutConstant - Test if S is divisible by Factor, using signed
154453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// division. If so, update S with Factor divided out and return true.
1554a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// S need not be evenly divisble if a reasonable remainder can be
1564a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// computed.
157453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
158453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
159453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// check to see if the divide was folded.
1600bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic bool FactorOutConstant(const SCEV *&S,
1610bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                              const SCEV *&Remainder,
162c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const SCEV *Factor,
163c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              ScalarEvolution &SE,
164c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const TargetData *TD) {
165453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // Everything is divisible by one.
166c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (Factor->isOne())
167c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    return true;
168c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
169c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // x/x == 1.
170c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (S == Factor) {
171c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    S = SE.getIntegerSCEV(1, S->getType());
172453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
173c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
174453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
175453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // For a Constant, check for a multiple of the given factor.
1764a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
177c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // 0/x == 0.
178c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (C->isZero())
179453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return true;
180c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Check for divisibility.
181c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
182c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      ConstantInt *CI =
183c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ConstantInt::get(SE.getContext(),
184c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         C->getValue()->getValue().sdiv(
185c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
186c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If the quotient is zero and the remainder is non-zero, reject
187c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // the value at this scale. It will be considered for subsequent
188c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // smaller scales.
189c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!CI->isZero()) {
190c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Div = SE.getConstant(CI);
191c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        S = Div;
192c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Remainder =
193c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          SE.getAddExpr(Remainder,
194c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                        SE.getConstant(C->getValue()->getValue().srem(
195c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                  FC->getValue()->getValue())));
196c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return true;
197c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
198453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
1994a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  }
200453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
201453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In a Mul, check if there is a constant operand which is a multiple
202453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // of the given factor.
203c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
204c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (TD) {
205c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // With TargetData, the size is known. Check if there is a constant
206c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // operand which is a multiple of the given factor. If so, we can
207c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // factor it.
208c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEVConstant *FC = cast<SCEVConstant>(Factor);
209c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
210c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
211c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
212c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
213c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                 MOperands.end());
214c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[0] =
215c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            SE.getConstant(C->getValue()->getValue().sdiv(
216c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
217c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
218c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
219c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
220c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    } else {
221c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Without TargetData, check if Factor can be factored out of any of the
222c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Mul's operands. If so, we can just remove it.
223c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
224c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *SOp = M->getOperand(i);
225c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType());
226c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
227c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            Remainder->isZero()) {
228c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
229c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
230c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                 MOperands.end());
231c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[i] = SOp;
232c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
233c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
234c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
235453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
236c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
237c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
238453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
239453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In an AddRec, check if both start and step are divisible.
240453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2410bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Step = A->getStepRecurrence(SE);
2420bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType());
243c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
2444a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2454a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman    if (!StepRem->isZero())
2464a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2470bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Start = A->getStart();
248c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
249453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return false;
250453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    S = SE.getAddRecExpr(Start, Step, A->getLoop());
251453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
252453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
253453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
254453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  return false;
255453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
256453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
257c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
258c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// is the number of SCEVAddRecExprs present, which are kept at the end of
259c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// the list.
260c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
261c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
262c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                const Type *Ty,
263c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                ScalarEvolution &SE) {
264c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  unsigned NumAddRecs = 0;
265c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
266c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ++NumAddRecs;
267c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Group Ops into non-addrecs and addrecs.
268c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
269c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
270c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Let ScalarEvolution sort and simplify the non-addrecs list.
271c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  const SCEV *Sum = NoAddRecs.empty() ?
272c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                    SE.getIntegerSCEV(0, Ty) :
273c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                    SE.getAddExpr(NoAddRecs);
274c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // If it returned an add, use the operands. Otherwise it simplified
275c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // the sum into a single value, so just use that.
276c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
277c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Ops = Add->getOperands();
278c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  else {
279c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Ops.clear();
280c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!Sum->isZero())
281c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      Ops.push_back(Sum);
282c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
283c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Then append the addrecs.
284c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
285c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
286c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
287c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
288c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
289c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// This helps expose more opportunities for folding parts of the expressions
290c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// into GEP indices.
291c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
292c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
293c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         const Type *Ty,
294c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         ScalarEvolution &SE) {
295c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Find the addrecs.
296c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs;
297c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
298c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
299c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEV *Start = A->getStart();
300c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (Start->isZero()) break;
301c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEV *Zero = SE.getIntegerSCEV(0, Ty);
302c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      AddRecs.push_back(SE.getAddRecExpr(Zero,
303c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                         A->getStepRecurrence(SE),
304c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                         A->getLoop()));
305c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
306c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Zero;
307c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
308c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        e += Add->getNumOperands();
309c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
310c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Start;
311c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
312c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
313c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (!AddRecs.empty()) {
314c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Add the addrecs onto the end of the list.
315c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
316c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Resort the operand list, moving any constants to the front.
317c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    SimplifyAddOperands(Ops, Ty, SE);
318c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
319c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
320c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
3214c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// expandAddToGEP - Expand an addition expression with a pointer type into
3224c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
3234c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// BasicAliasAnalysis and other passes analyze the result. See the rules
3244c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for getelementptr vs. inttoptr in
3254c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// http://llvm.org/docs/LangRef.html#pointeraliasing
3264c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for details.
32713c5e35222afe0895f0c5e68aa9f22f134ea437aDan Gohman///
3283abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman/// Design note: The correctness of using getelementptr here depends on
3294c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
3304c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// they may introduce pointer arithmetic which may not be safely converted
3314c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// into getelementptr.
332453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
333453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Design note: It might seem desirable for this function to be more
334453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-aware. If some of the indices are loop-invariant while others
335453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// aren't, it might seem desirable to emit multiple GEPs, keeping the
336453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of the overall computation outside the loop.
337453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// However, there are a few reasons this is not done here. Hoisting simple
338453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// arithmetic is a low-level optimization that often isn't very
339453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// important until late in the optimization process. In fact, passes
340453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// like InstructionCombining will combine GEPs, even if it means
341453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// pushing loop-invariant computation down into loops, so even if the
342453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEPs were split here, the work would quickly be undone. The
343453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// LoopStrengthReduction pass, which is usually run quite late (and
344453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// after the last InstructionCombining pass), takes care of hoisting
345453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of expressions, after considering what
346453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// can be folded using target addressing modes.
347453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
3480bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan GohmanValue *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
3490bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                                    const SCEV *const *op_end,
3505be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    const PointerType *PTy,
3515be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    const Type *Ty,
3525be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    Value *V) {
3535be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  const Type *ElTy = PTy->getElementType();
3545be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  SmallVector<Value *, 4> GepIndices;
3550bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
3565be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  bool AnyNonZeroIndices = false;
3575be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
358c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Split AddRecs up into parts as either of the parts may be usable
359c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // without the other.
360c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SplitAddRecs(Ops, Ty, SE);
361c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
362eb35699e642f2c021f04154bdb4bd90a1afb3baaBob Wilson  // Descend down the pointer's type and attempt to convert the other
3635be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // operands into GEP indices, at each level. The first index in a GEP
3645be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // indexes into the array implied by the pointer operand; the rest of
3655be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the indices index into the element or field type selected by the
3665be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // preceding index.
3675be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  for (;;) {
368c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If the scale size is not 0, attempt to factor out a scale for
369c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // array indexing.
3700bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> ScaledOps;
371150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman    if (ElTy->isSized()) {
3724f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman      const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
373150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman      if (!ElSize->isZero()) {
374150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        SmallVector<const SCEV *, 8> NewOps;
375150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
376150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          const SCEV *Op = Ops[i];
377150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          const SCEV *Remainder = SE.getIntegerSCEV(0, Ty);
378150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
379150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // Op now has ElSize factored out.
380150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            ScaledOps.push_back(Op);
381150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            if (!Remainder->isZero())
382150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman              NewOps.push_back(Remainder);
383150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            AnyNonZeroIndices = true;
384150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          } else {
385150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // The operand was not divisible, so add it to the list of operands
386150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // we'll scan next iteration.
387150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            NewOps.push_back(Ops[i]);
388150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          }
389150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        }
390150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        // If we made any changes, update Ops.
391150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        if (!ScaledOps.empty()) {
392150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          Ops = NewOps;
393150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          SimplifyAddOperands(Ops, Ty, SE);
3945be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        }
395c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
3965be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
397c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
398c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Record the scaled array index for this level of the type. If
399c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // we didn't find any operands that could be factored, tentatively
400c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // assume that element zero was selected (since the zero offset
401c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // would obviously be folded away).
4025be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    Value *Scaled = ScaledOps.empty() ?
403a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson                    Constant::getNullValue(Ty) :
4045be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                    expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
4055be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    GepIndices.push_back(Scaled);
4065be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4075be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Collect struct field index operands.
408c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
409c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      bool FoundFieldNo = false;
410c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // An empty struct has no fields.
411c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (STy->getNumElements() == 0) break;
412c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (SE.TD) {
413c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // With TargetData, field offsets are known. See if a constant offset
414c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // falls within any of the struct fields.
415c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (Ops.empty()) break;
4165be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
4175be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          if (SE.getTypeSizeInBits(C->getType()) <= 64) {
4185be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            const StructLayout &SL = *SE.TD->getStructLayout(STy);
4195be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            uint64_t FullOffset = C->getValue()->getZExtValue();
4205be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            if (FullOffset < SL.getSizeInBytes()) {
4215be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
4221d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson              GepIndices.push_back(
4231d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                  ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
4245be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              ElTy = STy->getTypeAtIndex(ElIdx);
4255be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              Ops[0] =
4266de29f8d960505421d61c80cdb738e16720b6c0eDan Gohman                SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
4275be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              AnyNonZeroIndices = true;
428c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
4295be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            }
4305be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          }
431c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
4320f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman        // Without TargetData, just check for an offsetof expression of the
433c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // appropriate struct type.
434c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4350f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
4364f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman            const Type *CTy;
4370f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman            Constant *FieldNo;
4384f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman            if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
4390f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman              GepIndices.push_back(FieldNo);
4400f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman              ElTy =
4410f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman                STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
442c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              Ops[i] = SE.getConstant(Ty, 0);
443c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              AnyNonZeroIndices = true;
444c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
445c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              break;
446c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            }
4470f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          }
4485be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
449c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If no struct field offsets were found, tentatively assume that
450c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // field zero was selected (since the zero offset would obviously
451c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // be folded away).
452c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!FoundFieldNo) {
453c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ElTy = STy->getTypeAtIndex(0u);
454c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        GepIndices.push_back(
455c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
456c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
457c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
4585be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
459c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
4605be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      ElTy = ATy->getElementType();
461c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    else
462c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      break;
4635be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
4645be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4655be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // If none of the operands were convertable to proper GEP indices, cast
4665be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the base to i8* and do an ugly getelementptr with that. It's still
4675be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // better than ptrtoint+arithmetic+inttoptr at least.
4685be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (!AnyNonZeroIndices) {
469c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Cast the base to i8*.
4705be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V,
471ac53a0b272452013124bfc70480aea5e41b60f40Duncan Sands       Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
472c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
473c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Expand the operands for a plain byte offset.
47492fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
4755be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4765be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Fold a GEP with constant operands.
4775be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    if (Constant *CLHS = dyn_cast<Constant>(V))
4785be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (Constant *CRHS = dyn_cast<Constant>(Idx))
479baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson        return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
4805be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4815be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
4825be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    unsigned ScanLimit = 6;
483267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
484267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    // Scanning starts from the last instruction before the insertion point.
485267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator IP = Builder.GetInsertPoint();
486267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    if (IP != BlockBegin) {
4875be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      --IP;
4885be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      for (; ScanLimit; --IP, --ScanLimit) {
4895be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP->getOpcode() == Instruction::GetElementPtr &&
4905be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            IP->getOperand(0) == V && IP->getOperand(1) == Idx)
4915be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          return IP;
4925be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP == BlockBegin) break;
4935be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
4945be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
4955be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
496c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Emit a GEP.
497c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
498a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(GEP);
4995be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    return GEP;
5005be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
5015be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
502d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
503d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // because ScalarEvolution may have changed the address arithmetic to
504d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // compute a value which is beyond the end of the allocated object.
505a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Casted = V;
506a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (V->getType() != PTy)
507a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Casted = InsertNoopCastOfTo(Casted, PTy);
508a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *GEP = Builder.CreateGEP(Casted,
509267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 GepIndices.begin(),
510267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 GepIndices.end(),
511267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 "scevgep");
5125be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  Ops.push_back(SE.getUnknown(GEP));
513a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(GEP);
5145be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return expand(SE.getAddExpr(Ops));
5155be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman}
5165be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
517a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// isNonConstantNegative - Return true if the specified scev is negated, but
518a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// not a constant.
519a10756ee657a4d43a48cca5c166919093930ed6bDan Gohmanstatic bool isNonConstantNegative(const SCEV *F) {
520a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
521a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!Mul) return false;
522a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
523a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // If there is a constant factor, it will be first.
524a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
525a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!SC) return false;
526a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
527a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Return true if the value is negative, this matches things like (-42 * V).
528a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return SC->getValue()->getValue().isNegative();
529a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
530a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
531890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
532c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman  int NumOperands = S->getNumOperands();
533af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
534c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman
535c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman  // Find the index of an operand to start with. Choose the operand with
536c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman  // pointer type, if there is one, or the last operand otherwise.
537c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman  int PIdx = 0;
538c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman  for (; PIdx != NumOperands - 1; ++PIdx)
539c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman    if (isa<PointerType>(S->getOperand(PIdx)->getType())) break;
540c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman
541c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman  // Expand code for the operand that we chose.
542c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman  Value *V = expand(S->getOperand(PIdx));
5435be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
544453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
545453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // comments on expandAddToGEP for details.
546c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
547c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman    // Take the operand at PIdx out of the list.
548c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SmallVectorImpl<const SCEV *> &Ops = S->getOperands();
549c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman    SmallVector<const SCEV *, 8> NewOps;
550c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman    NewOps.insert(NewOps.end(), Ops.begin(), Ops.begin() + PIdx);
551c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman    NewOps.insert(NewOps.end(), Ops.begin() + PIdx + 1, Ops.end());
552c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman    // Make a GEP.
553c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman    return expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, V);
554c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
5555be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
556c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman  // Otherwise, we'll expand the rest of the SCEVAddExpr as plain integer
557c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman  // arithmetic.
558af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  V = InsertNoopCastOfTo(V, Ty);
559e24fa64d52330626553298f56ba5aa702624c282Dan Gohman
560e24fa64d52330626553298f56ba5aa702624c282Dan Gohman  // Emit a bunch of add instructions
561c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman  for (int i = NumOperands-1; i >= 0; --i) {
562c70c37794fbff2c615d4f9dc3b6adf9583b855dcDan Gohman    if (i == PIdx) continue;
563a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    const SCEV *Op = S->getOperand(i);
564a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (isNonConstantNegative(Op)) {
565a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
566a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      V = InsertBinop(Instruction::Sub, V, W);
567a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
568a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(Op, Ty);
569a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      V = InsertBinop(Instruction::Add, V, W);
570a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
5712d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
572e24fa64d52330626553298f56ba5aa702624c282Dan Gohman  return V;
573e24fa64d52330626553298f56ba5aa702624c282Dan Gohman}
5745be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
575890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
576af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
57736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  int FirstOp = 0;  // Set if we should emit a subtract.
578890f92b744fb074465bc2b7006ee753a181f62a4Dan Gohman  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
57936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    if (SC->getValue()->isAllOnesValue())
58036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman      FirstOp = 1;
58136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
58236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  int i = S->getNumOperands()-2;
58392fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(i+1), Ty);
58436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
58536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // Emit a bunch of multiply instructions
5862d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  for (; i >= FirstOp; --i) {
58792fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *W = expandCodeFor(S->getOperand(i), Ty);
588267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    V = InsertBinop(Instruction::Mul, V, W);
5892d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
5902d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
59136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // -1 * ...  --->  0 - ...
59236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  if (FirstOp == 1)
593a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson    V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V);
59436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  return V;
59536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
59636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
597890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
598af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
5992d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
60092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *LHS = expandCodeFor(S->getLHS(), Ty);
601890f92b744fb074465bc2b7006ee753a181f62a4Dan Gohman  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
6026177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    const APInt &RHS = SC->getValue()->getValue();
6036177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    if (RHS.isPowerOf2())
6046177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky      return InsertBinop(Instruction::LShr, LHS,
605eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson                         ConstantInt::get(Ty, RHS.logBase2()));
6066177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky  }
6076177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
60892fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *RHS = expandCodeFor(S->getRHS(), Ty);
609267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  return InsertBinop(Instruction::UDiv, LHS, RHS);
6106177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky}
6116177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
612453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Move parts of Base into Rest to leave Base with the minimal
613453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// expression that provides a pointer operand suitable for a
614453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEP expansion.
6150bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
616453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                              ScalarEvolution &SE) {
617453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
618453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getStart();
619453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(Rest,
620453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                         SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
621453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                                          A->getStepRecurrence(SE),
622453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                                          A->getLoop()));
623453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
624453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
625453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getOperand(A->getNumOperands()-1);
6260bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
627453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    NewAddOps.back() = Rest;
628453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(NewAddOps);
629453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    ExposePointerBase(Base, Rest, SE);
630453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
631453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
632453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
633a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
634a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// the base addrec, which is the addrec without any non-loop-dominating
635a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// values, and return the PHI.
636a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanPHINode *
637a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanSCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
638a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                        const Loop *L,
639a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                        const Type *ExpandTy,
640a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                        const Type *IntTy) {
641a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Reuse a previously-inserted PHI, if present.
642a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  for (BasicBlock::iterator I = L->getHeader()->begin();
643a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman       PHINode *PN = dyn_cast<PHINode>(I); ++I)
644572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman    if (SE.isSCEVable(PN->getType()) &&
645572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        (SE.getEffectiveSCEVType(PN->getType()) ==
646572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman         SE.getEffectiveSCEVType(Normalized->getType())) &&
647572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        SE.getSCEV(PN) == Normalized)
648572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman      if (BasicBlock *LatchBlock = L->getLoopLatch()) {
649572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        // Remember this PHI, even in post-inc mode.
650572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        InsertedValues.insert(PN);
651572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        // Remember the increment.
652572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        Instruction *IncV =
653572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman          cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)
654572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman                                  ->stripPointerCasts());
655572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        rememberInstruction(IncV);
656572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        // Make sure the increment is where we want it. But don't move it
657572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        // down past a potential existing post-inc user.
658572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        if (L == IVIncInsertLoop && !SE.DT->dominates(IncV, IVIncInsertPos))
659572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman          IncV->moveBefore(IVIncInsertPos);
660572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        return PN;
661572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman      }
662a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
663a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Save the original insertion point so we can restore it when we're done.
664a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
665a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
666a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
667a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand code for the start value.
668a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
669a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                L->getHeader()->begin());
670a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
671a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand code for the step value. Insert instructions right before the
672a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // terminator corresponding to the back-edge. Do this before creating the PHI
673a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
674a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // negative, insert a sub instead of an add for the increment (unless it's a
675a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // constant, because subtracts of constants are canonicalized to adds).
676a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
677a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  bool isPointer = isa<PointerType>(ExpandTy);
678a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  bool isNegative = !isPointer && isNonConstantNegative(Step);
679a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (isNegative)
680a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Step = SE.getNegativeSCEV(Step);
681a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
682a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
683a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the PHI.
684a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin());
685a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv");
686a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(PN);
687a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
688a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the step instructions and populate the PHI.
689a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock *Header = L->getHeader();
690a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
691a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman       HPI != HPE; ++HPI) {
692a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *Pred = *HPI;
693a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
694a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // Add a start value.
695a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (!L->contains(Pred)) {
696a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      PN->addIncoming(StartV, Pred);
697a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      continue;
698a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
699a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
700a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // Create a step value and add it to the PHI. If IVIncInsertLoop is
701a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // non-null and equal to the addrec's loop, insert the instructions
702a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // at IVIncInsertPos.
703a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Instruction *InsertPos = L == IVIncInsertLoop ?
704a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IVIncInsertPos : Pred->getTerminator();
705a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Builder.SetInsertPoint(InsertPos->getParent(), InsertPos);
706a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Value *IncV;
707a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
708a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (isPointer) {
709a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
710a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      // If the step isn't constant, don't use an implicitly scaled GEP, because
711a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      // that would require a multiply inside the loop.
712a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      if (!isa<ConstantInt>(StepV))
713a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
714a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                    GEPPtrTy->getAddressSpace());
715a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
716a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
717a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      if (IncV->getType() != PN->getType()) {
718a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
719a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        rememberInstruction(IncV);
720a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      }
721a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
722a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IncV = isNegative ?
723a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        Builder.CreateSub(PN, StepV, "lsr.iv.next") :
724a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        Builder.CreateAdd(PN, StepV, "lsr.iv.next");
725a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      rememberInstruction(IncV);
726a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
727a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PN->addIncoming(IncV, Pred);
728a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
729a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
730a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Restore the original insert point.
731a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (SaveInsertBB)
732a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
733a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
734a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Remember this PHI, even in post-inc mode.
735a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  InsertedValues.insert(PN);
736a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
737a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return PN;
738a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
739a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
740a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanValue *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
741a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Type *STy = S->getType();
742a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Type *IntTy = SE.getEffectiveSCEVType(STy);
743a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Loop *L = S->getLoop();
744a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
745a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Determine a normalized form of this expression, which is the expression
746a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // before any post-inc adjustment is made.
747a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVAddRecExpr *Normalized = S;
748a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (L == PostIncLoop) {
749a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    const SCEV *Step = S->getStepRecurrence(SE);
750a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Normalized = cast<SCEVAddRecExpr>(SE.getMinusSCEV(S, Step));
751a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
752a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
753a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec start.
754a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Start = Normalized->getStart();
755a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *PostLoopOffset = 0;
756a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!Start->properlyDominates(L->getHeader(), SE.DT)) {
757a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopOffset = Start;
758a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Start = SE.getIntegerSCEV(0, Normalized->getType());
759a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Normalized =
760a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start,
761a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                            Normalized->getStepRecurrence(SE),
762a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                            Normalized->getLoop()));
763a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
764a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
765a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec step.
766a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
767a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *PostLoopScale = 0;
768a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!Step->hasComputableLoopEvolution(L) &&
769a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      !Step->dominates(L->getHeader(), SE.DT)) {
770a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopScale = Step;
771a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Step = SE.getIntegerSCEV(1, Normalized->getType());
772a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Normalized =
773a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
774a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                            Normalized->getLoop()));
775a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
776a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
777a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand the core addrec. If we need post-loop scaling, force it to
778a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // expand to an integer type to avoid the need for additional casting.
779a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Type *ExpandTy = PostLoopScale ? IntTy : STy;
780a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
781a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
782a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Accomodate post-inc mode, if necessary.
783a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Result;
784a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (L != PostIncLoop)
785a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN;
786a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  else {
787a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // In PostInc mode, use the post-incremented value.
788a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *LatchBlock = L->getLoopLatch();
789a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    assert(LatchBlock && "PostInc mode requires a unique loop latch!");
790a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN->getIncomingValueForBlock(LatchBlock);
791a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
792a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
793a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating scale.
794a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopScale) {
7950a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman    Result = InsertNoopCastOfTo(Result, IntTy);
796a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = Builder.CreateMul(Result,
797a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                               expandCodeFor(PostLoopScale, IntTy));
798a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Result);
799a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
800a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
801a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating offset.
802a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopOffset) {
803a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
804a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const SCEV *const OffsetArray[1] = { PostLoopOffset };
805a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
806a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
8070a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman      Result = InsertNoopCastOfTo(Result, IntTy);
808a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = Builder.CreateAdd(Result,
809a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                 expandCodeFor(PostLoopOffset, IntTy));
810a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      rememberInstruction(Result);
811a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
812a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
813a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
814a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return Result;
815a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
816a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
817890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
818a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!CanonicalMode) return expandAddRecExprLiterally(S);
819a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
820af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
82136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  const Loop *L = S->getLoop();
82236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
8234d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // First check for an existing canonical IV in a suitable type.
8244d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  PHINode *CanonicalIV = 0;
8254d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (PHINode *PN = L->getCanonicalInductionVariable())
8264d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    if (SE.isSCEVable(PN->getType()) &&
8274d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman        isa<IntegerType>(SE.getEffectiveSCEVType(PN->getType())) &&
8284d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman        SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
8294d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      CanonicalIV = PN;
8304d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
8314d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Rewrite an AddRec in terms of the canonical induction variable, if
8324d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // its type is more narrow.
8334d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (CanonicalIV &&
8344d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(CanonicalIV->getType()) >
8354d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(Ty)) {
836f3f1be6f065d1b90afe80ca80c9d6473c10deb5aDan Gohman    const SmallVectorImpl<const SCEV *> &Ops = S->getOperands();
837f3f1be6f065d1b90afe80ca80c9d6473c10deb5aDan Gohman    SmallVector<const SCEV *, 4> NewOps(Ops.size());
838f3f1be6f065d1b90afe80ca80c9d6473c10deb5aDan Gohman    for (unsigned i = 0, e = Ops.size(); i != e; ++i)
839f3f1be6f065d1b90afe80ca80c9d6473c10deb5aDan Gohman      NewOps[i] = SE.getAnyExtendExpr(Ops[i], CanonicalIV->getType());
840f3f1be6f065d1b90afe80ca80c9d6473c10deb5aDan Gohman    Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop()));
841267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
842267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
8434d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    BasicBlock::iterator NewInsertPt =
8447896c9f436a4eda5ec15e882a7505ba482a2fcd0Chris Lattner      llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
8454d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
8464d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
8474d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman                      NewInsertPt);
848267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
8494d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    return V;
8504d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  }
8514d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
85236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // {X,+,F} --> X + {0,+,F}
853cfeb6a450632f2a6cd05302633c8c2b8c90cfdfdDan Gohman  if (!S->getStart()->isZero()) {
8540bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SmallVectorImpl<const SCEV *> &SOperands = S->getOperands();
8550bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 4> NewOps(SOperands.begin(), SOperands.end());
856246b2564d3bbbafe06ebf6a67745cd24141b5cb4Dan Gohman    NewOps[0] = SE.getIntegerSCEV(0, Ty);
8570bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
858453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
859453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
860453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // comments on expandAddToGEP for details.
861c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *Base = S->getStart();
862c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *RestArray[1] = { Rest };
863c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Dig into the expression to find the pointer base for a GEP.
864c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ExposePointerBase(Base, RestArray[0], SE);
865c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If we found a pointer, expand the AddRec with a GEP.
866c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
867c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Make sure the Base isn't something exotic, such as a multiplied
868c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // or divided pointer value. In those cases, the result type isn't
869c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // actually a pointer type.
870c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
871c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Value *StartV = expand(Base);
872c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
873c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
874453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
875453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
876453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
87740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    // Just do a normal add. Pre-expand the operands to suppress folding.
87840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
87940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                SE.getUnknown(expand(Rest))));
88036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
88136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
88236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // {0,+,1} --> Insert a canonical induction variable into the loop!
88317f1972c770dc18f5c7c3c95776b4d62ae9e121dDan Gohman  if (S->isAffine() &&
884246b2564d3bbbafe06ebf6a67745cd24141b5cb4Dan Gohman      S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
8854d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    // If there's a canonical IV, just use it.
8864d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    if (CanonicalIV) {
8874d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
8884d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             "IVs with types different from the canonical IV should "
8894d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             "already have been handled!");
8904d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      return CanonicalIV;
8914d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    }
8924d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
89336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // Create and insert the PHI node for the induction variable in the
89436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // specified loop.
89536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    BasicBlock *Header = L->getHeader();
896051a950000e21935165db56695e35bade668193bGabor Greif    PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
897a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(PN);
89836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
899eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson    Constant *One = ConstantInt::get(Ty, 1);
90083d577490b1473213b6973236110c28e59127956Dan Gohman    for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
90183d577490b1473213b6973236110c28e59127956Dan Gohman         HPI != HPE; ++HPI)
90283d577490b1473213b6973236110c28e59127956Dan Gohman      if (L->contains(*HPI)) {
9033abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // Insert a unit add instruction right before the terminator
9043abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // corresponding to the back-edge.
90583d577490b1473213b6973236110c28e59127956Dan Gohman        Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
90683d577490b1473213b6973236110c28e59127956Dan Gohman                                                     (*HPI)->getTerminator());
907a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        rememberInstruction(Add);
90883d577490b1473213b6973236110c28e59127956Dan Gohman        PN->addIncoming(Add, *HPI);
90983d577490b1473213b6973236110c28e59127956Dan Gohman      } else {
91083d577490b1473213b6973236110c28e59127956Dan Gohman        PN->addIncoming(Constant::getNullValue(Ty), *HPI);
91183d577490b1473213b6973236110c28e59127956Dan Gohman      }
91236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
91336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
9144d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // {0,+,F} --> {0,+,1} * F
91536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // Get the canonical induction variable I for this loop.
9164d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  Value *I = CanonicalIV ?
9174d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             CanonicalIV :
9184d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             getOrInsertCanonicalInductionVariable(L, Ty);
91936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
920df14a04b5ccbbe6a46c2ccb93e27b12a36ff163eChris Lattner  // If this is a simple linear addrec, emit it now as a special case.
92140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  if (S->isAffine())    // {0,+,F} --> i*F
92240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return
92340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      expand(SE.getTruncateOrNoop(
92440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        SE.getMulExpr(SE.getUnknown(I),
92540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                      SE.getNoopOrAnyExtend(S->getOperand(1),
92640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                            I->getType())),
92740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        Ty));
92836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
92936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // If this is a chain of recurrences, turn it into a closed form, using the
93036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // folders, then expandCodeFor the closed form.  This allows the folders to
93136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // simplify the expression without having to build a bunch of special code
93236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // into this folder.
9330bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
93436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
9354d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Promote S up to the canonical IV type, if the cast is foldable.
9360bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *NewS = S;
9370bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
9384d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (isa<SCEVAddRecExpr>(Ext))
9394d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    NewS = Ext;
9404d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
9410bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
942e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
94336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
9444d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Truncate the result down to the original type, if needed.
9450bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
946469f3cdc13851914f3a766cbd8f701cf8431cacaDan Gohman  return expand(T);
94736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
94896fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov
949890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
950af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
95192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
95292fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
953267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateTrunc(V, Ty, "tmp");
954a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
955cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
95611f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
95711f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
958890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
959af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
96092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
96192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
962267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateZExt(V, Ty, "tmp");
963a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
964cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
96511f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
96611f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
967890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
968af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
96992fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
97092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
971267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateSExt(V, Ty, "tmp");
972a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
973cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
97411f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
97511f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
976890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
9770196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
9780196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  const Type *Ty = LHS->getType();
9790196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
9800196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
9810196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
9820196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
9830196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
9840196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
9850196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
98692fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
987267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
988a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
989267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
990a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
991cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
992c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  }
9930196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
9940196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
9950196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
9960196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
997c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  return LHS;
998c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky}
999c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky
1000890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
10010196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
10020196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  const Type *Ty = LHS->getType();
10030196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
10040196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
10050196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
10060196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
10070196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
10080196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
10090196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
101092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1011267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
1012a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1013267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1014a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1015cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
10163e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  }
10170196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
10180196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
10190196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
10200196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
10213e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  return LHS;
10223e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky}
10233e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky
10240bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan GohmanValue *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
102511f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman  // Expand the code for this SCEV.
10262d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  Value *V = expand(SH);
10275be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (Ty) {
10285be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
10295be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman           "non-trivial casts should be done with the SCEVs directly!");
10305be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V, Ty);
10315be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
10325be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return V;
103311f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
103411f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1035890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::expand(const SCEV *S) {
103640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // Compute an insertion point for this SCEV object. Hoist the instructions
103740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // as far out in the loop nest as possible.
1038267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction *InsertPt = Builder.GetInsertPoint();
1039267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
104040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman       L = L->getParentLoop())
104140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    if (S->isLoopInvariant(L)) {
104240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (!L) break;
104340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (BasicBlock *Preheader = L->getLoopPreheader())
104440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        InsertPt = Preheader->getTerminator();
104540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    } else {
104640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // If the SCEV is computable at this level, insert it into the header
104740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // after the PHIs (and after any other instructions that we've inserted
104840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // there) so that it is guaranteed to dominate any user inside the loop.
104940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (L && S->hasComputableLoopEvolution(L))
105040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        InsertPt = L->getHeader()->getFirstNonPHI();
1051267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman      while (isInsertedInstruction(InsertPt))
10527896c9f436a4eda5ec15e882a7505ba482a2fcd0Chris Lattner        InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
105340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      break;
105440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    }
105540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1056667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Check to see if we already expanded this here.
1057667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  std::map<std::pair<const SCEV *, Instruction *>,
1058667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman           AssertingVH<Value> >::iterator I =
1059667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    InsertedExpressions.find(std::make_pair(S, InsertPt));
1060267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (I != InsertedExpressions.end())
1061667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    return I->second;
1062267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
1063267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1064267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1065267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1066667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1067667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Expand the expression into instructions.
106896fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  Value *V = visit(S);
106940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1070667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Remember the expanded value for this SCEV at this location.
1071a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!PostIncLoop)
1072a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1073667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1074267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
107596fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  return V;
107696fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov}
10771d09de3eca23267855e28297fcb40de3632ea47bDan Gohman
10781d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// getOrInsertCanonicalInductionVariable - This method returns the
10791d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// canonical induction variable of the specified type for the specified
10801d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// loop (inserting one if there is none).  A canonical induction variable
10811d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// starts at zero and steps by one on each iteration.
10821d09de3eca23267855e28297fcb40de3632ea47bDan GohmanValue *
10831d09de3eca23267855e28297fcb40de3632ea47bDan GohmanSCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
10841d09de3eca23267855e28297fcb40de3632ea47bDan Gohman                                                    const Type *Ty) {
10851d09de3eca23267855e28297fcb40de3632ea47bDan Gohman  assert(Ty->isInteger() && "Can only insert integer induction variables!");
10860bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
108740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                   SE.getIntegerSCEV(1, Ty), L);
1088267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1089267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
109040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
1091267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (SaveInsertBB)
1092267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
109340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  return V;
10941d09de3eca23267855e28297fcb40de3632ea47bDan Gohman}
1095