ScalarEvolutionExpander.cpp revision c40f17b08774c2dcc5787fd83241e3c64ba82974
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  // FIXME: keep track of the cast instruction.
57ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Constant *C = dyn_cast<Constant>(V))
58baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getCast(Op, C, Ty);
59ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner
60ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Argument *A = dyn_cast<Argument>(V)) {
61ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    // Check to see if there is already a cast!
62ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
6340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman         UI != E; ++UI)
64ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner      if ((*UI)->getType() == Ty)
653913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz        if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
66267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          if (CI->getOpcode() == Op) {
673913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz            // If the cast isn't the first instruction of the function, move it.
6840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            if (BasicBlock::iterator(CI) !=
693913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz                A->getParent()->getEntryBlock().begin()) {
7040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              // Recreate the cast at the beginning of the entry block.
7140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              // The old cast is left in place in case it is being used
7240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              // as an insert point.
7340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              Instruction *NewCI =
74267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                CastInst::Create(Op, V, Ty, "",
7540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                 A->getParent()->getEntryBlock().begin());
7640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              NewCI->takeName(CI);
7740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              CI->replaceAllUsesWith(NewCI);
7840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman              return NewCI;
793913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz            }
803913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz            return CI;
81ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner          }
8240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
83267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Instruction *I = CastInst::Create(Op, V, Ty, V->getName(),
84cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman                                      A->getParent()->getEntryBlock().begin());
85cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    InsertedValues.insert(I);
86cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    return I;
87ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  }
883913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz
89ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  Instruction *I = cast<Instruction>(V);
903913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz
91ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  // Check to see if there is already a cast.  If there is, use it.
92ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
93ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner       UI != E; ++UI) {
94ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    if ((*UI)->getType() == Ty)
953913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz      if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
96267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman        if (CI->getOpcode() == Op) {
973913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          BasicBlock::iterator It = I; ++It;
983913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          if (isa<InvokeInst>(I))
993913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz            It = cast<InvokeInst>(I)->getNormalDest()->begin();
1003913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          while (isa<PHINode>(It)) ++It;
1013913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          if (It != BasicBlock::iterator(CI)) {
10240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            // Recreate the cast at the beginning of the entry block.
10340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            // The old cast is left in place in case it is being used
10440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            // as an insert point.
105267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman            Instruction *NewCI = CastInst::Create(Op, V, Ty, "", It);
10640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            NewCI->takeName(CI);
10740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            CI->replaceAllUsesWith(NewCI);
10840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            return NewCI;
1093913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          }
1103913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          return CI;
111ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner        }
112ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  }
113ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  BasicBlock::iterator IP = I; ++IP;
114ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(I))
115ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    IP = II->getNormalDest()->begin();
116ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  while (isa<PHINode>(IP)) ++IP;
117267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
118cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  InsertedValues.insert(CI);
119cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return CI;
120ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner}
121ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner
1227fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// InsertBinop - Insert the specified binary operator, doing a small amount
1237fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// of work to avoid inserting an obviously redundant operation.
124267a385342f2e7388f178b327dd87c5f29afd51bDan GohmanValue *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
125267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 Value *LHS, Value *RHS) {
1260f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  // Fold a binop with constant operands.
1270f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  if (Constant *CLHS = dyn_cast<Constant>(LHS))
1280f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman    if (Constant *CRHS = dyn_cast<Constant>(RHS))
129baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson      return ConstantExpr::get(Opcode, CLHS, CRHS);
1300f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman
1317fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
1327fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  unsigned ScanLimit = 6;
133267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
134267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  // Scanning starts from the last instruction before the insertion point.
135267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator IP = Builder.GetInsertPoint();
136267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (IP != BlockBegin) {
1378a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    --IP;
1388a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    for (; ScanLimit; --IP, --ScanLimit) {
1395be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
1405be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          IP->getOperand(1) == RHS)
1415be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        return IP;
1428a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz      if (IP == BlockBegin) break;
1438a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    }
1447fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  }
145267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
1468a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz  // If we haven't found this binop, insert it.
147267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
148cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  InsertedValues.insert(BO);
149cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return BO;
1507fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner}
1517fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner
1524a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// FactorOutConstant - Test if S is divisible by Factor, using signed
153453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// division. If so, update S with Factor divided out and return true.
1544a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// S need not be evenly divisble if a reasonable remainder can be
1554a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// computed.
156453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
157453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
158453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// check to see if the divide was folded.
1590bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic bool FactorOutConstant(const SCEV *&S,
1600bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                              const SCEV *&Remainder,
161c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const SCEV *Factor,
162c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              ScalarEvolution &SE,
163c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const TargetData *TD) {
164453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // Everything is divisible by one.
165c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (Factor->isOne())
166c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    return true;
167c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
168c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // x/x == 1.
169c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (S == Factor) {
170c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    S = SE.getIntegerSCEV(1, S->getType());
171453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
172c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
173453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
174453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // For a Constant, check for a multiple of the given factor.
1754a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
176c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // 0/x == 0.
177c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (C->isZero())
178453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return true;
179c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Check for divisibility.
180c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
181c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      ConstantInt *CI =
182c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ConstantInt::get(SE.getContext(),
183c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         C->getValue()->getValue().sdiv(
184c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
185c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If the quotient is zero and the remainder is non-zero, reject
186c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // the value at this scale. It will be considered for subsequent
187c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // smaller scales.
188c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!CI->isZero()) {
189c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Div = SE.getConstant(CI);
190c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        S = Div;
191c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Remainder =
192c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          SE.getAddExpr(Remainder,
193c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                        SE.getConstant(C->getValue()->getValue().srem(
194c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                  FC->getValue()->getValue())));
195c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return true;
196c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
197453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
1984a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  }
199453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
200453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In a Mul, check if there is a constant operand which is a multiple
201453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // of the given factor.
202c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
203c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (TD) {
204c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // With TargetData, the size is known. Check if there is a constant
205c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // operand which is a multiple of the given factor. If so, we can
206c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // factor it.
207c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEVConstant *FC = cast<SCEVConstant>(Factor);
208c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
209c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
210c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
211c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
212c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                 MOperands.end());
213c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[0] =
214c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            SE.getConstant(C->getValue()->getValue().sdiv(
215c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
216c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
217c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
218c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
219c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    } else {
220c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Without TargetData, check if Factor can be factored out of any of the
221c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Mul's operands. If so, we can just remove it.
222c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
223c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *SOp = M->getOperand(i);
224c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType());
225c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
226c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            Remainder->isZero()) {
227c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
228c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
229c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                 MOperands.end());
230c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[i] = SOp;
231c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
232c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
233c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
234453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
235c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
236c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
237453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
238453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In an AddRec, check if both start and step are divisible.
239453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2400bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Step = A->getStepRecurrence(SE);
2410bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType());
242c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
2434a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2444a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman    if (!StepRem->isZero())
2454a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2460bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Start = A->getStart();
247c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
248453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return false;
249453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    S = SE.getAddRecExpr(Start, Step, A->getLoop());
250453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
251453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
252453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
253453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  return false;
254453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
255453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
256c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
257c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// is the number of SCEVAddRecExprs present, which are kept at the end of
258c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// the list.
259c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
260c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
261c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                const Type *Ty,
262c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                ScalarEvolution &SE) {
263c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  unsigned NumAddRecs = 0;
264c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
265c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ++NumAddRecs;
266c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Group Ops into non-addrecs and addrecs.
267c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
268c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
269c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Let ScalarEvolution sort and simplify the non-addrecs list.
270c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  const SCEV *Sum = NoAddRecs.empty() ?
271c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                    SE.getIntegerSCEV(0, Ty) :
272c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                    SE.getAddExpr(NoAddRecs);
273c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // If it returned an add, use the operands. Otherwise it simplified
274c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // the sum into a single value, so just use that.
275c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
276c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Ops = Add->getOperands();
277c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  else {
278c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Ops.clear();
279c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!Sum->isZero())
280c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      Ops.push_back(Sum);
281c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
282c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Then append the addrecs.
283c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
284c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
285c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
286c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
287c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
288c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// This helps expose more opportunities for folding parts of the expressions
289c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// into GEP indices.
290c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
291c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
292c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         const Type *Ty,
293c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         ScalarEvolution &SE) {
294c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Find the addrecs.
295c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs;
296c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
297c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
298c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEV *Start = A->getStart();
299c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (Start->isZero()) break;
300c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEV *Zero = SE.getIntegerSCEV(0, Ty);
301c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      AddRecs.push_back(SE.getAddRecExpr(Zero,
302c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                         A->getStepRecurrence(SE),
303c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                         A->getLoop()));
304c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
305c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Zero;
306c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
307c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        e += Add->getNumOperands();
308c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
309c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Start;
310c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
311c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
312c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (!AddRecs.empty()) {
313c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Add the addrecs onto the end of the list.
314c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
315c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Resort the operand list, moving any constants to the front.
316c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    SimplifyAddOperands(Ops, Ty, SE);
317c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
318c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
319c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
3205be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman/// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
321453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// instead of using ptrtoint+arithmetic+inttoptr. This helps
322c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// BasicAliasAnalysis and other passes analyze the result.
32313c5e35222afe0895f0c5e68aa9f22f134ea437aDan Gohman///
32413c5e35222afe0895f0c5e68aa9f22f134ea437aDan Gohman/// Design note: This depends on ScalarEvolution not recognizing inttoptr
32513c5e35222afe0895f0c5e68aa9f22f134ea437aDan Gohman/// and ptrtoint operators, as they may introduce pointer arithmetic
32613c5e35222afe0895f0c5e68aa9f22f134ea437aDan Gohman/// which may not be safely converted into getelementptr.
327453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
328453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Design note: It might seem desirable for this function to be more
329453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-aware. If some of the indices are loop-invariant while others
330453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// aren't, it might seem desirable to emit multiple GEPs, keeping the
331453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of the overall computation outside the loop.
332453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// However, there are a few reasons this is not done here. Hoisting simple
333453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// arithmetic is a low-level optimization that often isn't very
334453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// important until late in the optimization process. In fact, passes
335453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// like InstructionCombining will combine GEPs, even if it means
336453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// pushing loop-invariant computation down into loops, so even if the
337453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEPs were split here, the work would quickly be undone. The
338453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// LoopStrengthReduction pass, which is usually run quite late (and
339453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// after the last InstructionCombining pass), takes care of hoisting
340453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of expressions, after considering what
341453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// can be folded using target addressing modes.
342453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
3430bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan GohmanValue *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
3440bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                                    const SCEV *const *op_end,
3455be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    const PointerType *PTy,
3465be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    const Type *Ty,
3475be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    Value *V) {
3485be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  const Type *ElTy = PTy->getElementType();
3495be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  SmallVector<Value *, 4> GepIndices;
3500bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
3515be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  bool AnyNonZeroIndices = false;
3525be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
353c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Split AddRecs up into parts as either of the parts may be usable
354c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // without the other.
355c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SplitAddRecs(Ops, Ty, SE);
356c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
3575be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // Decend down the pointer's type and attempt to convert the other
3585be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // operands into GEP indices, at each level. The first index in a GEP
3595be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // indexes into the array implied by the pointer operand; the rest of
3605be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the indices index into the element or field type selected by the
3615be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // preceding index.
3625be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  for (;;) {
363c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *ElSize = SE.getAllocSizeExpr(ElTy);
364c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If the scale size is not 0, attempt to factor out a scale for
365c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // array indexing.
3660bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> ScaledOps;
367c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (ElTy->isSized() && !ElSize->isZero()) {
368c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      SmallVector<const SCEV *, 8> NewOps;
369c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
3700bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman        const SCEV *Op = Ops[i];
371c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Remainder = SE.getIntegerSCEV(0, Ty);
372c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
373c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          // Op now has ElSize factored out.
374c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          ScaledOps.push_back(Op);
375c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          if (!Remainder->isZero())
376c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            NewOps.push_back(Remainder);
377c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          AnyNonZeroIndices = true;
378c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        } else {
379c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          // The operand was not divisible, so add it to the list of operands
380c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          // we'll scan next iteration.
381c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewOps.push_back(Ops[i]);
3825be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        }
3835be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
384c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If we made any changes, update Ops.
385c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!ScaledOps.empty()) {
386c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops = NewOps;
387c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        SimplifyAddOperands(Ops, Ty, SE);
388c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
3895be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
390c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
391c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Record the scaled array index for this level of the type. If
392c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // we didn't find any operands that could be factored, tentatively
393c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // assume that element zero was selected (since the zero offset
394c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // would obviously be folded away).
3955be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    Value *Scaled = ScaledOps.empty() ?
396a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson                    Constant::getNullValue(Ty) :
3975be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                    expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
3985be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    GepIndices.push_back(Scaled);
3995be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4005be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Collect struct field index operands.
401c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
402c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      bool FoundFieldNo = false;
403c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // An empty struct has no fields.
404c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (STy->getNumElements() == 0) break;
405c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (SE.TD) {
406c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // With TargetData, field offsets are known. See if a constant offset
407c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // falls within any of the struct fields.
408c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (Ops.empty()) break;
4095be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
4105be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          if (SE.getTypeSizeInBits(C->getType()) <= 64) {
4115be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            const StructLayout &SL = *SE.TD->getStructLayout(STy);
4125be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            uint64_t FullOffset = C->getValue()->getZExtValue();
4135be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            if (FullOffset < SL.getSizeInBytes()) {
4145be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
4151d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson              GepIndices.push_back(
4161d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                  ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
4175be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              ElTy = STy->getTypeAtIndex(ElIdx);
4185be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              Ops[0] =
4196de29f8d960505421d61c80cdb738e16720b6c0eDan Gohman                SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
4205be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              AnyNonZeroIndices = true;
421c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
4225be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            }
4235be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          }
424c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
425c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // Without TargetData, just check for a SCEVFieldOffsetExpr of the
426c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // appropriate struct type.
427c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        for (unsigned i = 0, e = Ops.size(); i != e; ++i)
428c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          if (const SCEVFieldOffsetExpr *FO =
429c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                dyn_cast<SCEVFieldOffsetExpr>(Ops[i]))
430c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            if (FO->getStructType() == STy) {
431c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              unsigned FieldNo = FO->getFieldNo();
432c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              GepIndices.push_back(
433c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                  ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
434c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                   FieldNo));
435c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              ElTy = STy->getTypeAtIndex(FieldNo);
436c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              Ops[i] = SE.getConstant(Ty, 0);
437c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              AnyNonZeroIndices = true;
438c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
439c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              break;
440c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            }
4415be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
442c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If no struct field offsets were found, tentatively assume that
443c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // field zero was selected (since the zero offset would obviously
444c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // be folded away).
445c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!FoundFieldNo) {
446c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ElTy = STy->getTypeAtIndex(0u);
447c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        GepIndices.push_back(
448c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
449c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
450c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
4515be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
452c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
4535be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      ElTy = ATy->getElementType();
454c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    else
455c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      break;
4565be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
4575be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4585be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // If none of the operands were convertable to proper GEP indices, cast
4595be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the base to i8* and do an ugly getelementptr with that. It's still
4605be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // better than ptrtoint+arithmetic+inttoptr at least.
4615be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (!AnyNonZeroIndices) {
462c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Cast the base to i8*.
4635be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V,
4641d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson       Type::getInt8Ty(Ty->getContext())->getPointerTo(PTy->getAddressSpace()));
465c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
466c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Expand the operands for a plain byte offset.
46792fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
4685be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4695be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Fold a GEP with constant operands.
4705be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    if (Constant *CLHS = dyn_cast<Constant>(V))
4715be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (Constant *CRHS = dyn_cast<Constant>(Idx))
472baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson        return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
4735be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4745be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
4755be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    unsigned ScanLimit = 6;
476267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
477267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    // Scanning starts from the last instruction before the insertion point.
478267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator IP = Builder.GetInsertPoint();
479267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    if (IP != BlockBegin) {
4805be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      --IP;
4815be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      for (; ScanLimit; --IP, --ScanLimit) {
4825be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP->getOpcode() == Instruction::GetElementPtr &&
4835be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            IP->getOperand(0) == V && IP->getOperand(1) == Idx)
4845be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          return IP;
4855be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP == BlockBegin) break;
4865be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
4875be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
4885be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
489c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Emit a GEP.
490c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
4915be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    InsertedValues.insert(GEP);
4925be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    return GEP;
4935be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
4945be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
495d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
496d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // because ScalarEvolution may have changed the address arithmetic to
497d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // compute a value which is beyond the end of the allocated object.
498267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *GEP = Builder.CreateGEP(V,
499267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 GepIndices.begin(),
500267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 GepIndices.end(),
501267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 "scevgep");
5025be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  Ops.push_back(SE.getUnknown(GEP));
5035be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  InsertedValues.insert(GEP);
5045be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return expand(SE.getAddExpr(Ops));
5055be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman}
5065be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
507890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
508af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
509e24fa64d52330626553298f56ba5aa702624c282Dan Gohman  Value *V = expand(S->getOperand(S->getNumOperands()-1));
5105be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
511453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
512453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // comments on expandAddToGEP for details.
513c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
514c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SmallVectorImpl<const SCEV *> &Ops = S->getOperands();
515c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1], PTy, Ty, V);
516c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
5175be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
518af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  V = InsertNoopCastOfTo(V, Ty);
519e24fa64d52330626553298f56ba5aa702624c282Dan Gohman
520e24fa64d52330626553298f56ba5aa702624c282Dan Gohman  // Emit a bunch of add instructions
5212d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
52292fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *W = expandCodeFor(S->getOperand(i), Ty);
523267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    V = InsertBinop(Instruction::Add, V, W);
5242d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
525e24fa64d52330626553298f56ba5aa702624c282Dan Gohman  return V;
526e24fa64d52330626553298f56ba5aa702624c282Dan Gohman}
5275be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
528890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
529af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
53036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  int FirstOp = 0;  // Set if we should emit a subtract.
531890f92b744fb074465bc2b7006ee753a181f62a4Dan Gohman  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
53236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    if (SC->getValue()->isAllOnesValue())
53336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman      FirstOp = 1;
53436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
53536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  int i = S->getNumOperands()-2;
53692fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(i+1), Ty);
53736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
53836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // Emit a bunch of multiply instructions
5392d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  for (; i >= FirstOp; --i) {
54092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *W = expandCodeFor(S->getOperand(i), Ty);
541267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    V = InsertBinop(Instruction::Mul, V, W);
5422d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
5432d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
54436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // -1 * ...  --->  0 - ...
54536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  if (FirstOp == 1)
546a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson    V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V);
54736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  return V;
54836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
54936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
550890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
551af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
5522d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
55392fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *LHS = expandCodeFor(S->getLHS(), Ty);
554890f92b744fb074465bc2b7006ee753a181f62a4Dan Gohman  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
5556177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    const APInt &RHS = SC->getValue()->getValue();
5566177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    if (RHS.isPowerOf2())
5576177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky      return InsertBinop(Instruction::LShr, LHS,
558eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson                         ConstantInt::get(Ty, RHS.logBase2()));
5596177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky  }
5606177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
56192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *RHS = expandCodeFor(S->getRHS(), Ty);
562267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  return InsertBinop(Instruction::UDiv, LHS, RHS);
5636177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky}
5646177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
565453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Move parts of Base into Rest to leave Base with the minimal
566453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// expression that provides a pointer operand suitable for a
567453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEP expansion.
5680bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
569453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                              ScalarEvolution &SE) {
570453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
571453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getStart();
572453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(Rest,
573453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                         SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
574453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                                          A->getStepRecurrence(SE),
575453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                                          A->getLoop()));
576453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
577453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
578453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getOperand(A->getNumOperands()-1);
5790bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
580453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    NewAddOps.back() = Rest;
581453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(NewAddOps);
582453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    ExposePointerBase(Base, Rest, SE);
583453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
584453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
585453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
586890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
587af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
58836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  const Loop *L = S->getLoop();
58936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
5904d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // First check for an existing canonical IV in a suitable type.
5914d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  PHINode *CanonicalIV = 0;
5924d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (PHINode *PN = L->getCanonicalInductionVariable())
5934d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    if (SE.isSCEVable(PN->getType()) &&
5944d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman        isa<IntegerType>(SE.getEffectiveSCEVType(PN->getType())) &&
5954d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman        SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
5964d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      CanonicalIV = PN;
5974d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
5984d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Rewrite an AddRec in terms of the canonical induction variable, if
5994d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // its type is more narrow.
6004d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (CanonicalIV &&
6014d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(CanonicalIV->getType()) >
6024d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(Ty)) {
6035001c21712f2e52fd6254461b2b2edb9a5823d23Dan Gohman    const SCEV *Start = SE.getAnyExtendExpr(S->getStart(),
6045001c21712f2e52fd6254461b2b2edb9a5823d23Dan Gohman                                            CanonicalIV->getType());
6055001c21712f2e52fd6254461b2b2edb9a5823d23Dan Gohman    const SCEV *Step = SE.getAnyExtendExpr(S->getStepRecurrence(SE),
6064d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman                                           CanonicalIV->getType());
6074d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    Value *V = expand(SE.getAddRecExpr(Start, Step, S->getLoop()));
608267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
609267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
6104d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    BasicBlock::iterator NewInsertPt =
6114d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      next(BasicBlock::iterator(cast<Instruction>(V)));
6124d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
6134d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
6144d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman                      NewInsertPt);
615267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
6164d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    return V;
6174d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  }
6184d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
61936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // {X,+,F} --> X + {0,+,F}
620cfeb6a450632f2a6cd05302633c8c2b8c90cfdfdDan Gohman  if (!S->getStart()->isZero()) {
6210bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SmallVectorImpl<const SCEV *> &SOperands = S->getOperands();
6220bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 4> NewOps(SOperands.begin(), SOperands.end());
623246b2564d3bbbafe06ebf6a67745cd24141b5cb4Dan Gohman    NewOps[0] = SE.getIntegerSCEV(0, Ty);
6240bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
625453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
626453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
627453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // comments on expandAddToGEP for details.
628c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *Base = S->getStart();
629c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *RestArray[1] = { Rest };
630c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Dig into the expression to find the pointer base for a GEP.
631c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ExposePointerBase(Base, RestArray[0], SE);
632c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If we found a pointer, expand the AddRec with a GEP.
633c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
634c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Make sure the Base isn't something exotic, such as a multiplied
635c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // or divided pointer value. In those cases, the result type isn't
636c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // actually a pointer type.
637c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
638c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Value *StartV = expand(Base);
639c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
640c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
641453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
642453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
643453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
64440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    // Just do a normal add. Pre-expand the operands to suppress folding.
64540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
64640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                SE.getUnknown(expand(Rest))));
64736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
64836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
64936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // {0,+,1} --> Insert a canonical induction variable into the loop!
65017f1972c770dc18f5c7c3c95776b4d62ae9e121dDan Gohman  if (S->isAffine() &&
651246b2564d3bbbafe06ebf6a67745cd24141b5cb4Dan Gohman      S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
6524d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    // If there's a canonical IV, just use it.
6534d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    if (CanonicalIV) {
6544d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
6554d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             "IVs with types different from the canonical IV should "
6564d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             "already have been handled!");
6574d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      return CanonicalIV;
6584d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    }
6594d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
66036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // Create and insert the PHI node for the induction variable in the
66136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // specified loop.
66236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    BasicBlock *Header = L->getHeader();
663267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
664051a950000e21935165db56695e35bade668193bGabor Greif    PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
665cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    InsertedValues.insert(PN);
666a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson    PN->addIncoming(Constant::getNullValue(Ty), Preheader);
66736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
66836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    pred_iterator HPI = pred_begin(Header);
66936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    assert(HPI != pred_end(Header) && "Loop with zero preds???");
67036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    if (!L->contains(*HPI)) ++HPI;
67136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    assert(HPI != pred_end(Header) && L->contains(*HPI) &&
67236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman           "No backedge in loop?");
67336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
67436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // Insert a unit add instruction right before the terminator corresponding
67536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // to the back-edge.
676eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson    Constant *One = ConstantInt::get(Ty, 1);
6777cbd8a3e92221437048b484d5ef9c0a22d0f8c58Gabor Greif    Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
67836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman                                                 (*HPI)->getTerminator());
679cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    InsertedValues.insert(Add);
68036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
68136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    pred_iterator PI = pred_begin(Header);
682267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    if (*PI == Preheader)
68336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman      ++PI;
68436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    PN->addIncoming(Add, *PI);
68536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    return PN;
68636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
68736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
6884d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // {0,+,F} --> {0,+,1} * F
68936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // Get the canonical induction variable I for this loop.
6904d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  Value *I = CanonicalIV ?
6914d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             CanonicalIV :
6924d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             getOrInsertCanonicalInductionVariable(L, Ty);
69336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
694df14a04b5ccbbe6a46c2ccb93e27b12a36ff163eChris Lattner  // If this is a simple linear addrec, emit it now as a special case.
69540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  if (S->isAffine())    // {0,+,F} --> i*F
69640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return
69740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      expand(SE.getTruncateOrNoop(
69840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        SE.getMulExpr(SE.getUnknown(I),
69940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                      SE.getNoopOrAnyExtend(S->getOperand(1),
70040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                            I->getType())),
70140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        Ty));
70236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
70336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // If this is a chain of recurrences, turn it into a closed form, using the
70436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // folders, then expandCodeFor the closed form.  This allows the folders to
70536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // simplify the expression without having to build a bunch of special code
70636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // into this folder.
7070bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
70836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
7094d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Promote S up to the canonical IV type, if the cast is foldable.
7100bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *NewS = S;
7110bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
7124d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (isa<SCEVAddRecExpr>(Ext))
7134d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    NewS = Ext;
7144d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
7150bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
716e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
71736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
7184d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Truncate the result down to the original type, if needed.
7190bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
720469f3cdc13851914f3a766cbd8f701cf8431cacaDan Gohman  return expand(T);
72136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
72296fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov
723890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
724af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
72592fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
72692fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
727267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateTrunc(V, Ty, "tmp");
728cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  InsertedValues.insert(I);
729cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
73011f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
73111f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
732890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
733af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
73492fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
73592fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
736267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateZExt(V, Ty, "tmp");
737cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  InsertedValues.insert(I);
738cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
73911f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
74011f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
741890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
742af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
74392fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
74492fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
745267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateSExt(V, Ty, "tmp");
746cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  InsertedValues.insert(I);
747cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
74811f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
74911f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
750890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
7510196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
7520196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  const Type *Ty = LHS->getType();
7530196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
7540196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
7550196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
7560196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
7570196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
7580196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
7590196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
76092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
761267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
762cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    InsertedValues.insert(ICmp);
763267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
764cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    InsertedValues.insert(Sel);
765cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
766c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  }
7670196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
7680196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
7690196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
7700196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
771c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  return LHS;
772c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky}
773c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky
774890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
7750196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
7760196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  const Type *Ty = LHS->getType();
7770196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
7780196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
7790196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
7800196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
7810196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
7820196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
7830196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
78492fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
785267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
786cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    InsertedValues.insert(ICmp);
787267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
788cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    InsertedValues.insert(Sel);
789cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
7903e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  }
7910196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
7920196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
7930196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
7940196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
7953e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  return LHS;
7963e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky}
7973e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky
798c40f17b08774c2dcc5787fd83241e3c64ba82974Dan GohmanValue *SCEVExpander::visitFieldOffsetExpr(const SCEVFieldOffsetExpr *S) {
799c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  return ConstantExpr::getOffsetOf(S->getStructType(), S->getFieldNo());
800c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
801c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
802c40f17b08774c2dcc5787fd83241e3c64ba82974Dan GohmanValue *SCEVExpander::visitAllocSizeExpr(const SCEVAllocSizeExpr *S) {
803c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  return ConstantExpr::getSizeOf(S->getAllocType());
804c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
805c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
8060bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan GohmanValue *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
80711f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman  // Expand the code for this SCEV.
8082d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  Value *V = expand(SH);
8095be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (Ty) {
8105be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
8115be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman           "non-trivial casts should be done with the SCEVs directly!");
8125be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V, Ty);
8135be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
8145be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return V;
81511f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
81611f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
817890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::expand(const SCEV *S) {
81840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // Compute an insertion point for this SCEV object. Hoist the instructions
81940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // as far out in the loop nest as possible.
820267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction *InsertPt = Builder.GetInsertPoint();
821267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
82240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman       L = L->getParentLoop())
82340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    if (S->isLoopInvariant(L)) {
82440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (!L) break;
82540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (BasicBlock *Preheader = L->getLoopPreheader())
82640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        InsertPt = Preheader->getTerminator();
82740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    } else {
82840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // If the SCEV is computable at this level, insert it into the header
82940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // after the PHIs (and after any other instructions that we've inserted
83040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // there) so that it is guaranteed to dominate any user inside the loop.
83140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (L && S->hasComputableLoopEvolution(L))
83240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        InsertPt = L->getHeader()->getFirstNonPHI();
833267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman      while (isInsertedInstruction(InsertPt))
834267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman        InsertPt = next(BasicBlock::iterator(InsertPt));
83540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      break;
83640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    }
83740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
838667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Check to see if we already expanded this here.
839667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  std::map<std::pair<const SCEV *, Instruction *>,
840667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman           AssertingVH<Value> >::iterator I =
841667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    InsertedExpressions.find(std::make_pair(S, InsertPt));
842267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (I != InsertedExpressions.end())
843667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    return I->second;
844267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
845267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
846267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
847267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
848667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
849667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Expand the expression into instructions.
85096fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  Value *V = visit(S);
85140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
852667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Remember the expanded value for this SCEV at this location.
853667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  InsertedExpressions[std::make_pair(S, InsertPt)] = V;
854667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
855267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
85696fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  return V;
85796fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov}
8581d09de3eca23267855e28297fcb40de3632ea47bDan Gohman
8591d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// getOrInsertCanonicalInductionVariable - This method returns the
8601d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// canonical induction variable of the specified type for the specified
8611d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// loop (inserting one if there is none).  A canonical induction variable
8621d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// starts at zero and steps by one on each iteration.
8631d09de3eca23267855e28297fcb40de3632ea47bDan GohmanValue *
8641d09de3eca23267855e28297fcb40de3632ea47bDan GohmanSCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
8651d09de3eca23267855e28297fcb40de3632ea47bDan Gohman                                                    const Type *Ty) {
8661d09de3eca23267855e28297fcb40de3632ea47bDan Gohman  assert(Ty->isInteger() && "Can only insert integer induction variables!");
8670bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
86840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                   SE.getIntegerSCEV(1, Ty), L);
869267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
870267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
87140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
872267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (SaveInsertBB)
873267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
87440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  return V;
8751d09de3eca23267855e28297fcb40de3632ea47bDan Gohman}
876