ScalarEvolutionExpander.cpp revision f8d0578e4cbd5922696c92f5068c5513d8e8d60e
136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//                     The LLVM Compiler Infrastructure
436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
54ee451de366474b9c228b4e5fa573795a715216dChris Lattner// This file is distributed under the University of Illinois Open Source
64ee451de366474b9c228b4e5fa573795a715216dChris Lattner// License. See LICENSE.TXT for details.
736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//===----------------------------------------------------------------------===//
936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
1036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman// This file contains the implementation of the scalar evolution expander,
1136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman// which is used to generate the code corresponding to a given scalar evolution
1236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman// expression.
1336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
1436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//===----------------------------------------------------------------------===//
1536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman#include "llvm/Analysis/ScalarEvolutionExpander.h"
17e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling#include "llvm/Analysis/LoopInfo.h"
188d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen#include "llvm/IntrinsicInst.h"
1976f600b205606a055ec35e7d3fd1a99602329d67Owen Anderson#include "llvm/LLVMContext.h"
205be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman#include "llvm/Target/TargetData.h"
214d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman#include "llvm/ADT/STLExtras.h"
2236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begemanusing namespace llvm;
2336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
24267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
25267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// which must be possible with a noop cast, doing what we can to share
26267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// the casts.
27267a385342f2e7388f178b327dd87c5f29afd51bDan GohmanValue *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
28267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
29267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert((Op == Instruction::BitCast ||
30267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::PtrToInt ||
31267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::IntToPtr) &&
32267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot perform non-noop casts!");
33267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
34267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot change sizes!");
35267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
362d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  // Short-circuit unnecessary bitcasts.
37267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (Op == Instruction::BitCast && V->getType() == Ty)
382d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman    return V;
392d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
40f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman  // Short-circuit unnecessary inttoptr<->ptrtoint casts.
41267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
4280dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
43af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman    if (CastInst *CI = dyn_cast<CastInst>(V))
44af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman      if ((CI->getOpcode() == Instruction::PtrToInt ||
45af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman           CI->getOpcode() == Instruction::IntToPtr) &&
46af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getType()) ==
47af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
48af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman        return CI->getOperand(0);
4980dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
5080dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      if ((CE->getOpcode() == Instruction::PtrToInt ||
5180dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman           CE->getOpcode() == Instruction::IntToPtr) &&
5280dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getType()) ==
5380dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
5480dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman        return CE->getOperand(0);
5580dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman  }
56f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman
57ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Constant *C = dyn_cast<Constant>(V))
58baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getCast(Op, C, Ty);
594c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman
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());
85a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(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)) {
102c37e3d5d7cd9576711204dfd0240edefba2df4c7Dan Gohman            // Recreate the cast after the user.
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);
108c37e3d5d7cd9576711204dfd0240edefba2df4c7Dan Gohman            rememberInstruction(NewCI);
10940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman            return NewCI;
1103913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          }
111c37e3d5d7cd9576711204dfd0240edefba2df4c7Dan Gohman          rememberInstruction(CI);
1123913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz          return CI;
113ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner        }
114ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  }
115ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  BasicBlock::iterator IP = I; ++IP;
116ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(I))
117ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    IP = II->getNormalDest()->begin();
118ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  while (isa<PHINode>(IP)) ++IP;
119267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
120a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(CI);
121cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return CI;
122ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner}
123ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner
1247fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// InsertBinop - Insert the specified binary operator, doing a small amount
1257fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// of work to avoid inserting an obviously redundant operation.
126267a385342f2e7388f178b327dd87c5f29afd51bDan GohmanValue *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
127267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 Value *LHS, Value *RHS) {
1280f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  // Fold a binop with constant operands.
1290f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  if (Constant *CLHS = dyn_cast<Constant>(LHS))
1300f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman    if (Constant *CRHS = dyn_cast<Constant>(RHS))
131baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson      return ConstantExpr::get(Opcode, CLHS, CRHS);
1320f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman
1337fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
1347fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  unsigned ScanLimit = 6;
135267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
136267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  // Scanning starts from the last instruction before the insertion point.
137267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator IP = Builder.GetInsertPoint();
138267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (IP != BlockBegin) {
1398a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    --IP;
1408a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    for (; ScanLimit; --IP, --ScanLimit) {
1418d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // Don't count dbg.value against the ScanLimit, to avoid perturbing the
1428d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // generated code.
1438d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      if (isa<DbgInfoIntrinsic>(IP))
1448d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        ScanLimit++;
1455be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
1465be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          IP->getOperand(1) == RHS)
1475be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        return IP;
1488a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz      if (IP == BlockBegin) break;
1498a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    }
1507fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  }
151267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
152087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Save the original insertion point so we can restore it when we're done.
153087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
154087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
155087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
156087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Move the insertion point out of as many loops as we can.
157087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
158087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
159087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
160087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Preheader) break;
161087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
162087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Ok, move up a level.
163087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
164087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
165087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
1668a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz  // If we haven't found this binop, insert it.
167267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
168a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(BO);
169087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
170087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Restore the original insert point.
171087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (SaveInsertBB)
172087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
173087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
174cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return BO;
1757fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner}
1767fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner
1774a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// FactorOutConstant - Test if S is divisible by Factor, using signed
178453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// division. If so, update S with Factor divided out and return true.
1793f46a3abeedba8d517b4182de34c821d752db058Dan Gohman/// S need not be evenly divisible if a reasonable remainder can be
1804a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// computed.
181453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
182453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
183453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// check to see if the divide was folded.
1840bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic bool FactorOutConstant(const SCEV *&S,
1850bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                              const SCEV *&Remainder,
186c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const SCEV *Factor,
187c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              ScalarEvolution &SE,
188c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const TargetData *TD) {
189453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // Everything is divisible by one.
190c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (Factor->isOne())
191c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    return true;
192c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
193c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // x/x == 1.
194c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (S == Factor) {
195c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    S = SE.getIntegerSCEV(1, S->getType());
196453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
197c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
198453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
199453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // For a Constant, check for a multiple of the given factor.
2004a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
201c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // 0/x == 0.
202c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (C->isZero())
203453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return true;
204c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Check for divisibility.
205c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
206c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      ConstantInt *CI =
207c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ConstantInt::get(SE.getContext(),
208c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         C->getValue()->getValue().sdiv(
209c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
210c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If the quotient is zero and the remainder is non-zero, reject
211c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // the value at this scale. It will be considered for subsequent
212c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // smaller scales.
213c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!CI->isZero()) {
214c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Div = SE.getConstant(CI);
215c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        S = Div;
216c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Remainder =
217c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          SE.getAddExpr(Remainder,
218c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                        SE.getConstant(C->getValue()->getValue().srem(
219c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                  FC->getValue()->getValue())));
220c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return true;
221c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
222453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
2234a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  }
224453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
225453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In a Mul, check if there is a constant operand which is a multiple
226453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // of the given factor.
227c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
228c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (TD) {
229c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // With TargetData, the size is known. Check if there is a constant
230c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // operand which is a multiple of the given factor. If so, we can
231c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // factor it.
232c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEVConstant *FC = cast<SCEVConstant>(Factor);
233c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
234c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
235f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
236c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[0] =
237c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            SE.getConstant(C->getValue()->getValue().sdiv(
238c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
239c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
240c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
241c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
242c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    } else {
243c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Without TargetData, check if Factor can be factored out of any of the
244c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Mul's operands. If so, we can just remove it.
245c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
246c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *SOp = M->getOperand(i);
247c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType());
248c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
249c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            Remainder->isZero()) {
250f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
251c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[i] = SOp;
252c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
253c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
254c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
255453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
256c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
257c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
258453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
259453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In an AddRec, check if both start and step are divisible.
260453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2610bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Step = A->getStepRecurrence(SE);
2620bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType());
263c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
2644a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2654a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman    if (!StepRem->isZero())
2664a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2670bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Start = A->getStart();
268c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
269453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return false;
270453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    S = SE.getAddRecExpr(Start, Step, A->getLoop());
271453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
272453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
273453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
274453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  return false;
275453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
276453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
277c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
278c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// is the number of SCEVAddRecExprs present, which are kept at the end of
279c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// the list.
280c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
281c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
282c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                const Type *Ty,
283c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                ScalarEvolution &SE) {
284c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  unsigned NumAddRecs = 0;
285c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
286c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ++NumAddRecs;
287c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Group Ops into non-addrecs and addrecs.
288c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
289c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
290c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Let ScalarEvolution sort and simplify the non-addrecs list.
291c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  const SCEV *Sum = NoAddRecs.empty() ?
292c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                    SE.getIntegerSCEV(0, Ty) :
293c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                    SE.getAddExpr(NoAddRecs);
294c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // If it returned an add, use the operands. Otherwise it simplified
295c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // the sum into a single value, so just use that.
296f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  Ops.clear();
297c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
298f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
299f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  else if (!Sum->isZero())
300f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    Ops.push_back(Sum);
301c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Then append the addrecs.
302c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
303c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
304c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
305c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
306c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
307c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// This helps expose more opportunities for folding parts of the expressions
308c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// into GEP indices.
309c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
310c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
311c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         const Type *Ty,
312c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         ScalarEvolution &SE) {
313c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Find the addrecs.
314c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs;
315c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
316c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
317c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEV *Start = A->getStart();
318c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (Start->isZero()) break;
319c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEV *Zero = SE.getIntegerSCEV(0, Ty);
320c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      AddRecs.push_back(SE.getAddRecExpr(Zero,
321c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                         A->getStepRecurrence(SE),
322c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                         A->getLoop()));
323c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
324c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Zero;
325c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
326c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        e += Add->getNumOperands();
327c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
328c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Start;
329c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
330c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
331c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (!AddRecs.empty()) {
332c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Add the addrecs onto the end of the list.
333c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
334c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Resort the operand list, moving any constants to the front.
335c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    SimplifyAddOperands(Ops, Ty, SE);
336c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
337c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
338c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
3394c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// expandAddToGEP - Expand an addition expression with a pointer type into
3404c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
3414c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// BasicAliasAnalysis and other passes analyze the result. See the rules
3424c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for getelementptr vs. inttoptr in
3434c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// http://llvm.org/docs/LangRef.html#pointeraliasing
3444c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for details.
34513c5e35222afe0895f0c5e68aa9f22f134ea437aDan Gohman///
3463abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman/// Design note: The correctness of using getelementptr here depends on
3474c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
3484c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// they may introduce pointer arithmetic which may not be safely converted
3494c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// into getelementptr.
350453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
351453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Design note: It might seem desirable for this function to be more
352453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-aware. If some of the indices are loop-invariant while others
353453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// aren't, it might seem desirable to emit multiple GEPs, keeping the
354453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of the overall computation outside the loop.
355453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// However, there are a few reasons this is not done here. Hoisting simple
356453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// arithmetic is a low-level optimization that often isn't very
357453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// important until late in the optimization process. In fact, passes
358453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// like InstructionCombining will combine GEPs, even if it means
359453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// pushing loop-invariant computation down into loops, so even if the
360453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEPs were split here, the work would quickly be undone. The
361453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// LoopStrengthReduction pass, which is usually run quite late (and
362453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// after the last InstructionCombining pass), takes care of hoisting
363453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of expressions, after considering what
364453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// can be folded using target addressing modes.
365453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
3660bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan GohmanValue *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
3670bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                                    const SCEV *const *op_end,
3685be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    const PointerType *PTy,
3695be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    const Type *Ty,
3705be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    Value *V) {
3715be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  const Type *ElTy = PTy->getElementType();
3725be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  SmallVector<Value *, 4> GepIndices;
3730bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
3745be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  bool AnyNonZeroIndices = false;
3755be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
376c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Split AddRecs up into parts as either of the parts may be usable
377c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // without the other.
378c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SplitAddRecs(Ops, Ty, SE);
379c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
380eb35699e642f2c021f04154bdb4bd90a1afb3baaBob Wilson  // Descend down the pointer's type and attempt to convert the other
3815be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // operands into GEP indices, at each level. The first index in a GEP
3825be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // indexes into the array implied by the pointer operand; the rest of
3835be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the indices index into the element or field type selected by the
3845be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // preceding index.
3855be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  for (;;) {
386c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If the scale size is not 0, attempt to factor out a scale for
387c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // array indexing.
3880bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> ScaledOps;
389150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman    if (ElTy->isSized()) {
3904f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman      const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
391150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman      if (!ElSize->isZero()) {
392150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        SmallVector<const SCEV *, 8> NewOps;
393150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
394150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          const SCEV *Op = Ops[i];
395150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          const SCEV *Remainder = SE.getIntegerSCEV(0, Ty);
396150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
397150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // Op now has ElSize factored out.
398150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            ScaledOps.push_back(Op);
399150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            if (!Remainder->isZero())
400150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman              NewOps.push_back(Remainder);
401150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            AnyNonZeroIndices = true;
402150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          } else {
403150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // The operand was not divisible, so add it to the list of operands
404150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // we'll scan next iteration.
405150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            NewOps.push_back(Ops[i]);
406150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          }
407150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        }
408150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        // If we made any changes, update Ops.
409150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        if (!ScaledOps.empty()) {
410150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          Ops = NewOps;
411150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          SimplifyAddOperands(Ops, Ty, SE);
4125be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        }
413c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
4145be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
415c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
416c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Record the scaled array index for this level of the type. If
417c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // we didn't find any operands that could be factored, tentatively
418c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // assume that element zero was selected (since the zero offset
419c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // would obviously be folded away).
4205be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    Value *Scaled = ScaledOps.empty() ?
421a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson                    Constant::getNullValue(Ty) :
4225be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                    expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
4235be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    GepIndices.push_back(Scaled);
4245be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4255be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Collect struct field index operands.
426c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
427c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      bool FoundFieldNo = false;
428c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // An empty struct has no fields.
429c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (STy->getNumElements() == 0) break;
430c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (SE.TD) {
431c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // With TargetData, field offsets are known. See if a constant offset
432c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // falls within any of the struct fields.
433c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (Ops.empty()) break;
4345be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
4355be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          if (SE.getTypeSizeInBits(C->getType()) <= 64) {
4365be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            const StructLayout &SL = *SE.TD->getStructLayout(STy);
4375be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            uint64_t FullOffset = C->getValue()->getZExtValue();
4385be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            if (FullOffset < SL.getSizeInBytes()) {
4395be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
4401d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson              GepIndices.push_back(
4411d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                  ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
4425be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              ElTy = STy->getTypeAtIndex(ElIdx);
4435be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              Ops[0] =
4446de29f8d960505421d61c80cdb738e16720b6c0eDan Gohman                SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
4455be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              AnyNonZeroIndices = true;
446c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
4475be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            }
4485be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          }
449c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
4500f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman        // Without TargetData, just check for an offsetof expression of the
451c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // appropriate struct type.
452c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4530f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
4544f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman            const Type *CTy;
4550f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman            Constant *FieldNo;
4564f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman            if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
4570f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman              GepIndices.push_back(FieldNo);
4580f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman              ElTy =
4590f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman                STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
460c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              Ops[i] = SE.getConstant(Ty, 0);
461c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              AnyNonZeroIndices = true;
462c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
463c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              break;
464c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            }
4650f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          }
4665be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
467c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If no struct field offsets were found, tentatively assume that
468c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // field zero was selected (since the zero offset would obviously
469c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // be folded away).
470c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!FoundFieldNo) {
471c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ElTy = STy->getTypeAtIndex(0u);
472c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        GepIndices.push_back(
473c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
474c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
475c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
4765be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
477c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
4785be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      ElTy = ATy->getElementType();
479c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    else
480c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      break;
4815be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
4825be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4833f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // If none of the operands were convertible to proper GEP indices, cast
4845be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the base to i8* and do an ugly getelementptr with that. It's still
4855be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // better than ptrtoint+arithmetic+inttoptr at least.
4865be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (!AnyNonZeroIndices) {
487c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Cast the base to i8*.
4885be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V,
489ac53a0b272452013124bfc70480aea5e41b60f40Duncan Sands       Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
490c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
491c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Expand the operands for a plain byte offset.
49292fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
4935be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4945be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Fold a GEP with constant operands.
4955be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    if (Constant *CLHS = dyn_cast<Constant>(V))
4965be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (Constant *CRHS = dyn_cast<Constant>(Idx))
497baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson        return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
4985be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4995be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
5005be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    unsigned ScanLimit = 6;
501267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
502267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    // Scanning starts from the last instruction before the insertion point.
503267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator IP = Builder.GetInsertPoint();
504267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    if (IP != BlockBegin) {
5055be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      --IP;
5065be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      for (; ScanLimit; --IP, --ScanLimit) {
5078d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        // Don't count dbg.value against the ScanLimit, to avoid perturbing the
5088d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        // generated code.
5098d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        if (isa<DbgInfoIntrinsic>(IP))
5108d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen          ScanLimit++;
5115be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP->getOpcode() == Instruction::GetElementPtr &&
5125be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            IP->getOperand(0) == V && IP->getOperand(1) == Idx)
5135be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          return IP;
5145be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP == BlockBegin) break;
5155be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
5165be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
5175be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
518087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Save the original insertion point so we can restore it when we're done.
519087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
520087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
521087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
522087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Move the insertion point out of as many loops as we can.
523087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
524087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
525087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      BasicBlock *Preheader = L->getLoopPreheader();
526087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!Preheader) break;
527087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
528087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Ok, move up a level.
529087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
530087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
531087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
532c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Emit a GEP.
533c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
534a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(GEP);
535087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
536087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Restore the original insert point.
537087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (SaveInsertBB)
538087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      restoreInsertPoint(SaveInsertBB, SaveInsertPt);
539087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
5405be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    return GEP;
5415be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
5425be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
543087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Save the original insertion point so we can restore it when we're done.
544087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
545087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
546087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
547087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Move the insertion point out of as many loops as we can.
548087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
549087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!L->isLoopInvariant(V)) break;
550087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
551087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    bool AnyIndexNotLoopInvariant = false;
552087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
553087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman         E = GepIndices.end(); I != E; ++I)
554087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!L->isLoopInvariant(*I)) {
555087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        AnyIndexNotLoopInvariant = true;
556087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        break;
557087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      }
558087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (AnyIndexNotLoopInvariant)
559087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      break;
560087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
561087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
562087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Preheader) break;
563087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
564087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Ok, move up a level.
565087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
566087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
567087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
568d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
569d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // because ScalarEvolution may have changed the address arithmetic to
570d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // compute a value which is beyond the end of the allocated object.
571a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Casted = V;
572a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (V->getType() != PTy)
573a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Casted = InsertNoopCastOfTo(Casted, PTy);
574a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *GEP = Builder.CreateGEP(Casted,
575267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 GepIndices.begin(),
576267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 GepIndices.end(),
577267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 "scevgep");
5785be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  Ops.push_back(SE.getUnknown(GEP));
579a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(GEP);
580087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
581087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Restore the original insert point.
582087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (SaveInsertBB)
583087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
584087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
5855be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return expand(SE.getAddExpr(Ops));
5865be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman}
5875be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
588a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// isNonConstantNegative - Return true if the specified scev is negated, but
589a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// not a constant.
590a10756ee657a4d43a48cca5c166919093930ed6bDan Gohmanstatic bool isNonConstantNegative(const SCEV *F) {
591a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
592a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!Mul) return false;
593a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
594a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // If there is a constant factor, it will be first.
595a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
596a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!SC) return false;
597a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
598a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Return true if the value is negative, this matches things like (-42 * V).
599a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return SC->getValue()->getValue().isNegative();
600a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
601a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
602087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
603087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// SCEV expansion. If they are nested, this is the most nested. If they are
604087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// neighboring, pick the later.
605087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanstatic const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
606087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                                        DominatorTree &DT) {
607087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!A) return B;
608087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!B) return A;
609087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (A->contains(B)) return B;
610087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (B->contains(A)) return A;
611087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(A->getHeader(), B->getHeader())) return B;
612087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(B->getHeader(), A->getHeader())) return A;
613087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return A; // Arbitrarily break the tie.
614087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
615087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
616087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// GetRelevantLoop - Get the most relevant loop associated with the given
617087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// expression, according to PickMostRelevantLoop.
618087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanstatic const Loop *GetRelevantLoop(const SCEV *S, LoopInfo &LI,
619087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                                   DominatorTree &DT) {
620087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (isa<SCEVConstant>(S))
621087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return 0;
622087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
623087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
624087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return LI.getLoopFor(I->getParent());
625087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return 0;
626087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
627087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
628087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const Loop *L = 0;
629087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
630087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      L = AR->getLoop();
631087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
632087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman         I != E; ++I)
633087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      L = PickMostRelevantLoop(L, GetRelevantLoop(*I, LI, DT), DT);
634087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return L;
635087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
636087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
637087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return GetRelevantLoop(C->getOperand(), LI, DT);
638087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S))
639087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return PickMostRelevantLoop(GetRelevantLoop(D->getLHS(), LI, DT),
640087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                                GetRelevantLoop(D->getRHS(), LI, DT),
641087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                                DT);
642087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  llvm_unreachable("Unexpected SCEV type!");
643087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
644c4f7ec85ecb760fff2b702c6deb06506b968ba4fDan Gohman
645087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// LoopCompare - Compare loops by PickMostRelevantLoop.
646087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanclass LoopCompare {
647087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  DominatorTree &DT;
648087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanpublic:
649087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
650087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
651087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  bool operator()(std::pair<const Loop *, const SCEV *> LHS,
652087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                  std::pair<const Loop *, const SCEV *> RHS) const {
653087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Compare loops with PickMostRelevantLoop.
654087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (LHS.first != RHS.first)
655087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
656087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
657087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // If one operand is a non-constant negative and the other is not,
658087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // put the non-constant negative on the right so that a sub can
659087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // be used instead of a negate and add.
660087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (isNonConstantNegative(LHS.second)) {
661087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!isNonConstantNegative(RHS.second))
662087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        return false;
663087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (isNonConstantNegative(RHS.second))
664087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return true;
665087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
666087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Otherwise they are equivalent according to this comparison.
667087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return false;
668c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
669087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman};
6705be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
671087bd1e3a12893873761736bf0f905a350e9e708Dan GohmanValue *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
672087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
673e24fa64d52330626553298f56ba5aa702624c282Dan Gohman
674087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the add operands in a loop, along with their associated loops.
675087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal, and
676087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // so that pointer operands are inserted first, which the code below relies on
677087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // to form more involved GEPs.
678087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
679087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
680087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
681087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
682087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                                         *I));
683087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
684087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants and
685087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // pointer operands precede non-pointer operands.
686087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
687087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
688087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to add all the operands. Hoist as much as possible
689087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops, and form meaningful getelementptrs where possible.
690087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  Value *Sum = 0;
691087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
692087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
693087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const Loop *CurLoop = I->first;
694087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const SCEV *Op = I->second;
695087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Sum) {
696087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
697087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expand(Op);
698087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
699087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (const PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
700087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum expression is a pointer. Try to form a getelementptr
701087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // at this level with that as the base.
702087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
703087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      for (; I != E && I->first == CurLoop; ++I)
704087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        NewOps.push_back(I->second);
705087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
706087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (const PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
707087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum is an integer, and there's a pointer at this level.
708f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // Try to form a getelementptr. If the running sum is instructions,
709f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // use a SCEVUnknown to avoid re-analyzing them.
710087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
711f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
712f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman                                               SE.getSCEV(Sum));
713087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      for (++I; I != E && I->first == CurLoop; ++I)
714087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        NewOps.push_back(I->second);
715087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
716087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (isNonConstantNegative(Op)) {
717087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a negate and add, just do a subtract.
718a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
719087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
720087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Sub, Sum, W);
721087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
722a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
723087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple add.
724a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(Op, Ty);
725087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
726087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
727087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Sum)) std::swap(Sum, W);
728087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Add, Sum, W);
729087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
730a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
7312d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
732087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
733087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Sum;
734e24fa64d52330626553298f56ba5aa702624c282Dan Gohman}
7355be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
736890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
737af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
738087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
739087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the mul operands in a loop, along with their associated loops.
740087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal.
741087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
742087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
743087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
744087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
745087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                                         *I));
746087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
747087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants.
748087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
749087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
750087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to mul all the operands. Hoist as much as possible
751087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops.
752087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  Value *Prod = 0;
753087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
754087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
755087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const SCEV *Op = I->second;
756087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Prod) {
757087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
758087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = expand(Op);
759087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
760087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (Op->isAllOnesValue()) {
761087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a multiply by negative one, just do a negate.
762087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
763087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
764087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
765087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else {
766087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple mul.
767087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Value *W = expandCodeFor(Op, Ty);
768087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
769087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
770087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Prod)) std::swap(Prod, W);
771087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertBinop(Instruction::Mul, Prod, W);
772087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
773087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
7742d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
7752d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
776087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Prod;
77736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
77836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
779890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
780af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
7812d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
78292fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *LHS = expandCodeFor(S->getLHS(), Ty);
783890f92b744fb074465bc2b7006ee753a181f62a4Dan Gohman  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
7846177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    const APInt &RHS = SC->getValue()->getValue();
7856177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    if (RHS.isPowerOf2())
7866177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky      return InsertBinop(Instruction::LShr, LHS,
787eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson                         ConstantInt::get(Ty, RHS.logBase2()));
7886177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky  }
7896177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
79092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *RHS = expandCodeFor(S->getRHS(), Ty);
791267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  return InsertBinop(Instruction::UDiv, LHS, RHS);
7926177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky}
7936177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
794453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Move parts of Base into Rest to leave Base with the minimal
795453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// expression that provides a pointer operand suitable for a
796453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEP expansion.
7970bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
798453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                              ScalarEvolution &SE) {
799453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
800453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getStart();
801453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(Rest,
802453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                         SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
803453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                                          A->getStepRecurrence(SE),
804453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                                          A->getLoop()));
805453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
806453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
807453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getOperand(A->getNumOperands()-1);
8080bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
809453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    NewAddOps.back() = Rest;
810453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(NewAddOps);
811453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    ExposePointerBase(Base, Rest, SE);
812453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
813453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
814453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
815a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
816a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// the base addrec, which is the addrec without any non-loop-dominating
817a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// values, and return the PHI.
818a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanPHINode *
819a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanSCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
820a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                        const Loop *L,
821a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                        const Type *ExpandTy,
822a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                        const Type *IntTy) {
823a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Reuse a previously-inserted PHI, if present.
824a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  for (BasicBlock::iterator I = L->getHeader()->begin();
825a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman       PHINode *PN = dyn_cast<PHINode>(I); ++I)
826572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman    if (SE.isSCEVable(PN->getType()) &&
827572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        (SE.getEffectiveSCEVType(PN->getType()) ==
828572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman         SE.getEffectiveSCEVType(Normalized->getType())) &&
829572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        SE.getSCEV(PN) == Normalized)
830572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman      if (BasicBlock *LatchBlock = L->getLoopLatch()) {
831572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman        Instruction *IncV =
83222e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
83322e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman
83422e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        // Determine if this is a well-behaved chain of instructions leading
83522e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        // back to the PHI. It probably will be, if we're scanning an inner
83622e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        // loop already visited by LSR for example, but it wouldn't have
83722e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        // to be.
83822e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        do {
83922e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV)) {
84022e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            IncV = 0;
84122e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            break;
84222e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          }
8439feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman          // If any of the operands don't dominate the insert position, bail.
8449feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman          // Addrec operands are always loop-invariant, so this can only happen
8459feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman          // if there are instructions which haven't been hoisted.
8469feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman          for (User::op_iterator OI = IncV->op_begin()+1,
8479feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman               OE = IncV->op_end(); OI != OE; ++OI)
8489feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman            if (Instruction *OInst = dyn_cast<Instruction>(OI))
8499feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman              if (!SE.DT->dominates(OInst, IVIncInsertPos)) {
8509feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman                IncV = 0;
8519feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman                break;
8529feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman              }
8539feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman          if (!IncV)
8549feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman            break;
8559feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman          // Advance to the next instruction.
85622e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          IncV = dyn_cast<Instruction>(IncV->getOperand(0));
85722e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          if (!IncV)
85822e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            break;
85922e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          if (IncV->mayHaveSideEffects()) {
86022e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            IncV = 0;
86122e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            break;
86222e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          }
86322e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        } while (IncV != PN);
86422e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman
86522e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        if (IncV) {
86622e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          // Ok, the add recurrence looks usable.
86722e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          // Remember this PHI, even in post-inc mode.
86822e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          InsertedValues.insert(PN);
86922e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          // Remember the increment.
87022e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          IncV = cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
87122e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          rememberInstruction(IncV);
87222e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          if (L == IVIncInsertLoop)
87322e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            do {
87422e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              if (SE.DT->dominates(IncV, IVIncInsertPos))
87522e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman                break;
87622e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              // Make sure the increment is where we want it. But don't move it
87722e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              // down past a potential existing post-inc user.
87822e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              IncV->moveBefore(IVIncInsertPos);
87922e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              IVIncInsertPos = IncV;
88022e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman              IncV = cast<Instruction>(IncV->getOperand(0));
88122e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman            } while (IncV != PN);
88222e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman          return PN;
88322e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        }
884572645cf84060c0fc25cb91d38cb9079918b3a88Dan Gohman      }
885a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
886a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Save the original insertion point so we can restore it when we're done.
887a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
888a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
889a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
890a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand code for the start value.
891a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
892a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                L->getHeader()->begin());
893a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
894a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand code for the step value. Insert instructions right before the
895a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // terminator corresponding to the back-edge. Do this before creating the PHI
896a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
897a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // negative, insert a sub instead of an add for the increment (unless it's a
898a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // constant, because subtracts of constants are canonicalized to adds).
899a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
9001df9859c40492511b8aa4321eb76496005d3b75bDuncan Sands  bool isPointer = ExpandTy->isPointerTy();
901a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  bool isNegative = !isPointer && isNonConstantNegative(Step);
902a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (isNegative)
903a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Step = SE.getNegativeSCEV(Step);
904a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
905a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
906a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the PHI.
907a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin());
908a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv");
909a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(PN);
910a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
911a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the step instructions and populate the PHI.
912a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock *Header = L->getHeader();
913a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
914a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman       HPI != HPE; ++HPI) {
915a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *Pred = *HPI;
916a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
917a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // Add a start value.
918a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (!L->contains(Pred)) {
919a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      PN->addIncoming(StartV, Pred);
920a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      continue;
921a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
922a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
923a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // Create a step value and add it to the PHI. If IVIncInsertLoop is
924a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // non-null and equal to the addrec's loop, insert the instructions
925a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // at IVIncInsertPos.
926a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Instruction *InsertPos = L == IVIncInsertLoop ?
927a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IVIncInsertPos : Pred->getTerminator();
928a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Builder.SetInsertPoint(InsertPos->getParent(), InsertPos);
929a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Value *IncV;
930a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
931a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (isPointer) {
932a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
933a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      // If the step isn't constant, don't use an implicitly scaled GEP, because
934a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      // that would require a multiply inside the loop.
935a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      if (!isa<ConstantInt>(StepV))
936a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
937a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                    GEPPtrTy->getAddressSpace());
938a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
939a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
940a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      if (IncV->getType() != PN->getType()) {
941a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
942a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        rememberInstruction(IncV);
943a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      }
944a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
945a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IncV = isNegative ?
946a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        Builder.CreateSub(PN, StepV, "lsr.iv.next") :
947a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        Builder.CreateAdd(PN, StepV, "lsr.iv.next");
948a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      rememberInstruction(IncV);
949a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
950a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PN->addIncoming(IncV, Pred);
951a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
952a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
953a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Restore the original insert point.
954a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (SaveInsertBB)
955455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
956a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
957a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Remember this PHI, even in post-inc mode.
958a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  InsertedValues.insert(PN);
959a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
960a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return PN;
961a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
962a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
963a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanValue *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
964a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Type *STy = S->getType();
965a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Type *IntTy = SE.getEffectiveSCEVType(STy);
966a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Loop *L = S->getLoop();
967a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
968a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Determine a normalized form of this expression, which is the expression
969a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // before any post-inc adjustment is made.
970a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVAddRecExpr *Normalized = S;
971448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (PostIncLoops.count(L)) {
972448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    PostIncLoopSet Loops;
973448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    Loops.insert(L);
974448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    Normalized =
975448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman      cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
976448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman                                                  Loops, SE, *SE.DT));
977a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
978a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
979a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec start.
980a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Start = Normalized->getStart();
981a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *PostLoopOffset = 0;
982a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!Start->properlyDominates(L->getHeader(), SE.DT)) {
983a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopOffset = Start;
984a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Start = SE.getIntegerSCEV(0, Normalized->getType());
985a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Normalized =
986a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start,
987a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                            Normalized->getStepRecurrence(SE),
988a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                            Normalized->getLoop()));
989a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
990a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
991a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec step.
992a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
993a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *PostLoopScale = 0;
994a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!Step->hasComputableLoopEvolution(L) &&
995a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      !Step->dominates(L->getHeader(), SE.DT)) {
996a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopScale = Step;
997a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Step = SE.getIntegerSCEV(1, Normalized->getType());
998a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Normalized =
999a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
1000a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                            Normalized->getLoop()));
1001a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1002a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1003a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand the core addrec. If we need post-loop scaling, force it to
1004a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // expand to an integer type to avoid the need for additional casting.
1005a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Type *ExpandTy = PostLoopScale ? IntTy : STy;
1006a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1007a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
10083f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // Accommodate post-inc mode, if necessary.
1009a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Result;
1010448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (!PostIncLoops.count(L))
1011a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN;
1012a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  else {
1013a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // In PostInc mode, use the post-incremented value.
1014a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *LatchBlock = L->getLoopLatch();
1015a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1016a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN->getIncomingValueForBlock(LatchBlock);
1017a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1018a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1019a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating scale.
1020a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopScale) {
10210a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman    Result = InsertNoopCastOfTo(Result, IntTy);
1022a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = Builder.CreateMul(Result,
1023a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                               expandCodeFor(PostLoopScale, IntTy));
1024a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Result);
1025a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1026a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1027a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating offset.
1028a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopOffset) {
1029a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1030a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const SCEV *const OffsetArray[1] = { PostLoopOffset };
1031a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1032a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
10330a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman      Result = InsertNoopCastOfTo(Result, IntTy);
1034a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = Builder.CreateAdd(Result,
1035a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                 expandCodeFor(PostLoopOffset, IntTy));
1036a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      rememberInstruction(Result);
1037a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
1038a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1039a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1040a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return Result;
1041a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
1042a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1043890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1044a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!CanonicalMode) return expandAddRecExprLiterally(S);
1045a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1046af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
104736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  const Loop *L = S->getLoop();
104836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
10494d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // First check for an existing canonical IV in a suitable type.
10504d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  PHINode *CanonicalIV = 0;
10514d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (PHINode *PN = L->getCanonicalInductionVariable())
10524d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    if (SE.isSCEVable(PN->getType()) &&
10531df9859c40492511b8aa4321eb76496005d3b75bDuncan Sands        SE.getEffectiveSCEVType(PN->getType())->isIntegerTy() &&
10544d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman        SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
10554d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      CanonicalIV = PN;
10564d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
10574d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Rewrite an AddRec in terms of the canonical induction variable, if
10584d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // its type is more narrow.
10594d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (CanonicalIV &&
10604d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(CanonicalIV->getType()) >
10614d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(Ty)) {
1062f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1063f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1064f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman      NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1065f3f1be6f065d1b90afe80ca80c9d6473c10deb5aDan Gohman    Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop()));
1066267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1067267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
10684d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    BasicBlock::iterator NewInsertPt =
10697896c9f436a4eda5ec15e882a7505ba482a2fcd0Chris Lattner      llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
10704d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
10714d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
10724d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman                      NewInsertPt);
1073455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
10744d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    return V;
10754d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  }
10764d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
107736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // {X,+,F} --> X + {0,+,F}
1078cfeb6a450632f2a6cd05302633c8c2b8c90cfdfdDan Gohman  if (!S->getStart()->isZero()) {
1079f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1080246b2564d3bbbafe06ebf6a67745cd24141b5cb4Dan Gohman    NewOps[0] = SE.getIntegerSCEV(0, Ty);
10810bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
1082453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
1083453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1084453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // comments on expandAddToGEP for details.
1085c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *Base = S->getStart();
1086c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *RestArray[1] = { Rest };
1087c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Dig into the expression to find the pointer base for a GEP.
1088c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ExposePointerBase(Base, RestArray[0], SE);
1089c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If we found a pointer, expand the AddRec with a GEP.
1090c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1091c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Make sure the Base isn't something exotic, such as a multiplied
1092c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // or divided pointer value. In those cases, the result type isn't
1093c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // actually a pointer type.
1094c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1095c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Value *StartV = expand(Base);
1096c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1097c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1098453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
1099453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
1100453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
110140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    // Just do a normal add. Pre-expand the operands to suppress folding.
110240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
110340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                SE.getUnknown(expand(Rest))));
110436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
110536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
110636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // {0,+,1} --> Insert a canonical induction variable into the loop!
110717f1972c770dc18f5c7c3c95776b4d62ae9e121dDan Gohman  if (S->isAffine() &&
1108246b2564d3bbbafe06ebf6a67745cd24141b5cb4Dan Gohman      S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
11094d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    // If there's a canonical IV, just use it.
11104d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    if (CanonicalIV) {
11114d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
11124d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             "IVs with types different from the canonical IV should "
11134d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             "already have been handled!");
11144d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      return CanonicalIV;
11154d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    }
11164d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
111736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // Create and insert the PHI node for the induction variable in the
111836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // specified loop.
111936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    BasicBlock *Header = L->getHeader();
1120051a950000e21935165db56695e35bade668193bGabor Greif    PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
1121a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(PN);
112236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1123eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson    Constant *One = ConstantInt::get(Ty, 1);
112483d577490b1473213b6973236110c28e59127956Dan Gohman    for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
112583d577490b1473213b6973236110c28e59127956Dan Gohman         HPI != HPE; ++HPI)
112683d577490b1473213b6973236110c28e59127956Dan Gohman      if (L->contains(*HPI)) {
11273abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // Insert a unit add instruction right before the terminator
11283abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // corresponding to the back-edge.
112983d577490b1473213b6973236110c28e59127956Dan Gohman        Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
113083d577490b1473213b6973236110c28e59127956Dan Gohman                                                     (*HPI)->getTerminator());
1131a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        rememberInstruction(Add);
113283d577490b1473213b6973236110c28e59127956Dan Gohman        PN->addIncoming(Add, *HPI);
113383d577490b1473213b6973236110c28e59127956Dan Gohman      } else {
113483d577490b1473213b6973236110c28e59127956Dan Gohman        PN->addIncoming(Constant::getNullValue(Ty), *HPI);
113583d577490b1473213b6973236110c28e59127956Dan Gohman      }
113636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
113736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
11384d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // {0,+,F} --> {0,+,1} * F
113936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // Get the canonical induction variable I for this loop.
11404d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  Value *I = CanonicalIV ?
11414d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             CanonicalIV :
11424d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman             getOrInsertCanonicalInductionVariable(L, Ty);
114336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1144df14a04b5ccbbe6a46c2ccb93e27b12a36ff163eChris Lattner  // If this is a simple linear addrec, emit it now as a special case.
114540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  if (S->isAffine())    // {0,+,F} --> i*F
114640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return
114740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      expand(SE.getTruncateOrNoop(
114840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        SE.getMulExpr(SE.getUnknown(I),
114940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                      SE.getNoopOrAnyExtend(S->getOperand(1),
115040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                            I->getType())),
115140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        Ty));
115236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
115336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // If this is a chain of recurrences, turn it into a closed form, using the
115436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // folders, then expandCodeFor the closed form.  This allows the folders to
115536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // simplify the expression without having to build a bunch of special code
115636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // into this folder.
11570bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
115836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
11594d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Promote S up to the canonical IV type, if the cast is foldable.
11600bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *NewS = S;
11610bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
11624d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (isa<SCEVAddRecExpr>(Ext))
11634d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    NewS = Ext;
11644d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
11650bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1166e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
116736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
11684d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Truncate the result down to the original type, if needed.
11690bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1170469f3cdc13851914f3a766cbd8f701cf8431cacaDan Gohman  return expand(T);
117136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
117296fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov
1173890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1174af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
117592fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
117692fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1177267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateTrunc(V, Ty, "tmp");
1178a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1179cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
118011f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
118111f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1182890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1183af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
118492fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
118592fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1186267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateZExt(V, Ty, "tmp");
1187a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1188cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
118911f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
119011f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1191890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1192af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
119392fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
119492fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1195267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Value *I = Builder.CreateSExt(V, Ty, "tmp");
1196a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1197cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
119811f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
119911f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1200890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
12010196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
12020196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  const Type *Ty = LHS->getType();
12030196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
12040196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
12050196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
12060196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
12070196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
12080196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
12090196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
121092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1211267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
1212a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1213267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1214a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1215cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
1216c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  }
12170196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
12180196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
12190196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
12200196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
1221c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  return LHS;
1222c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky}
1223c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky
1224890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
12250196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
12260196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  const Type *Ty = LHS->getType();
12270196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
12280196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
12290196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
12300196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
12310196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
12320196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
12330196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
123492fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1235267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
1236a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1237267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1238a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1239cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
12403e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  }
12410196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
12420196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
12430196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
12440196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
12453e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  return LHS;
12463e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky}
12473e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky
12486c7ed6b54949949806797bafdf545fbfecb2cef5Dan GohmanValue *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty,
12496c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman                                   Instruction *I) {
12506c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  BasicBlock::iterator IP = I;
12516c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
12526c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman    ++IP;
12536c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  Builder.SetInsertPoint(IP->getParent(), IP);
12546c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  return expandCodeFor(SH, Ty);
12556c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman}
12566c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman
12570bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan GohmanValue *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
125811f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman  // Expand the code for this SCEV.
12592d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  Value *V = expand(SH);
12605be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (Ty) {
12615be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
12625be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman           "non-trivial casts should be done with the SCEVs directly!");
12635be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V, Ty);
12645be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
12655be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return V;
126611f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
126711f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1268890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::expand(const SCEV *S) {
126940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // Compute an insertion point for this SCEV object. Hoist the instructions
127040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // as far out in the loop nest as possible.
1271267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction *InsertPt = Builder.GetInsertPoint();
1272267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
127340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman       L = L->getParentLoop())
127440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    if (S->isLoopInvariant(L)) {
127540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (!L) break;
1276e059ee832ca36d65a5fb87b0ac5bcdb0490b15cbDan Gohman      if (BasicBlock *Preheader = L->getLoopPreheader())
127740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        InsertPt = Preheader->getTerminator();
127840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    } else {
127940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // If the SCEV is computable at this level, insert it into the header
128040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // after the PHIs (and after any other instructions that we've inserted
128140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // there) so that it is guaranteed to dominate any user inside the loop.
1282448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman      if (L && S->hasComputableLoopEvolution(L) && !PostIncLoops.count(L))
128340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        InsertPt = L->getHeader()->getFirstNonPHI();
12846c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman      while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
12857896c9f436a4eda5ec15e882a7505ba482a2fcd0Chris Lattner        InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
128640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      break;
128740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    }
128840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1289667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Check to see if we already expanded this here.
1290667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  std::map<std::pair<const SCEV *, Instruction *>,
1291667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman           AssertingVH<Value> >::iterator I =
1292667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    InsertedExpressions.find(std::make_pair(S, InsertPt));
1293267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (I != InsertedExpressions.end())
1294667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    return I->second;
1295267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
1296267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1297267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1298267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1299667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1300667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Expand the expression into instructions.
130196fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  Value *V = visit(S);
130240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1303667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Remember the expanded value for this SCEV at this location.
1304448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (PostIncLoops.empty())
1305a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1306667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1307455985501381777db03534c925a35e261e356395Dan Gohman  restoreInsertPoint(SaveInsertBB, SaveInsertPt);
130896fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  return V;
130996fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov}
13101d09de3eca23267855e28297fcb40de3632ea47bDan Gohman
13111d826a76f591afea445489b9a5485c345e66bf87Dan Gohmanvoid SCEVExpander::rememberInstruction(Value *I) {
1312448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (PostIncLoops.empty())
13131d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    InsertedValues.insert(I);
13141d826a76f591afea445489b9a5485c345e66bf87Dan Gohman
13151d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  // If we just claimed an existing instruction and that instruction had
13161d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  // been the insert point, adjust the insert point forward so that
13171d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  // subsequently inserted code will be dominated.
13181d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  if (Builder.GetInsertPoint() == I) {
13191d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    BasicBlock::iterator It = cast<Instruction>(I);
13206c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman    do { ++It; } while (isInsertedInstruction(It) ||
13216c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman                        isa<DbgInfoIntrinsic>(It));
13221d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
13231d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  }
13241d826a76f591afea445489b9a5485c345e66bf87Dan Gohman}
13251d826a76f591afea445489b9a5485c345e66bf87Dan Gohman
1326455985501381777db03534c925a35e261e356395Dan Gohmanvoid SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
13273f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // If we acquired more instructions since the old insert point was saved,
1328455985501381777db03534c925a35e261e356395Dan Gohman  // advance past them.
13296c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
1330455985501381777db03534c925a35e261e356395Dan Gohman
1331455985501381777db03534c925a35e261e356395Dan Gohman  Builder.SetInsertPoint(BB, I);
1332455985501381777db03534c925a35e261e356395Dan Gohman}
1333455985501381777db03534c925a35e261e356395Dan Gohman
13341d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// getOrInsertCanonicalInductionVariable - This method returns the
13351d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// canonical induction variable of the specified type for the specified
13361d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// loop (inserting one if there is none).  A canonical induction variable
13371d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// starts at zero and steps by one on each iteration.
13381d09de3eca23267855e28297fcb40de3632ea47bDan GohmanValue *
13391d09de3eca23267855e28297fcb40de3632ea47bDan GohmanSCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
13401d09de3eca23267855e28297fcb40de3632ea47bDan Gohman                                                    const Type *Ty) {
1341b0bc6c361da9009e8414efde317d9bbff755f6c0Duncan Sands  assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
13420bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
134340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                   SE.getIntegerSCEV(1, Ty), L);
1344267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1345267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
134640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
1347267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (SaveInsertBB)
1348455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
134940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  return V;
13501d09de3eca23267855e28297fcb40de3632ea47bDan Gohman}
1351