ScalarEvolutionExpander.cpp revision c9ae8cc24c70dda33b68cacf01d2feeeb836f6f2
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"
20c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick#include "llvm/Support/Debug.h"
215be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman#include "llvm/Target/TargetData.h"
22ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick#include "llvm/Target/TargetLowering.h"
234d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman#include "llvm/ADT/STLExtras.h"
24d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
2536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begemanusing namespace llvm;
2636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
2719e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
28485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman/// reusing an existing cast if a suitable one exists, moving an existing
29485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman/// cast if a suitable one exists but isn't in the right place, or
3019e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif/// creating a new one.
31db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
32485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman                                       Instruction::CastOps Op,
33485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman                                       BasicBlock::iterator IP) {
34919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // This function must be called with the builder having a valid insertion
35919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // point. It doesn't need to be the actual IP where the uses of the returned
36919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // cast will be added, but it must dominate such IP.
37919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // We use this precondition to assert that we can produce a cast that will
387481d07a076420e192f95c22e4866c4aee243c80Rafael Espindola  // dominate all its uses. In particular, this is crucial for the case
39919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // where the builder's insertion point *is* the point where we were asked
40919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // to put the cast.
41919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // Since we don't know the the builder's insertion point is actually
42919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // where the uses will be added (only that it dominates it), we are
43919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // not allowed to move it.
44919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  BasicBlock::iterator BIP = Builder.GetInsertPoint();
45919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola
46919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // FIXME: enable once our implementation of dominates is fixed.
47919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  //  assert(BIP == IP || SE.DT->dominates(IP, BIP));
48ef4c80e07baf02dd2a8f08db49c5634a06d3ca1eRafael Espindola
49485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Check to see if there is already a cast!
50485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
51f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif       UI != E; ++UI) {
52f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif    User *U = *UI;
53f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif    if (U->getType() == Ty)
5419e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif      if (CastInst *CI = dyn_cast<CastInst>(U))
55485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman        if (CI->getOpcode() == Op) {
56b84d540bc9d70de00b791d0e0deab410d6ba3ad5Rafael Espindola          // If the cast isn't where we want it, create a new cast at IP.
57b84d540bc9d70de00b791d0e0deab410d6ba3ad5Rafael Espindola          // Likewise, do not reuse a cast at BIP because it must dominate
58b84d540bc9d70de00b791d0e0deab410d6ba3ad5Rafael Espindola          // instructions that might be inserted before BIP.
59919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola          if (BasicBlock::iterator(CI) != IP || BIP == IP) {
60485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // Create a new cast, and leave the old cast in place in case
61485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // it is being used as an insert point. Clear its operand
62485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // so that it doesn't hold anything live.
63485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
64485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            NewCI->takeName(CI);
65485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            CI->replaceAllUsesWith(NewCI);
66485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            CI->setOperand(0, UndefValue::get(V->getType()));
67485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            rememberInstruction(NewCI);
68485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            return NewCI;
69485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman          }
706f5fed253f58645bf45448893a585ffbd9914989Dan Gohman          rememberInstruction(CI);
71485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman          return CI;
72485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman        }
73f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif  }
74485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman
75485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Create a new cast.
76485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
77485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  rememberInstruction(I);
78485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  return I;
79485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman}
80485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman
81267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
82267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// which must be possible with a noop cast, doing what we can to share
83267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// the casts.
84db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
85267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
86267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert((Op == Instruction::BitCast ||
87267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::PtrToInt ||
88267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::IntToPtr) &&
89267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot perform non-noop casts!");
90267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
91267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot change sizes!");
92267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
932d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  // Short-circuit unnecessary bitcasts.
9419154f457696f286b4a597179fa07e3b38ea0310Andrew Trick  if (Op == Instruction::BitCast) {
9519154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    if (V->getType() == Ty)
9619154f457696f286b4a597179fa07e3b38ea0310Andrew Trick      return V;
9719154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    if (CastInst *CI = dyn_cast<CastInst>(V)) {
9819154f457696f286b4a597179fa07e3b38ea0310Andrew Trick      if (CI->getOperand(0)->getType() == Ty)
9919154f457696f286b4a597179fa07e3b38ea0310Andrew Trick        return CI->getOperand(0);
10019154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    }
10119154f457696f286b4a597179fa07e3b38ea0310Andrew Trick  }
102f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman  // Short-circuit unnecessary inttoptr<->ptrtoint casts.
103267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
10480dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
105af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman    if (CastInst *CI = dyn_cast<CastInst>(V))
106af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman      if ((CI->getOpcode() == Instruction::PtrToInt ||
107af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman           CI->getOpcode() == Instruction::IntToPtr) &&
108af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getType()) ==
109af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
110af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman        return CI->getOperand(0);
11180dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
11280dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      if ((CE->getOpcode() == Instruction::PtrToInt ||
11380dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman           CE->getOpcode() == Instruction::IntToPtr) &&
11480dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getType()) ==
11580dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
11680dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman        return CE->getOperand(0);
11780dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman  }
118f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman
119485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Fold a cast of a constant.
120ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Constant *C = dyn_cast<Constant>(V))
121baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getCast(Op, C, Ty);
1224c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman
123485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Cast the argument at the beginning of the entry block, after
124485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // any bitcasts of other arguments.
125ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Argument *A = dyn_cast<Argument>(V)) {
126485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
127485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    while ((isa<BitCastInst>(IP) &&
128485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
129485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            cast<BitCastInst>(IP)->getOperand(0) != A) ||
130a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling           isa<DbgInfoIntrinsic>(IP) ||
131a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling           isa<LandingPadInst>(IP))
132485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman      ++IP;
133485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    return ReuseOrCreateCast(A, Ty, Op, IP);
134ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  }
1353913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz
136485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Cast the instruction immediately after the instruction.
137ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  Instruction *I = cast<Instruction>(V);
138ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  BasicBlock::iterator IP = I; ++IP;
139ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(I))
140ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    IP = II->getNormalDest()->begin();
141ef4c80e07baf02dd2a8f08db49c5634a06d3ca1eRafael Espindola  while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
142a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling    ++IP;
143485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  return ReuseOrCreateCast(I, Ty, Op, IP);
144ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner}
145ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner
1467fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// InsertBinop - Insert the specified binary operator, doing a small amount
1477fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// of work to avoid inserting an obviously redundant operation.
148267a385342f2e7388f178b327dd87c5f29afd51bDan GohmanValue *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
149267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 Value *LHS, Value *RHS) {
1500f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  // Fold a binop with constant operands.
1510f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  if (Constant *CLHS = dyn_cast<Constant>(LHS))
1520f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman    if (Constant *CRHS = dyn_cast<Constant>(RHS))
153baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson      return ConstantExpr::get(Opcode, CLHS, CRHS);
1540f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman
1557fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
1567fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  unsigned ScanLimit = 6;
157267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
158267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  // Scanning starts from the last instruction before the insertion point.
159267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator IP = Builder.GetInsertPoint();
160267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (IP != BlockBegin) {
1618a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    --IP;
1628a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    for (; ScanLimit; --IP, --ScanLimit) {
1638d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // Don't count dbg.value against the ScanLimit, to avoid perturbing the
1648d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // generated code.
1658d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      if (isa<DbgInfoIntrinsic>(IP))
1668d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        ScanLimit++;
1675be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
1685be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          IP->getOperand(1) == RHS)
1695be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        return IP;
1708a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz      if (IP == BlockBegin) break;
1718a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    }
1727fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  }
173267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
174087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Save the original insertion point so we can restore it when we're done.
175087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
176087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
177087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
178087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Move the insertion point out of as many loops as we can.
179087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
180087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
181087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
182087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Preheader) break;
183087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
184087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Ok, move up a level.
185087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
186087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
187087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
1888a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz  // If we haven't found this binop, insert it.
189a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
190df3ad6697bb849e514c0881ca8700ea36678cbdaDevang Patel  BO->setDebugLoc(SaveInsertPt->getDebugLoc());
191a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(BO);
192087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
193087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Restore the original insert point.
194087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (SaveInsertBB)
195087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
196087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
197cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return BO;
1987fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner}
1997fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner
2004a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// FactorOutConstant - Test if S is divisible by Factor, using signed
201453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// division. If so, update S with Factor divided out and return true.
2023f46a3abeedba8d517b4182de34c821d752db058Dan Gohman/// S need not be evenly divisible if a reasonable remainder can be
2034a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// computed.
204453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
205453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
206453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// check to see if the divide was folded.
2070bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic bool FactorOutConstant(const SCEV *&S,
2080bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                              const SCEV *&Remainder,
209c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const SCEV *Factor,
210c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              ScalarEvolution &SE,
211c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const TargetData *TD) {
212453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // Everything is divisible by one.
213c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (Factor->isOne())
214c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    return true;
215c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
216c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // x/x == 1.
217c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (S == Factor) {
218deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    S = SE.getConstant(S->getType(), 1);
219453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
220c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
221453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
222453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // For a Constant, check for a multiple of the given factor.
2234a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
224c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // 0/x == 0.
225c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (C->isZero())
226453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return true;
227c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Check for divisibility.
228c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
229c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      ConstantInt *CI =
230c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ConstantInt::get(SE.getContext(),
231c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         C->getValue()->getValue().sdiv(
232c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
233c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If the quotient is zero and the remainder is non-zero, reject
234c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // the value at this scale. It will be considered for subsequent
235c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // smaller scales.
236c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!CI->isZero()) {
237c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Div = SE.getConstant(CI);
238c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        S = Div;
239c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Remainder =
240c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          SE.getAddExpr(Remainder,
241c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                        SE.getConstant(C->getValue()->getValue().srem(
242c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                  FC->getValue()->getValue())));
243c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return true;
244c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
245453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
2464a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  }
247453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
248453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In a Mul, check if there is a constant operand which is a multiple
249453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // of the given factor.
250c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
251c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (TD) {
252c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // With TargetData, the size is known. Check if there is a constant
253c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // operand which is a multiple of the given factor. If so, we can
254c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // factor it.
255c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEVConstant *FC = cast<SCEVConstant>(Factor);
256c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
257c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
258f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
259c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[0] =
260c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            SE.getConstant(C->getValue()->getValue().sdiv(
261c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
262c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
263c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
264c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
265c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    } else {
266c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Without TargetData, check if Factor can be factored out of any of the
267c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Mul's operands. If so, we can just remove it.
268c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
269c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *SOp = M->getOperand(i);
270deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman        const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
271c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
272c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            Remainder->isZero()) {
273f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
274c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[i] = SOp;
275c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
276c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
277c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
278453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
279c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
280c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
281453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
282453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In an AddRec, check if both start and step are divisible.
283453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2840bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Step = A->getStepRecurrence(SE);
285deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
286c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
2874a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2884a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman    if (!StepRem->isZero())
2894a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2900bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Start = A->getStart();
291c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
292453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return false;
2933228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    // FIXME: can use A->getNoWrapFlags(FlagNW)
2943228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    S = SE.getAddRecExpr(Start, Step, A->getLoop(), SCEV::FlagAnyWrap);
295453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
296453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
297453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
298453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  return false;
299453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
300453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
301c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
302c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// is the number of SCEVAddRecExprs present, which are kept at the end of
303c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// the list.
304c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
305c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
306db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                Type *Ty,
307c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                ScalarEvolution &SE) {
308c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  unsigned NumAddRecs = 0;
309c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
310c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ++NumAddRecs;
311c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Group Ops into non-addrecs and addrecs.
312c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
313c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
314c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Let ScalarEvolution sort and simplify the non-addrecs list.
315c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  const SCEV *Sum = NoAddRecs.empty() ?
316deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman                    SE.getConstant(Ty, 0) :
317c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                    SE.getAddExpr(NoAddRecs);
318c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // If it returned an add, use the operands. Otherwise it simplified
319c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // the sum into a single value, so just use that.
320f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  Ops.clear();
321c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
322403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman    Ops.append(Add->op_begin(), Add->op_end());
323f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  else if (!Sum->isZero())
324f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    Ops.push_back(Sum);
325c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Then append the addrecs.
326403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman  Ops.append(AddRecs.begin(), AddRecs.end());
327c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
328c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
329c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
330c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
331c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// This helps expose more opportunities for folding parts of the expressions
332c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// into GEP indices.
333c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
334c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
335db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                         Type *Ty,
336c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         ScalarEvolution &SE) {
337c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Find the addrecs.
338c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs;
339c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
340c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
341c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEV *Start = A->getStart();
342c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (Start->isZero()) break;
343deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman      const SCEV *Zero = SE.getConstant(Ty, 0);
344c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      AddRecs.push_back(SE.getAddRecExpr(Zero,
345c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                         A->getStepRecurrence(SE),
3463228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                         A->getLoop(),
3473228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                         // FIXME: A->getNoWrapFlags(FlagNW)
3483228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                         SCEV::FlagAnyWrap));
349c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
350c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Zero;
351403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman        Ops.append(Add->op_begin(), Add->op_end());
352c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        e += Add->getNumOperands();
353c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
354c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Start;
355c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
356c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
357c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (!AddRecs.empty()) {
358c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Add the addrecs onto the end of the list.
359403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman    Ops.append(AddRecs.begin(), AddRecs.end());
360c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Resort the operand list, moving any constants to the front.
361c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    SimplifyAddOperands(Ops, Ty, SE);
362c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
363c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
364c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
3654c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// expandAddToGEP - Expand an addition expression with a pointer type into
3664c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
3674c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// BasicAliasAnalysis and other passes analyze the result. See the rules
3684c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for getelementptr vs. inttoptr in
3694c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// http://llvm.org/docs/LangRef.html#pointeraliasing
3704c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for details.
37113c5e35222afe0895f0c5e68aa9f22f134ea437aDan Gohman///
3723abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman/// Design note: The correctness of using getelementptr here depends on
3734c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
3744c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// they may introduce pointer arithmetic which may not be safely converted
3754c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// into getelementptr.
376453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
377453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Design note: It might seem desirable for this function to be more
378453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-aware. If some of the indices are loop-invariant while others
379453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// aren't, it might seem desirable to emit multiple GEPs, keeping the
380453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of the overall computation outside the loop.
381453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// However, there are a few reasons this is not done here. Hoisting simple
382453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// arithmetic is a low-level optimization that often isn't very
383453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// important until late in the optimization process. In fact, passes
384453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// like InstructionCombining will combine GEPs, even if it means
385453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// pushing loop-invariant computation down into loops, so even if the
386453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEPs were split here, the work would quickly be undone. The
387453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// LoopStrengthReduction pass, which is usually run quite late (and
388453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// after the last InstructionCombining pass), takes care of hoisting
389453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of expressions, after considering what
390453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// can be folded using target addressing modes.
391453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
3920bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan GohmanValue *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
3930bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                                    const SCEV *const *op_end,
394db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                    PointerType *PTy,
395db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                    Type *Ty,
3965be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    Value *V) {
397db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *ElTy = PTy->getElementType();
3985be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  SmallVector<Value *, 4> GepIndices;
3990bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
4005be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  bool AnyNonZeroIndices = false;
4015be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
402c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Split AddRecs up into parts as either of the parts may be usable
403c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // without the other.
404c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SplitAddRecs(Ops, Ty, SE);
405c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
406eb35699e642f2c021f04154bdb4bd90a1afb3baaBob Wilson  // Descend down the pointer's type and attempt to convert the other
4075be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // operands into GEP indices, at each level. The first index in a GEP
4085be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // indexes into the array implied by the pointer operand; the rest of
4095be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the indices index into the element or field type selected by the
4105be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // preceding index.
4115be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  for (;;) {
412c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If the scale size is not 0, attempt to factor out a scale for
413c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // array indexing.
4140bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> ScaledOps;
415150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman    if (ElTy->isSized()) {
4164f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman      const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
417150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman      if (!ElSize->isZero()) {
418150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        SmallVector<const SCEV *, 8> NewOps;
419150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
420150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          const SCEV *Op = Ops[i];
421deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman          const SCEV *Remainder = SE.getConstant(Ty, 0);
422150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
423150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // Op now has ElSize factored out.
424150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            ScaledOps.push_back(Op);
425150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            if (!Remainder->isZero())
426150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman              NewOps.push_back(Remainder);
427150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            AnyNonZeroIndices = true;
428150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          } else {
429150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // The operand was not divisible, so add it to the list of operands
430150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // we'll scan next iteration.
431150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            NewOps.push_back(Ops[i]);
432150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          }
433150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        }
434150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        // If we made any changes, update Ops.
435150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        if (!ScaledOps.empty()) {
436150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          Ops = NewOps;
437150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          SimplifyAddOperands(Ops, Ty, SE);
4385be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        }
439c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
4405be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
441c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
442c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Record the scaled array index for this level of the type. If
443c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // we didn't find any operands that could be factored, tentatively
444c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // assume that element zero was selected (since the zero offset
445c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // would obviously be folded away).
4465be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    Value *Scaled = ScaledOps.empty() ?
447a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson                    Constant::getNullValue(Ty) :
4485be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                    expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
4495be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    GepIndices.push_back(Scaled);
4505be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4515be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Collect struct field index operands.
452db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    while (StructType *STy = dyn_cast<StructType>(ElTy)) {
453c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      bool FoundFieldNo = false;
454c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // An empty struct has no fields.
455c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (STy->getNumElements() == 0) break;
456c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (SE.TD) {
457c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // With TargetData, field offsets are known. See if a constant offset
458c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // falls within any of the struct fields.
459c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (Ops.empty()) break;
4605be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
4615be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          if (SE.getTypeSizeInBits(C->getType()) <= 64) {
4625be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            const StructLayout &SL = *SE.TD->getStructLayout(STy);
4635be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            uint64_t FullOffset = C->getValue()->getZExtValue();
4645be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            if (FullOffset < SL.getSizeInBytes()) {
4655be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
4661d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson              GepIndices.push_back(
4671d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                  ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
4685be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              ElTy = STy->getTypeAtIndex(ElIdx);
4695be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              Ops[0] =
4706de29f8d960505421d61c80cdb738e16720b6c0eDan Gohman                SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
4715be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              AnyNonZeroIndices = true;
472c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
4735be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            }
4745be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          }
475c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
4760f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman        // Without TargetData, just check for an offsetof expression of the
477c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // appropriate struct type.
478c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4790f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
480db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner            Type *CTy;
4810f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman            Constant *FieldNo;
4824f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman            if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
4830f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman              GepIndices.push_back(FieldNo);
4840f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman              ElTy =
4850f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman                STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
486c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              Ops[i] = SE.getConstant(Ty, 0);
487c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              AnyNonZeroIndices = true;
488c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
489c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              break;
490c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            }
4910f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          }
4925be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
493c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If no struct field offsets were found, tentatively assume that
494c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // field zero was selected (since the zero offset would obviously
495c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // be folded away).
496c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!FoundFieldNo) {
497c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ElTy = STy->getTypeAtIndex(0u);
498c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        GepIndices.push_back(
499c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
500c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
501c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
5025be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
503db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
5045be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      ElTy = ATy->getElementType();
505c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    else
506c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      break;
5075be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
5085be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
5093f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // If none of the operands were convertible to proper GEP indices, cast
5105be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the base to i8* and do an ugly getelementptr with that. It's still
5115be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // better than ptrtoint+arithmetic+inttoptr at least.
5125be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (!AnyNonZeroIndices) {
513c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Cast the base to i8*.
5145be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V,
515ac53a0b272452013124bfc70480aea5e41b60f40Duncan Sands       Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
516c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
517705b48d960dff1a96ac40d0cf932eb465b9a550aRafael Espindola    assert(!isa<Instruction>(V) ||
518c9ae8cc24c70dda33b68cacf01d2feeeb836f6f2Rafael Espindola           SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
5194b04578d65e38cdb5077de2498889e4a174ccdfdRafael Espindola
520c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Expand the operands for a plain byte offset.
52192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
5225be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
5235be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Fold a GEP with constant operands.
5245be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    if (Constant *CLHS = dyn_cast<Constant>(V))
5255be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (Constant *CRHS = dyn_cast<Constant>(Idx))
526dab3d29605a5c83db41b28176273ef55961120c1Jay Foad        return ConstantExpr::getGetElementPtr(CLHS, CRHS);
5275be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
5285be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
5295be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    unsigned ScanLimit = 6;
530267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
531267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    // Scanning starts from the last instruction before the insertion point.
532267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator IP = Builder.GetInsertPoint();
533267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    if (IP != BlockBegin) {
5345be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      --IP;
5355be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      for (; ScanLimit; --IP, --ScanLimit) {
5368d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        // Don't count dbg.value against the ScanLimit, to avoid perturbing the
5378d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        // generated code.
5388d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        if (isa<DbgInfoIntrinsic>(IP))
5398d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen          ScanLimit++;
5405be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP->getOpcode() == Instruction::GetElementPtr &&
5415be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            IP->getOperand(0) == V && IP->getOperand(1) == Idx)
5425be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          return IP;
5435be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP == BlockBegin) break;
5445be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
5455be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
5465be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
547087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Save the original insertion point so we can restore it when we're done.
548087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
549087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
550087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
551087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Move the insertion point out of as many loops as we can.
552087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
553087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
554087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      BasicBlock *Preheader = L->getLoopPreheader();
555087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!Preheader) break;
556087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
557087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Ok, move up a level.
558087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
559087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
560087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
561c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Emit a GEP.
562c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
563a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(GEP);
564087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
565087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Restore the original insert point.
566087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (SaveInsertBB)
567087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      restoreInsertPoint(SaveInsertBB, SaveInsertPt);
568087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
5695be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    return GEP;
5705be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
5715be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
572087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Save the original insertion point so we can restore it when we're done.
573087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
574087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
575087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
576087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Move the insertion point out of as many loops as we can.
577087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
578087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!L->isLoopInvariant(V)) break;
579087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
580087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    bool AnyIndexNotLoopInvariant = false;
581087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
582087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman         E = GepIndices.end(); I != E; ++I)
583087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!L->isLoopInvariant(*I)) {
584087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        AnyIndexNotLoopInvariant = true;
585087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        break;
586087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      }
587087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (AnyIndexNotLoopInvariant)
588087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      break;
589087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
590087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
591087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Preheader) break;
592087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
593087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Ok, move up a level.
594087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
595087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
596087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
597d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
598d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // because ScalarEvolution may have changed the address arithmetic to
599d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // compute a value which is beyond the end of the allocated object.
600a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Casted = V;
601a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (V->getType() != PTy)
602a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Casted = InsertNoopCastOfTo(Casted, PTy);
603a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *GEP = Builder.CreateGEP(Casted,
6040a2a60ace9b79164b71794ce7ff981171c61e442Jay Foad                                 GepIndices,
605267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 "scevgep");
6065be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  Ops.push_back(SE.getUnknown(GEP));
607a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(GEP);
608087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
609087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Restore the original insert point.
610087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (SaveInsertBB)
611087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
612087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
6135be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return expand(SE.getAddExpr(Ops));
6145be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman}
6155be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
616087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
617087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// SCEV expansion. If they are nested, this is the most nested. If they are
618087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// neighboring, pick the later.
619087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanstatic const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
620087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                                        DominatorTree &DT) {
621087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!A) return B;
622087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!B) return A;
623087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (A->contains(B)) return B;
624087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (B->contains(A)) return A;
625087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(A->getHeader(), B->getHeader())) return B;
626087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(B->getHeader(), A->getHeader())) return A;
627087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return A; // Arbitrarily break the tie.
628087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
629087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
6309c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman/// getRelevantLoop - Get the most relevant loop associated with the given
631087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// expression, according to PickMostRelevantLoop.
6329c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohmanconst Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
6339c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  // Test whether we've already computed the most relevant loop for this SCEV.
6349c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
6359c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
6369c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (!Pair.second)
6379c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return Pair.first->second;
6389c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman
639087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (isa<SCEVConstant>(S))
6409c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    // A constant has no relevant loops.
641087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return 0;
642087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
643087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
6449c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman      return Pair.first->second = SE.LI->getLoopFor(I->getParent());
6459c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    // A non-instruction has no relevant loops.
646087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return 0;
647087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
648087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
649087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const Loop *L = 0;
650087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
651087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      L = AR->getLoop();
652087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
653087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman         I != E; ++I)
6549c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman      L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
6559c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[N] = L;
6569c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  }
6579c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
6589c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    const Loop *Result = getRelevantLoop(C->getOperand());
6599c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[C] = Result;
6609c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  }
6619c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
6629c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    const Loop *Result =
6639c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman      PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
6649c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman                           getRelevantLoop(D->getRHS()),
6659c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman                           *SE.DT);
6669c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[D] = Result;
667087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
668087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  llvm_unreachable("Unexpected SCEV type!");
669087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
670c4f7ec85ecb760fff2b702c6deb06506b968ba4fDan Gohman
671b35798347ea87b8b6d36155b211016a7769f01abDan Gohmannamespace {
672b35798347ea87b8b6d36155b211016a7769f01abDan Gohman
673087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// LoopCompare - Compare loops by PickMostRelevantLoop.
674087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanclass LoopCompare {
675087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  DominatorTree &DT;
676087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanpublic:
677087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
678087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
679087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  bool operator()(std::pair<const Loop *, const SCEV *> LHS,
680087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                  std::pair<const Loop *, const SCEV *> RHS) const {
681bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman    // Keep pointer operands sorted at the end.
682bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman    if (LHS.second->getType()->isPointerTy() !=
683bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        RHS.second->getType()->isPointerTy())
684bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      return LHS.second->getType()->isPointerTy();
685bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman
686087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Compare loops with PickMostRelevantLoop.
687087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (LHS.first != RHS.first)
688087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
689087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
690087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // If one operand is a non-constant negative and the other is not,
691087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // put the non-constant negative on the right so that a sub can
692087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // be used instead of a negate and add.
693f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    if (LHS.second->isNonConstantNegative()) {
694f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick      if (!RHS.second->isNonConstantNegative())
695087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        return false;
696f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    } else if (RHS.second->isNonConstantNegative())
697087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return true;
698087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
699087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Otherwise they are equivalent according to this comparison.
700087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return false;
701c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
702087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman};
7035be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
704b35798347ea87b8b6d36155b211016a7769f01abDan Gohman}
705b35798347ea87b8b6d36155b211016a7769f01abDan Gohman
706087bd1e3a12893873761736bf0f905a350e9e708Dan GohmanValue *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
707db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
708e24fa64d52330626553298f56ba5aa702624c282Dan Gohman
709087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the add operands in a loop, along with their associated loops.
710087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal, and
711087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // so that pointer operands are inserted first, which the code below relies on
712087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // to form more involved GEPs.
713087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
714087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
715087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
7169c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
717087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
718087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants and
719087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // pointer operands precede non-pointer operands.
720087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
721087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
722087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to add all the operands. Hoist as much as possible
723087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops, and form meaningful getelementptrs where possible.
724087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  Value *Sum = 0;
725087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
726087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
727087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const Loop *CurLoop = I->first;
728087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const SCEV *Op = I->second;
729087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Sum) {
730087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
731087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expand(Op);
732087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
733db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
734087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum expression is a pointer. Try to form a getelementptr
735087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // at this level with that as the base.
736087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
737bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      for (; I != E && I->first == CurLoop; ++I) {
738bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        // If the operand is SCEVUnknown and not instructions, peek through
739bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        // it, to enable more of it to be folded into the GEP.
740bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        const SCEV *X = I->second;
741bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
742bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman          if (!isa<Instruction>(U->getValue()))
743bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman            X = SE.getSCEV(U->getValue());
744bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        NewOps.push_back(X);
745bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      }
746087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
747db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
748087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum is an integer, and there's a pointer at this level.
749f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // Try to form a getelementptr. If the running sum is instructions,
750f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // use a SCEVUnknown to avoid re-analyzing them.
751087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
752f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
753f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman                                               SE.getSCEV(Sum));
754087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      for (++I; I != E && I->first == CurLoop; ++I)
755087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        NewOps.push_back(I->second);
756087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
757f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    } else if (Op->isNonConstantNegative()) {
758087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a negate and add, just do a subtract.
759a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
760087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
761087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Sub, Sum, W);
762087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
763a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
764087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple add.
765a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(Op, Ty);
766087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
767087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
768087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Sum)) std::swap(Sum, W);
769087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Add, Sum, W);
770087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
771a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
7722d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
773087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
774087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Sum;
775e24fa64d52330626553298f56ba5aa702624c282Dan Gohman}
7765be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
777890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
778db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
779087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
780087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the mul operands in a loop, along with their associated loops.
781087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal.
782087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
783087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
784087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
7859c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
786087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
787087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants.
788087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
789087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
790087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to mul all the operands. Hoist as much as possible
791087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops.
792087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  Value *Prod = 0;
793087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
794087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
795087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const SCEV *Op = I->second;
796087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Prod) {
797087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
798087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = expand(Op);
799087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
800087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (Op->isAllOnesValue()) {
801087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a multiply by negative one, just do a negate.
802087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
803087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
804087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
805087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else {
806087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple mul.
807087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Value *W = expandCodeFor(Op, Ty);
808087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
809087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
810087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Prod)) std::swap(Prod, W);
811087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertBinop(Instruction::Mul, Prod, W);
812087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
813087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
8142d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
8152d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
816087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Prod;
81736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
81836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
819890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
820db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
8212d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
82292fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *LHS = expandCodeFor(S->getLHS(), Ty);
823890f92b744fb074465bc2b7006ee753a181f62a4Dan Gohman  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
8246177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    const APInt &RHS = SC->getValue()->getValue();
8256177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    if (RHS.isPowerOf2())
8266177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky      return InsertBinop(Instruction::LShr, LHS,
827eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson                         ConstantInt::get(Ty, RHS.logBase2()));
8286177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky  }
8296177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
83092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *RHS = expandCodeFor(S->getRHS(), Ty);
831267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  return InsertBinop(Instruction::UDiv, LHS, RHS);
8326177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky}
8336177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
834453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Move parts of Base into Rest to leave Base with the minimal
835453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// expression that provides a pointer operand suitable for a
836453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEP expansion.
8370bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
838453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                              ScalarEvolution &SE) {
839453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
840453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getStart();
841453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(Rest,
842deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman                         SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
843453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                                          A->getStepRecurrence(SE),
8443228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                          A->getLoop(),
8453228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                          // FIXME: A->getNoWrapFlags(FlagNW)
8463228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                          SCEV::FlagAnyWrap));
847453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
848453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
849453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getOperand(A->getNumOperands()-1);
8500bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
851453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    NewAddOps.back() = Rest;
852453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(NewAddOps);
853453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    ExposePointerBase(Base, Rest, SE);
854453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
855453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
856453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
857c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// Determine if this is a well-behaved chain of instructions leading back to
858c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// the PHI. If so, it may be reused by expanded expressions.
859c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trickbool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
860c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick                                         const Loop *L) {
861c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
862c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
863c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
864c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // If any of the operands don't dominate the insert position, bail.
865c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Addrec operands are always loop-invariant, so this can only happen
866c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // if there are instructions which haven't been hoisted.
867c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (L == IVIncInsertLoop) {
868c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    for (User::op_iterator OI = IncV->op_begin()+1,
869c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick           OE = IncV->op_end(); OI != OE; ++OI)
870c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (Instruction *OInst = dyn_cast<Instruction>(OI))
871c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        if (!SE.DT->dominates(OInst, IVIncInsertPos))
872c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          return false;
873c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
874c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Advance to the next instruction.
875c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  IncV = dyn_cast<Instruction>(IncV->getOperand(0));
876c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (!IncV)
877c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
878c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
879c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV->mayHaveSideEffects())
880c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
881c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
882c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV != PN)
883c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return true;
884c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
885c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  return isNormalAddRecExprPHI(PN, IncV, L);
886c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick}
887c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
888b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// getIVIncOperand returns an induction variable increment's induction
889b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// variable operand.
890b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick///
891b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// If allowScale is set, any type of GEP is allowed as long as the nonIV
892b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// operands dominate InsertPos.
893b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick///
894b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// If allowScale is not set, ensure that a GEP increment conforms to one of the
895b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// simple patterns generated by getAddRecExprPHILiterally and
896b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
897b5c26ef9da16052597d59a412eaae32098aa1be0Andrew TrickInstruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
898b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                           Instruction *InsertPos,
899b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                           bool allowScale) {
900b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  if (IncV == InsertPos)
901b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    return NULL;
90264925c55c65f9345a69fb67db07aa62cfb723577Andrew Trick
903c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  switch (IncV->getOpcode()) {
904b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  default:
905b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    return NULL;
906c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Check for a simple Add/Sub or GEP of a loop invariant step.
907c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  case Instruction::Add:
908b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  case Instruction::Sub: {
909b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
910c9ae8cc24c70dda33b68cacf01d2feeeb836f6f2Rafael Espindola    if (!OInst || SE.DT->dominates(OInst, InsertPos))
911b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return dyn_cast<Instruction>(IncV->getOperand(0));
912b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    return NULL;
913b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  }
914c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  case Instruction::BitCast:
915b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    return dyn_cast<Instruction>(IncV->getOperand(0));
916b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  case Instruction::GetElementPtr:
917c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
918c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick         I != E; ++I) {
919c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (isa<Constant>(*I))
920c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        continue;
921b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
922c9ae8cc24c70dda33b68cacf01d2feeeb836f6f2Rafael Espindola        if (!SE.DT->dominates(OInst, InsertPos))
923b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          return NULL;
924b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      }
925b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      if (allowScale) {
926b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick        // allow any kind of GEP as long as it can be hoisted.
927b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick        continue;
928b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      }
929b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // This must be a pointer addition of constants (pretty), which is already
930b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // handled, or some number of address-size elements (ugly). Ugly geps
931b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // have 2 operands. i1* is used by the expander to represent an
932b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // address-size element.
933c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (IncV->getNumOperands() != 2)
934b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick        return NULL;
935365c9f1ff55bef134c6b9707f7df44d680ddabeaAndrew Trick      unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
936c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
937c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
938b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick        return NULL;
939c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      break;
940c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    }
941b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    return dyn_cast<Instruction>(IncV->getOperand(0));
942c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
943b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick}
944b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
945b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
946b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// it available to other uses in this loop. Recursively hoist any operands,
947b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// until we reach a value that dominates InsertPos.
948b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trickbool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
949c9ae8cc24c70dda33b68cacf01d2feeeb836f6f2Rafael Espindola  if (SE.DT->dominates(IncV, InsertPos))
950b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return true;
951b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
952b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  // InsertPos must itself dominate IncV so that IncV's new position satisfies
953b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  // its existing users.
954b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  if (!SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
955c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
956b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
957b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  // Check that the chain of IV operands leading back to Phi can be hoisted.
958b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  SmallVector<Instruction*, 4> IVIncs;
959b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  for(;;) {
960b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
961b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    if (!Oper)
962b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return false;
963b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    // IncV is safe to hoist.
964b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    IVIncs.push_back(IncV);
965b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    IncV = Oper;
966c9ae8cc24c70dda33b68cacf01d2feeeb836f6f2Rafael Espindola    if (SE.DT->dominates(IncV, InsertPos))
967b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      break;
968b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  }
969b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
970b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick         E = IVIncs.rend(); I != E; ++I) {
971b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    (*I)->moveBefore(InsertPos);
972b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  }
973b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  return true;
974b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick}
975b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
976b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// Determine if this cyclic phi is in a form that would have been generated by
977b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// LSR. We don't care if the phi was actually expanded in this pass, as long
978b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// as it is in a low-cost form, for example, no implied multiplication. This
979b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// should match any patterns generated by getAddRecExprPHILiterally and
980b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// expandAddtoGEP.
981b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trickbool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
982b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                           const Loop *L) {
983b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  for(Instruction *IVOper = IncV;
984b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
985b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                /*allowScale=*/false));) {
986b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    if (IVOper == PN)
987b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return true;
988c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
989b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  return false;
990c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick}
991c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
992553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
993553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
994553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// need to materialize IV increments elsewhere to handle difficult situations.
995553fe05f236f46fe27b7fcfa822b06367d50183eAndrew TrickValue *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
996553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                 Type *ExpandTy, Type *IntTy,
997553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                 bool useSubtract) {
998553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  Value *IncV;
999553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
1000553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  if (ExpandTy->isPointerTy()) {
1001553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
1002553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // If the step isn't constant, don't use an implicitly scaled GEP, because
1003553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // that would require a multiply inside the loop.
1004553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    if (!isa<ConstantInt>(StepV))
1005553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
1006553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                  GEPPtrTy->getAddressSpace());
1007553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
1008553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
1009553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    if (IncV->getType() != PN->getType()) {
1010553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      IncV = Builder.CreateBitCast(IncV, PN->getType());
1011553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      rememberInstruction(IncV);
1012553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    }
1013553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  } else {
1014553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    IncV = useSubtract ?
1015553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1016553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1017553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    rememberInstruction(IncV);
1018553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  }
1019553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  return IncV;
1020553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick}
1021553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick
1022a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1023a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// the base addrec, which is the addrec without any non-loop-dominating
1024a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// values, and return the PHI.
1025a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanPHINode *
1026a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanSCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1027a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                        const Loop *L,
1028db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                        Type *ExpandTy,
1029db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                        Type *IntTy) {
103093a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer  assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1031d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
1032a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Reuse a previously-inserted PHI, if present.
1033c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  BasicBlock *LatchBlock = L->getLoopLatch();
1034c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (LatchBlock) {
1035c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    for (BasicBlock::iterator I = L->getHeader()->begin();
1036c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick         PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1037c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (!SE.isSCEVable(PN->getType()) ||
1038c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          (SE.getEffectiveSCEVType(PN->getType()) !=
1039c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick           SE.getEffectiveSCEVType(Normalized->getType())) ||
1040c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          SE.getSCEV(PN) != Normalized)
1041c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        continue;
1042c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
1043c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      Instruction *IncV =
1044c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1045c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
1046c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (LSRMode) {
1047365c9f1ff55bef134c6b9707f7df44d680ddabeaAndrew Trick        if (!isExpandedAddRecExprPHI(PN, IncV, L))
1048c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          continue;
1049b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick        if (L == IVIncInsertLoop && !hoistIVInc(IncV, IVIncInsertPos))
1050b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          continue;
1051c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      }
1052c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      else {
1053c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        if (!isNormalAddRecExprPHI(PN, IncV, L))
1054c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          continue;
1055b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick        if (L == IVIncInsertLoop)
1056b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          do {
1057b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick            if (SE.DT->dominates(IncV, IVIncInsertPos))
1058b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick              break;
1059b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick            // Make sure the increment is where we want it. But don't move it
1060b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick            // down past a potential existing post-inc user.
1061b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick            IncV->moveBefore(IVIncInsertPos);
1062b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick            IVIncInsertPos = IncV;
1063b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick            IncV = cast<Instruction>(IncV->getOperand(0));
1064b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          } while (IncV != PN);
1065c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      }
1066c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Ok, the add recurrence looks usable.
1067c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Remember this PHI, even in post-inc mode.
1068c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      InsertedValues.insert(PN);
1069c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Remember the increment.
1070c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      rememberInstruction(IncV);
1071c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      return PN;
1072c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    }
1073c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
1074a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1075a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Save the original insertion point so we can restore it when we're done.
1076a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1077a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1078a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1079ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // Another AddRec may need to be recursively expanded below. For example, if
1080ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // this AddRec is quadratic, the StepV may itself be an AddRec in this
1081ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // loop. Remove this loop from the PostIncLoops set before expanding such
1082ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // AddRecs. Otherwise, we cannot find a valid position for the step
1083ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // (i.e. StepV can never dominate its loop header).  Ideally, we could do
1084ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1085ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // so it's not worth implementing SmallPtrSet::swap.
1086ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1087ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoops.clear();
1088ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick
1089a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand code for the start value.
1090a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1091a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                L->getHeader()->begin());
1092a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1093d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick  // StartV must be hoisted into L's preheader to dominate the new phi.
109493a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer  assert(!isa<Instruction>(StartV) ||
109593a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer         SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
109693a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer                                  L->getHeader()));
1097d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
1098553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // Expand code for the step value. Do this before creating the PHI so that PHI
1099553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // reuse code doesn't see an incomplete PHI.
1100a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
1101553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // If the stride is negative, insert a sub instead of an add for the increment
1102553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // (unless it's a constant, because subtracts of constants are canonicalized
1103553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // to adds).
1104f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick  bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1105553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  if (useSubtract)
1106a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Step = SE.getNegativeSCEV(Step);
1107553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // Expand the step somewhere that dominates the loop header.
1108a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1109a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1110a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the PHI.
1111d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  BasicBlock *Header = L->getHeader();
1112d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  Builder.SetInsertPoint(Header, Header->begin());
1113d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
11145e7645be4c9dd2193add44d30b5fef8036d7a3ceAndrew Trick  PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1115dc8e546048db2f7ff5656742b2b26975098a11a0Andrew Trick                                  Twine(IVName) + ".iv");
1116a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(PN);
1117a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1118a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the step instructions and populate the PHI.
1119d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1120a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *Pred = *HPI;
1121a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1122a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // Add a start value.
1123a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (!L->contains(Pred)) {
1124a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      PN->addIncoming(StartV, Pred);
1125a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      continue;
1126a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
1127a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1128553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // Create a step value and add it to the PHI.
1129553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1130553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // instructions at IVIncInsertPos.
1131a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Instruction *InsertPos = L == IVIncInsertLoop ?
1132a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IVIncInsertPos : Pred->getTerminator();
1133c5ecbdc1896f1cc089372feef3191ace2f840898Devang Patel    Builder.SetInsertPoint(InsertPos);
1134553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1135553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick
1136a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PN->addIncoming(IncV, Pred);
1137a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1138a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1139a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Restore the original insert point.
1140a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (SaveInsertBB)
1141455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1142a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1143ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // After expanding subexpressions, restore the PostIncLoops set so the caller
1144ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // can ensure that IVIncrement dominates the current uses.
1145ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoops = SavedPostIncLoops;
1146ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick
1147a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Remember this PHI, even in post-inc mode.
1148a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  InsertedValues.insert(PN);
1149a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1150a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return PN;
1151a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
1152a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1153a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanValue *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1154db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *STy = S->getType();
1155db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *IntTy = SE.getEffectiveSCEVType(STy);
1156a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Loop *L = S->getLoop();
1157a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1158a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Determine a normalized form of this expression, which is the expression
1159a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // before any post-inc adjustment is made.
1160a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVAddRecExpr *Normalized = S;
1161448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (PostIncLoops.count(L)) {
1162448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    PostIncLoopSet Loops;
1163448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    Loops.insert(L);
1164448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    Normalized =
1165448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman      cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1166448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman                                                  Loops, SE, *SE.DT));
1167a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1168a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1169a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec start.
1170a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Start = Normalized->getStart();
1171a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *PostLoopOffset = 0;
1172dc0e8fb9f9512622f55f73e1a434caa5c0915694Dan Gohman  if (!SE.properlyDominates(Start, L->getHeader())) {
1173a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopOffset = Start;
1174deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    Start = SE.getConstant(Normalized->getType(), 0);
11753228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    Normalized = cast<SCEVAddRecExpr>(
11763228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick      SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
11773228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                       Normalized->getLoop(),
11783228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                       // FIXME: Normalized->getNoWrapFlags(FlagNW)
11793228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                       SCEV::FlagAnyWrap));
1180a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1181a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1182a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec step.
1183a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
1184a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *PostLoopScale = 0;
1185dc0e8fb9f9512622f55f73e1a434caa5c0915694Dan Gohman  if (!SE.dominates(Step, L->getHeader())) {
1186a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopScale = Step;
1187deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    Step = SE.getConstant(Normalized->getType(), 1);
1188a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Normalized =
1189a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
11903228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            Normalized->getLoop(),
11913228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            // FIXME: Normalized
11923228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            // ->getNoWrapFlags(FlagNW)
11933228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            SCEV::FlagAnyWrap));
1194a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1195a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1196a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand the core addrec. If we need post-loop scaling, force it to
1197a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // expand to an integer type to avoid the need for additional casting.
1198db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *ExpandTy = PostLoopScale ? IntTy : STy;
1199a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1200a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
12013f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // Accommodate post-inc mode, if necessary.
1202a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Result;
1203448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (!PostIncLoops.count(L))
1204a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN;
1205a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  else {
1206a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // In PostInc mode, use the post-incremented value.
1207a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *LatchBlock = L->getLoopLatch();
1208a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1209a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN->getIncomingValueForBlock(LatchBlock);
121048ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick
121148ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // For an expansion to use the postinc form, the client must call
121248ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
121348ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // or dominated by IVIncInsertPos.
1214553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    if (isa<Instruction>(Result)
1215553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick        && !SE.DT->dominates(cast<Instruction>(Result),
1216553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                             Builder.GetInsertPoint())) {
1217553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // The induction variable's postinc expansion does not dominate this use.
1218553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // IVUsers tries to prevent this case, so it is rare. However, it can
1219553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // happen when an IVUser outside the loop is not dominated by the latch
1220553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1221553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // all cases. Consider a phi outide whose operand is replaced during
1222553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // expansion with the value of the postinc user. Without fundamentally
1223553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // changing the way postinc users are tracked, the only remedy is
1224553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1225553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // but hopefully expandCodeFor handles that.
1226553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      bool useSubtract =
1227f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick        !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1228553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      if (useSubtract)
1229553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick        Step = SE.getNegativeSCEV(Step);
1230553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // Expand the step somewhere that dominates the loop header.
1231553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1232553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1233553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1234553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // Restore the insertion point to the place where the caller has
1235553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // determined dominates all uses.
1236553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1237553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1238553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    }
1239a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1240a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1241a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating scale.
1242a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopScale) {
12430a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman    Result = InsertNoopCastOfTo(Result, IntTy);
1244a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = Builder.CreateMul(Result,
1245a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                               expandCodeFor(PostLoopScale, IntTy));
1246a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Result);
1247a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1248a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1249a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating offset.
1250a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopOffset) {
1251db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1252a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const SCEV *const OffsetArray[1] = { PostLoopOffset };
1253a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1254a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
12550a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman      Result = InsertNoopCastOfTo(Result, IntTy);
1256a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = Builder.CreateAdd(Result,
1257a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                 expandCodeFor(PostLoopOffset, IntTy));
1258a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      rememberInstruction(Result);
1259a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
1260a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1261a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1262a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return Result;
1263a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
1264a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1265890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1266a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!CanonicalMode) return expandAddRecExprLiterally(S);
1267a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1268db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
126936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  const Loop *L = S->getLoop();
127036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
12714d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // First check for an existing canonical IV in a suitable type.
12724d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  PHINode *CanonicalIV = 0;
12734d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (PHINode *PN = L->getCanonicalInductionVariable())
1274133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman    if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
12754d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      CanonicalIV = PN;
12764d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
12774d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Rewrite an AddRec in terms of the canonical induction variable, if
12784d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // its type is more narrow.
12794d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (CanonicalIV &&
12804d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(CanonicalIV->getType()) >
12814d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(Ty)) {
1282f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1283f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1284f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman      NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
12853228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
12863228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                       // FIXME: S->getNoWrapFlags(FlagNW)
12873228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                       SCEV::FlagAnyWrap));
1288267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1289267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
12904d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    BasicBlock::iterator NewInsertPt =
12917896c9f436a4eda5ec15e882a7505ba482a2fcd0Chris Lattner      llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
1292a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling    while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1293a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling           isa<LandingPadInst>(NewInsertPt))
129408f55d02da2cd24f3b4297259ef6429b8bf1ef97Jim Grosbach      ++NewInsertPt;
12954d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
12964d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman                      NewInsertPt);
1297455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
12984d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    return V;
12994d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  }
13004d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
130136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // {X,+,F} --> X + {0,+,F}
1302cfeb6a450632f2a6cd05302633c8c2b8c90cfdfdDan Gohman  if (!S->getStart()->isZero()) {
1303f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1304deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    NewOps[0] = SE.getConstant(Ty, 0);
13053228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    // FIXME: can use S->getNoWrapFlags()
13063228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    const SCEV *Rest = SE.getAddRecExpr(NewOps, L, SCEV::FlagAnyWrap);
1307453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
1308453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1309453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // comments on expandAddToGEP for details.
1310c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *Base = S->getStart();
1311c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *RestArray[1] = { Rest };
1312c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Dig into the expression to find the pointer base for a GEP.
1313c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ExposePointerBase(Base, RestArray[0], SE);
1314c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If we found a pointer, expand the AddRec with a GEP.
1315db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1316c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Make sure the Base isn't something exotic, such as a multiplied
1317c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // or divided pointer value. In those cases, the result type isn't
1318c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // actually a pointer type.
1319c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1320c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Value *StartV = expand(Base);
1321c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1322c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1323453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
1324453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
1325453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
132640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    // Just do a normal add. Pre-expand the operands to suppress folding.
132740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
132840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                SE.getUnknown(expand(Rest))));
132936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
133036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
13316ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  // If we don't yet have a canonical IV, create one.
13326ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  if (!CanonicalIV) {
133336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // Create and insert the PHI node for the induction variable in the
133436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // specified loop.
133536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    BasicBlock *Header = L->getHeader();
1336d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad    pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
13373ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad    CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
13383ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad                                  Header->begin());
13396ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    rememberInstruction(CanonicalIV);
134036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1341eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson    Constant *One = ConstantInt::get(Ty, 1);
1342d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad    for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
13437656018c2268285907cfdc106071462a01a73878Gabor Greif      BasicBlock *HP = *HPI;
13447656018c2268285907cfdc106071462a01a73878Gabor Greif      if (L->contains(HP)) {
13453abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // Insert a unit add instruction right before the terminator
13463abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // corresponding to the back-edge.
13476ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
13486ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                                     "indvar.next",
13496ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                                     HP->getTerminator());
1350df3ad6697bb849e514c0881ca8700ea36678cbdaDevang Patel        Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1351a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        rememberInstruction(Add);
13526ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        CanonicalIV->addIncoming(Add, HP);
135383d577490b1473213b6973236110c28e59127956Dan Gohman      } else {
13546ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
135583d577490b1473213b6973236110c28e59127956Dan Gohman      }
13567656018c2268285907cfdc106071462a01a73878Gabor Greif    }
135736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
135836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
13596ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  // {0,+,1} --> Insert a canonical induction variable into the loop!
13606ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  if (S->isAffine() && S->getOperand(1)->isOne()) {
13616ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
13626ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman           "IVs with types different from the canonical IV should "
13636ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman           "already have been handled!");
13646ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    return CanonicalIV;
13656ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  }
13666ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman
13674d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // {0,+,F} --> {0,+,1} * F
136836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1369df14a04b5ccbbe6a46c2ccb93e27b12a36ff163eChris Lattner  // If this is a simple linear addrec, emit it now as a special case.
137040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  if (S->isAffine())    // {0,+,F} --> i*F
137140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return
137240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      expand(SE.getTruncateOrNoop(
13736ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        SE.getMulExpr(SE.getUnknown(CanonicalIV),
137440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                      SE.getNoopOrAnyExtend(S->getOperand(1),
13756ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                            CanonicalIV->getType())),
137640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        Ty));
137736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
137836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // If this is a chain of recurrences, turn it into a closed form, using the
137936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // folders, then expandCodeFor the closed form.  This allows the folders to
138036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // simplify the expression without having to build a bunch of special code
138136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // into this folder.
13826ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
138336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
13844d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Promote S up to the canonical IV type, if the cast is foldable.
13850bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *NewS = S;
13866ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
13874d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (isa<SCEVAddRecExpr>(Ext))
13884d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    NewS = Ext;
13894d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
13900bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1391e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
139236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
13934d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Truncate the result down to the original type, if needed.
13940bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1395469f3cdc13851914f3a766cbd8f701cf8431cacaDan Gohman  return expand(T);
139636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
139796fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov
1398890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1399db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
140092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
140192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1402a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateTrunc(V, Ty);
1403a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1404cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
140511f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
140611f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1407890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1408db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
140992fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
141092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1411a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateZExt(V, Ty);
1412a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1413cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
141411f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
141511f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1416890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1417db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
141892fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
141992fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1420a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateSExt(V, Ty);
1421a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1422cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
142311f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
142411f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1425890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
14260196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1427db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = LHS->getType();
14280196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
14290196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
14300196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
14310196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
14320196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
14330196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
14340196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
143592fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1436a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer    Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1437a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1438267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1439a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1440cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
1441c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  }
14420196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
14430196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
14440196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
14450196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
1446c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  return LHS;
1447c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky}
1448c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky
1449890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
14500196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1451db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = LHS->getType();
14520196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
14530196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
14540196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
14550196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
14560196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
14570196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
14580196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
145992fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1460a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer    Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1461a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1462267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1463a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1464cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
14653e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  }
14660196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
14670196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
14680196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
14690196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
14703e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  return LHS;
14713e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky}
14723e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky
1473db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1474b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                   Instruction *IP) {
14756c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  Builder.SetInsertPoint(IP->getParent(), IP);
14766c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  return expandCodeFor(SH, Ty);
14776c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman}
14786c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman
1479db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
148011f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman  // Expand the code for this SCEV.
14812d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  Value *V = expand(SH);
14825be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (Ty) {
14835be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
14845be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman           "non-trivial casts should be done with the SCEVs directly!");
14855be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V, Ty);
14865be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
14875be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return V;
148811f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
148911f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1490890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::expand(const SCEV *S) {
149140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // Compute an insertion point for this SCEV object. Hoist the instructions
149240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // as far out in the loop nest as possible.
1493267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction *InsertPt = Builder.GetInsertPoint();
1494267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
149540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman       L = L->getParentLoop())
149617ead4ff4baceb2c5503f233d0288d363ae44165Dan Gohman    if (SE.isLoopInvariant(S, L)) {
149740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (!L) break;
1498e059ee832ca36d65a5fb87b0ac5bcdb0490b15cbDan Gohman      if (BasicBlock *Preheader = L->getLoopPreheader())
149940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        InsertPt = Preheader->getTerminator();
15000f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick      else {
15010f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // LSR sets the insertion point for AddRec start/step values to the
15020f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // block start to simplify value reuse, even though it's an invalid
15030f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // position. SCEVExpander must correct for this in all cases.
15040f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        InsertPt = L->getHeader()->getFirstInsertionPt();
15050f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick      }
150640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    } else {
150740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // If the SCEV is computable at this level, insert it into the header
150840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // after the PHIs (and after any other instructions that we've inserted
150940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // there) so that it is guaranteed to dominate any user inside the loop.
15105b6f42f57e730c2d968c313a27fa505a3c3e5efaBill Wendling      if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
15115b6f42f57e730c2d968c313a27fa505a3c3e5efaBill Wendling        InsertPt = L->getHeader()->getFirstInsertionPt();
1512b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      while (InsertPt != Builder.GetInsertPoint()
1513b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick             && (isInsertedInstruction(InsertPt)
1514b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                 || isa<DbgInfoIntrinsic>(InsertPt))) {
15157896c9f436a4eda5ec15e882a7505ba482a2fcd0Chris Lattner        InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
1516b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      }
151740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      break;
151840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    }
151940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1520667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Check to see if we already expanded this here.
1521667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  std::map<std::pair<const SCEV *, Instruction *>,
1522667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman           AssertingVH<Value> >::iterator I =
1523667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    InsertedExpressions.find(std::make_pair(S, InsertPt));
1524267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (I != InsertedExpressions.end())
1525667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    return I->second;
1526267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
1527267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1528267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1529267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1530667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1531667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Expand the expression into instructions.
153296fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  Value *V = visit(S);
153340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1534667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Remember the expanded value for this SCEV at this location.
153548ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  //
153648ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // This is independent of PostIncLoops. The mapped value simply materializes
153748ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // the expression at this insertion point. If the mapped value happened to be
153848ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // a postinc expansion, it could be reused by a non postinc user, but only if
153948ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // its insertion point was already at the head of the loop.
154048ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1541667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1542455985501381777db03534c925a35e261e356395Dan Gohman  restoreInsertPoint(SaveInsertBB, SaveInsertPt);
154396fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  return V;
154496fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov}
15451d09de3eca23267855e28297fcb40de3632ea47bDan Gohman
15461d826a76f591afea445489b9a5485c345e66bf87Dan Gohmanvoid SCEVExpander::rememberInstruction(Value *I) {
154725fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman  if (!PostIncLoops.empty())
154825fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman    InsertedPostIncValues.insert(I);
154925fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman  else
15501d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    InsertedValues.insert(I);
15511d826a76f591afea445489b9a5485c345e66bf87Dan Gohman}
15521d826a76f591afea445489b9a5485c345e66bf87Dan Gohman
1553455985501381777db03534c925a35e261e356395Dan Gohmanvoid SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
1554455985501381777db03534c925a35e261e356395Dan Gohman  Builder.SetInsertPoint(BB, I);
1555455985501381777db03534c925a35e261e356395Dan Gohman}
1556455985501381777db03534c925a35e261e356395Dan Gohman
15571d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// getOrInsertCanonicalInductionVariable - This method returns the
15581d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// canonical induction variable of the specified type for the specified
15591d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// loop (inserting one if there is none).  A canonical induction variable
15601d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// starts at zero and steps by one on each iteration.
15617c58dbd88c36c5d6c411ea6c046ddcff4c5841e9Dan GohmanPHINode *
15621d09de3eca23267855e28297fcb40de3632ea47bDan GohmanSCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1563db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                                    Type *Ty) {
1564b0bc6c361da9009e8414efde317d9bbff755f6c0Duncan Sands  assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1565133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
1566133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman  // Build a SCEV for {0,+,1}<L>.
15673228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick  // Conservatively use FlagAnyWrap for now.
1568deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman  const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
15693228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                   SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1570133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
1571133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman  // Emit code for it.
1572267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1573267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
15747c58dbd88c36c5d6c411ea6c046ddcff4c5841e9Dan Gohman  PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
1575267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (SaveInsertBB)
1576455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1577133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
157840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  return V;
15791d09de3eca23267855e28297fcb40de3632ea47bDan Gohman}
1580204494149b6f846e8f173f525b129f5508076049Andrew Trick
1581139f333f88fb9e0c39dfa3b56fd2a26b33837b70Andrew Trick/// Sort values by integer width for replaceCongruentIVs.
1582139f333f88fb9e0c39dfa3b56fd2a26b33837b70Andrew Trickstatic bool width_descending(Value *lhs, Value *rhs) {
1583ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  // Put pointers at the back and make sure pointer < pointer = false.
1584ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  if (!lhs->getType()->isIntegerTy() || !rhs->getType()->isIntegerTy())
1585ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    return rhs->getType()->isIntegerTy() && !lhs->getType()->isIntegerTy();
1586ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  return rhs->getType()->getPrimitiveSizeInBits()
1587ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    < lhs->getType()->getPrimitiveSizeInBits();
1588ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick}
1589ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick
1590204494149b6f846e8f173f525b129f5508076049Andrew Trick/// replaceCongruentIVs - Check for congruent phis in this loop header and
1591204494149b6f846e8f173f525b129f5508076049Andrew Trick/// replace them with their most canonical representative. Return the number of
1592204494149b6f846e8f173f525b129f5508076049Andrew Trick/// phis eliminated.
1593204494149b6f846e8f173f525b129f5508076049Andrew Trick///
1594204494149b6f846e8f173f525b129f5508076049Andrew Trick/// This does not depend on any SCEVExpander state but should be used in
1595204494149b6f846e8f173f525b129f5508076049Andrew Trick/// the same context that SCEVExpander is used.
1596204494149b6f846e8f173f525b129f5508076049Andrew Trickunsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1597ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick                                           SmallVectorImpl<WeakVH> &DeadInsts,
1598ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick                                           const TargetLowering *TLI) {
1599ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  // Find integer phis in order of increasing width.
1600ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  SmallVector<PHINode*, 8> Phis;
1601ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  for (BasicBlock::iterator I = L->getHeader()->begin();
1602ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick       PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1603ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    Phis.push_back(Phi);
1604ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  }
1605ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  if (TLI)
1606ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    std::sort(Phis.begin(), Phis.end(), width_descending);
1607ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick
1608204494149b6f846e8f173f525b129f5508076049Andrew Trick  unsigned NumElim = 0;
1609204494149b6f846e8f173f525b129f5508076049Andrew Trick  DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1610ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  // Process phis from wide to narrow. Mapping wide phis to the their truncation
1611ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  // so narrow phis can reuse them.
1612ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1613ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick         PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1614ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    PHINode *Phi = *PIter;
1615ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick
1616204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (!SE.isSCEVable(Phi->getType()))
1617204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1618204494149b6f846e8f173f525b129f5508076049Andrew Trick
1619204494149b6f846e8f173f525b129f5508076049Andrew Trick    PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1620204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (!OrigPhiRef) {
1621204494149b6f846e8f173f525b129f5508076049Andrew Trick      OrigPhiRef = Phi;
1622ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      if (Phi->getType()->isIntegerTy() && TLI
1623ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick          && TLI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1624ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        // This phi can be freely truncated to the narrowest phi type. Map the
1625ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        // truncated expression to it so it will be reused for narrow types.
1626ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        const SCEV *TruncExpr =
1627ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick          SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1628ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        ExprToIVMap[TruncExpr] = Phi;
1629ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      }
1630204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1631204494149b6f846e8f173f525b129f5508076049Andrew Trick    }
1632204494149b6f846e8f173f525b129f5508076049Andrew Trick
1633ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1634ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    // sense.
1635ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1636204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1637204494149b6f846e8f173f525b129f5508076049Andrew Trick
1638204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1639204494149b6f846e8f173f525b129f5508076049Andrew Trick      Instruction *OrigInc =
1640204494149b6f846e8f173f525b129f5508076049Andrew Trick        cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1641204494149b6f846e8f173f525b129f5508076049Andrew Trick      Instruction *IsomorphicInc =
1642204494149b6f846e8f173f525b129f5508076049Andrew Trick        cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1643204494149b6f846e8f173f525b129f5508076049Andrew Trick
1644ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      // If this phi has the same width but is more canonical, replace the
1645b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // original with it. As part of the "more canonical" determination,
1646b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // respect a prior decision to use an IV chain.
1647ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      if (OrigPhiRef->getType() == Phi->getType()
1648b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          && !(ChainedPhis.count(Phi)
1649b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick               || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1650b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          && (ChainedPhis.count(Phi)
1651b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick              || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1652204494149b6f846e8f173f525b129f5508076049Andrew Trick        std::swap(OrigPhiRef, Phi);
1653204494149b6f846e8f173f525b129f5508076049Andrew Trick        std::swap(OrigInc, IsomorphicInc);
1654204494149b6f846e8f173f525b129f5508076049Andrew Trick      }
1655204494149b6f846e8f173f525b129f5508076049Andrew Trick      // Replacing the congruent phi is sufficient because acyclic redundancy
1656204494149b6f846e8f173f525b129f5508076049Andrew Trick      // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1657204494149b6f846e8f173f525b129f5508076049Andrew Trick      // that a phi is congruent, it's often the head of an IV user cycle that
1658139f333f88fb9e0c39dfa3b56fd2a26b33837b70Andrew Trick      // is isomorphic with the original phi. It's worth eagerly cleaning up the
1659139f333f88fb9e0c39dfa3b56fd2a26b33837b70Andrew Trick      // common case of a single IV increment so that DeleteDeadPHIs can remove
1660139f333f88fb9e0c39dfa3b56fd2a26b33837b70Andrew Trick      // cycles that had postinc uses.
1661ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1662ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick                                                   IsomorphicInc->getType());
1663ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      if (OrigInc != IsomorphicInc
166464925c55c65f9345a69fb67db07aa62cfb723577Andrew Trick          && TruncExpr == SE.getSCEV(IsomorphicInc)
1665b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1666b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick              || hoistIVInc(OrigInc, IsomorphicInc))) {
1667204494149b6f846e8f173f525b129f5508076049Andrew Trick        DEBUG_WITH_TYPE(DebugType, dbgs()
1668204494149b6f846e8f173f525b129f5508076049Andrew Trick                        << "INDVARS: Eliminated congruent iv.inc: "
1669204494149b6f846e8f173f525b129f5508076049Andrew Trick                        << *IsomorphicInc << '\n');
1670ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        Value *NewInc = OrigInc;
1671ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        if (OrigInc->getType() != IsomorphicInc->getType()) {
1672dd1f22f25d8496b10cfddedb63d674dd39897bb0Andrew Trick          Instruction *IP = isa<PHINode>(OrigInc)
1673dd1f22f25d8496b10cfddedb63d674dd39897bb0Andrew Trick            ? (Instruction*)L->getHeader()->getFirstInsertionPt()
1674dd1f22f25d8496b10cfddedb63d674dd39897bb0Andrew Trick            : OrigInc->getNextNode();
1675dd1f22f25d8496b10cfddedb63d674dd39897bb0Andrew Trick          IRBuilder<> Builder(IP);
1676ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick          Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1677ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick          NewInc = Builder.
1678ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick            CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1679ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        }
1680ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        IsomorphicInc->replaceAllUsesWith(NewInc);
1681204494149b6f846e8f173f525b129f5508076049Andrew Trick        DeadInsts.push_back(IsomorphicInc);
1682204494149b6f846e8f173f525b129f5508076049Andrew Trick      }
1683204494149b6f846e8f173f525b129f5508076049Andrew Trick    }
1684204494149b6f846e8f173f525b129f5508076049Andrew Trick    DEBUG_WITH_TYPE(DebugType, dbgs()
1685204494149b6f846e8f173f525b129f5508076049Andrew Trick                    << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1686204494149b6f846e8f173f525b129f5508076049Andrew Trick    ++NumElim;
1687ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    Value *NewIV = OrigPhiRef;
1688ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    if (OrigPhiRef->getType() != Phi->getType()) {
1689ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1690ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1691ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1692ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    }
1693ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    Phi->replaceAllUsesWith(NewIV);
1694204494149b6f846e8f173f525b129f5508076049Andrew Trick    DeadInsts.push_back(Phi);
1695204494149b6f846e8f173f525b129f5508076049Andrew Trick  }
1696204494149b6f846e8f173f525b129f5508076049Andrew Trick  return NumElim;
1697204494149b6f846e8f173f525b129f5508076049Andrew Trick}
1698