blob: 216a95870a85f15565b0fee8fb9123d6a8453410 [file] [log] [blame]
Nick Lewyckyaf508372016-04-24 17:55:41 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
Nate Begeman2bca4d92005-07-30 00:12:19 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman2bca4d92005-07-30 00:12:19 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution expander,
11// which is used to generate the code corresponding to a given scalar evolution
12// expression.
13//
14//===----------------------------------------------------------------------===//
15
Nate Begeman2bca4d92005-07-30 00:12:19 +000016#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallSet.h"
Benjamin Kramer8dd637a2014-06-21 11:47:18 +000019#include "llvm/Analysis/InstructionSimplify.h"
Bill Wendlingf3baad32006-12-07 01:30:32 +000020#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth26c59fa2013-01-07 14:41:08 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/IntrinsicInst.h"
25#include "llvm/IR/LLVMContext.h"
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +000026#include "llvm/IR/Module.h"
Jingyue Wu6f72aed2015-06-24 19:28:40 +000027#include "llvm/IR/PatternMatch.h"
Andrew Trick7fb669a2011-10-07 23:46:21 +000028#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "llvm/Support/raw_ostream.h"
Andrew Trick244e2c32011-07-16 00:59:39 +000030
Nate Begeman2bca4d92005-07-30 00:12:19 +000031using namespace llvm;
Jingyue Wu6f72aed2015-06-24 19:28:40 +000032using namespace PatternMatch;
Nate Begeman2bca4d92005-07-30 00:12:19 +000033
Gabor Greif8e66a422010-07-09 16:42:04 +000034/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohmand2772462010-06-19 13:25:23 +000035/// reusing an existing cast if a suitable one exists, moving an existing
36/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif8e66a422010-07-09 16:42:04 +000037/// creating a new one.
Chris Lattner229907c2011-07-18 04:54:35 +000038Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohmand2772462010-06-19 13:25:23 +000039 Instruction::CastOps Op,
40 BasicBlock::iterator IP) {
Rafael Espindolacd06b482012-02-22 03:21:39 +000041 // This function must be called with the builder having a valid insertion
42 // point. It doesn't need to be the actual IP where the uses of the returned
43 // cast will be added, but it must dominate such IP.
Rafael Espindola09a42012012-02-27 02:13:03 +000044 // We use this precondition to produce a cast that will dominate all its
45 // uses. In particular, this is crucial for the case where the builder's
46 // insertion point *is* the point where we were asked to put the cast.
Sylvestre Ledru35521e22012-07-23 08:51:15 +000047 // Since we don't know the builder's insertion point is actually
Rafael Espindolacd06b482012-02-22 03:21:39 +000048 // where the uses will be added (only that it dominates it), we are
49 // not allowed to move it.
50 BasicBlock::iterator BIP = Builder.GetInsertPoint();
51
Craig Topper9f008862014-04-15 04:59:12 +000052 Instruction *Ret = nullptr;
Rafael Espindola82d95752012-02-18 17:22:58 +000053
Dan Gohmand2772462010-06-19 13:25:23 +000054 // Check to see if there is already a cast!
Chandler Carruthcdf47882014-03-09 03:16:01 +000055 for (User *U : V->users())
Gabor Greif3b740e92010-07-09 16:39:02 +000056 if (U->getType() == Ty)
Gabor Greif8e66a422010-07-09 16:42:04 +000057 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohmand2772462010-06-19 13:25:23 +000058 if (CI->getOpcode() == Op) {
Rafael Espindola337cfaf2012-02-22 03:44:46 +000059 // If the cast isn't where we want it, create a new cast at IP.
60 // Likewise, do not reuse a cast at BIP because it must dominate
61 // instructions that might be inserted before BIP.
Rafael Espindolacd06b482012-02-22 03:21:39 +000062 if (BasicBlock::iterator(CI) != IP || BIP == IP) {
Dan Gohmand2772462010-06-19 13:25:23 +000063 // Create a new cast, and leave the old cast in place in case
64 // it is being used as an insert point. Clear its operand
65 // so that it doesn't hold anything live.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +000066 Ret = CastInst::Create(Op, V, Ty, "", &*IP);
Rafael Espindola09a42012012-02-27 02:13:03 +000067 Ret->takeName(CI);
68 CI->replaceAllUsesWith(Ret);
Dan Gohmand2772462010-06-19 13:25:23 +000069 CI->setOperand(0, UndefValue::get(V->getType()));
Rafael Espindola09a42012012-02-27 02:13:03 +000070 break;
Dan Gohmand2772462010-06-19 13:25:23 +000071 }
Rafael Espindola09a42012012-02-27 02:13:03 +000072 Ret = CI;
73 break;
Dan Gohmand2772462010-06-19 13:25:23 +000074 }
75
76 // Create a new cast.
Rafael Espindola09a42012012-02-27 02:13:03 +000077 if (!Ret)
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +000078 Ret = CastInst::Create(Op, V, Ty, V->getName(), &*IP);
Rafael Espindola09a42012012-02-27 02:13:03 +000079
80 // We assert at the end of the function since IP might point to an
81 // instruction with different dominance properties than a cast
82 // (an invoke for example) and not dominate BIP (but the cast does).
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +000083 assert(SE.DT.dominates(Ret, &*BIP));
Rafael Espindola09a42012012-02-27 02:13:03 +000084
85 rememberInstruction(Ret);
86 return Ret;
Dan Gohmand2772462010-06-19 13:25:23 +000087}
88
David Majnemerdd9a8152015-10-27 07:36:42 +000089static BasicBlock::iterator findInsertPointAfter(Instruction *I,
David Majnemerdd9a8152015-10-27 07:36:42 +000090 BasicBlock *MustDominate) {
91 BasicBlock::iterator IP = ++I->getIterator();
92 if (auto *II = dyn_cast<InvokeInst>(I))
93 IP = II->getNormalDest()->begin();
David Majnemerdd9a8152015-10-27 07:36:42 +000094
95 while (isa<PHINode>(IP))
96 ++IP;
97
David Majnemerfa8681e42016-02-03 21:30:31 +000098 if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
99 ++IP;
100 } else if (isa<CatchSwitchInst>(IP)) {
101 IP = MustDominate->getFirstInsertionPt();
102 } else {
103 assert(!IP->isEHPad() && "unexpected eh pad!");
David Majnemerdd9a8152015-10-27 07:36:42 +0000104 }
105
106 return IP;
107}
108
Dan Gohman830fd382009-06-27 21:18:18 +0000109/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
110/// which must be possible with a noop cast, doing what we can to share
111/// the casts.
Chris Lattner229907c2011-07-18 04:54:35 +0000112Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman830fd382009-06-27 21:18:18 +0000113 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
114 assert((Op == Instruction::BitCast ||
115 Op == Instruction::PtrToInt ||
116 Op == Instruction::IntToPtr) &&
117 "InsertNoopCastOfTo cannot perform non-noop casts!");
118 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
119 "InsertNoopCastOfTo cannot change sizes!");
120
Dan Gohman0a40ad92009-04-16 03:18:22 +0000121 // Short-circuit unnecessary bitcasts.
Andrew Tricke0ced622011-12-14 22:07:19 +0000122 if (Op == Instruction::BitCast) {
123 if (V->getType() == Ty)
124 return V;
125 if (CastInst *CI = dyn_cast<CastInst>(V)) {
126 if (CI->getOperand(0)->getType() == Ty)
127 return CI->getOperand(0);
128 }
129 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000130 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman830fd382009-06-27 21:18:18 +0000131 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman150b4c32009-05-01 17:00:00 +0000132 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000133 if (CastInst *CI = dyn_cast<CastInst>(V))
134 if ((CI->getOpcode() == Instruction::PtrToInt ||
135 CI->getOpcode() == Instruction::IntToPtr) &&
136 SE.getTypeSizeInBits(CI->getType()) ==
137 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
138 return CI->getOperand(0);
Dan Gohman150b4c32009-05-01 17:00:00 +0000139 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
140 if ((CE->getOpcode() == Instruction::PtrToInt ||
141 CE->getOpcode() == Instruction::IntToPtr) &&
142 SE.getTypeSizeInBits(CE->getType()) ==
143 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
144 return CE->getOperand(0);
145 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000146
Dan Gohmand2772462010-06-19 13:25:23 +0000147 // Fold a cast of a constant.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000148 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000149 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000150
Dan Gohmand2772462010-06-19 13:25:23 +0000151 // Cast the argument at the beginning of the entry block, after
152 // any bitcasts of other arguments.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000153 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohmand2772462010-06-19 13:25:23 +0000154 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
155 while ((isa<BitCastInst>(IP) &&
156 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
157 cast<BitCastInst>(IP)->getOperand(0) != A) ||
David Majnemerdd9a8152015-10-27 07:36:42 +0000158 isa<DbgInfoIntrinsic>(IP))
Dan Gohmand2772462010-06-19 13:25:23 +0000159 ++IP;
160 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000161 }
Wojciech Matyjewicz784d071e12008-02-09 18:30:13 +0000162
Dan Gohmand2772462010-06-19 13:25:23 +0000163 // Cast the instruction immediately after the instruction.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000164 Instruction *I = cast<Instruction>(V);
David Majnemer235acde2015-10-27 19:48:28 +0000165 BasicBlock::iterator IP = findInsertPointAfter(I, Builder.GetInsertBlock());
Dan Gohmand2772462010-06-19 13:25:23 +0000166 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000167}
168
Chris Lattnere71f1442007-04-13 05:04:18 +0000169/// InsertBinop - Insert the specified binary operator, doing a small amount
170/// of work to avoid inserting an obviously redundant operation.
Dan Gohman830fd382009-06-27 21:18:18 +0000171Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
172 Value *LHS, Value *RHS) {
Dan Gohman00cb1172007-06-15 19:21:55 +0000173 // Fold a binop with constant operands.
174 if (Constant *CLHS = dyn_cast<Constant>(LHS))
175 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Anderson487375e2009-07-29 18:55:55 +0000176 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman00cb1172007-06-15 19:21:55 +0000177
Chris Lattnere71f1442007-04-13 05:04:18 +0000178 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
179 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000180 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
181 // Scanning starts from the last instruction before the insertion point.
182 BasicBlock::iterator IP = Builder.GetInsertPoint();
183 if (IP != BlockBegin) {
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000184 --IP;
185 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000186 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
187 // generated code.
188 if (isa<DbgInfoIntrinsic>(IP))
189 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000190 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
191 IP->getOperand(1) == RHS)
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000192 return &*IP;
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000193 if (IP == BlockBegin) break;
194 }
Chris Lattnere71f1442007-04-13 05:04:18 +0000195 }
Dan Gohman830fd382009-06-27 21:18:18 +0000196
Dan Gohman29707de2010-03-03 05:29:13 +0000197 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000198 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
Geoff Berry0c095172016-06-01 20:03:09 +0000199 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohman29707de2010-03-03 05:29:13 +0000200
Sanjoy Das3d75b622016-11-10 07:56:12 +0000201 auto *RHSConst = dyn_cast<ConstantInt>(RHS);
202
203 if (Opcode != Instruction::UDiv || (RHSConst && !RHSConst->isZero())) {
Sanjoy Dase30a2812016-11-10 07:56:09 +0000204 // FIXME: There is alredy similar logic in expandCodeFor, we should see if
205 // this is actually needed here.
Dan Gohman29707de2010-03-03 05:29:13 +0000206
Sanjoy Dase30a2812016-11-10 07:56:09 +0000207 // Move the insertion point out of as many loops as we can.
208 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
209 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS))
210 break;
211 BasicBlock *Preheader = L->getLoopPreheader();
212 if (!Preheader)
213 break;
214
215 // Ok, move up a level.
216 Builder.SetInsertPoint(Preheader->getTerminator());
217 }
Dan Gohman29707de2010-03-03 05:29:13 +0000218 }
219
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000220 // If we haven't found this binop, insert it.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000221 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Benjamin Kramer6e931522013-09-30 15:40:17 +0000222 BO->setDebugLoc(Loc);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000223 rememberInstruction(BO);
Dan Gohman29707de2010-03-03 05:29:13 +0000224
Dan Gohmand195a222009-05-01 17:13:31 +0000225 return BO;
Chris Lattnere71f1442007-04-13 05:04:18 +0000226}
227
Dan Gohman17893622009-05-27 02:00:53 +0000228/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman291c2e02009-05-24 18:06:31 +0000229/// division. If so, update S with Factor divided out and return true.
Dan Gohman8b0a4192010-03-01 17:49:51 +0000230/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman17893622009-05-27 02:00:53 +0000231/// computed.
Dan Gohman291c2e02009-05-24 18:06:31 +0000232/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
233/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
234/// check to see if the divide was folded.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000235static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
236 const SCEV *Factor, ScalarEvolution &SE,
237 const DataLayout &DL) {
Dan Gohman291c2e02009-05-24 18:06:31 +0000238 // Everything is divisible by one.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000239 if (Factor->isOne())
Dan Gohman291c2e02009-05-24 18:06:31 +0000240 return true;
241
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000242 // x/x == 1.
243 if (S == Factor) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000244 S = SE.getConstant(S->getType(), 1);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000245 return true;
246 }
247
Dan Gohman291c2e02009-05-24 18:06:31 +0000248 // For a Constant, check for a multiple of the given factor.
Dan Gohman17893622009-05-27 02:00:53 +0000249 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000250 // 0/x == 0.
251 if (C->isZero())
Dan Gohman291c2e02009-05-24 18:06:31 +0000252 return true;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000253 // Check for divisibility.
254 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
255 ConstantInt *CI =
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000256 ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000257 // If the quotient is zero and the remainder is non-zero, reject
258 // the value at this scale. It will be considered for subsequent
259 // smaller scales.
260 if (!CI->isZero()) {
261 const SCEV *Div = SE.getConstant(CI);
262 S = Div;
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000263 Remainder = SE.getAddExpr(
264 Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000265 return true;
266 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000267 }
Dan Gohman17893622009-05-27 02:00:53 +0000268 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000269
270 // In a Mul, check if there is a constant operand which is a multiple
271 // of the given factor.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000272 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000273 // Size is known, check if there is a constant operand which is a multiple
274 // of the given factor. If so, we can factor it.
275 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
276 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000277 if (!C->getAPInt().srem(FC->getAPInt())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000278 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000279 NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000280 S = SE.getMulExpr(NewMulOps);
281 return true;
Dan Gohman291c2e02009-05-24 18:06:31 +0000282 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000283 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000284
285 // In an AddRec, check if both start and step are divisible.
286 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmanaf752342009-07-07 17:06:11 +0000287 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000288 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000289 if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
Dan Gohman17893622009-05-27 02:00:53 +0000290 return false;
291 if (!StepRem->isZero())
292 return false;
Dan Gohmanaf752342009-07-07 17:06:11 +0000293 const SCEV *Start = A->getStart();
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000294 if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
Dan Gohman291c2e02009-05-24 18:06:31 +0000295 return false;
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000296 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
297 A->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +0000298 return true;
299 }
300
301 return false;
302}
303
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000304/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
305/// is the number of SCEVAddRecExprs present, which are kept at the end of
306/// the list.
307///
308static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000309 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000310 ScalarEvolution &SE) {
311 unsigned NumAddRecs = 0;
312 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
313 ++NumAddRecs;
314 // Group Ops into non-addrecs and addrecs.
315 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
316 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
317 // Let ScalarEvolution sort and simplify the non-addrecs list.
318 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +0000319 SE.getConstant(Ty, 0) :
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000320 SE.getAddExpr(NoAddRecs);
321 // If it returned an add, use the operands. Otherwise it simplified
322 // the sum into a single value, so just use that.
Dan Gohman00524492010-03-18 01:17:13 +0000323 Ops.clear();
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000324 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohmandd41bba2010-06-21 19:47:52 +0000325 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohman00524492010-03-18 01:17:13 +0000326 else if (!Sum->isZero())
327 Ops.push_back(Sum);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000328 // Then append the addrecs.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000329 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000330}
331
332/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
333/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
334/// This helps expose more opportunities for folding parts of the expressions
335/// into GEP indices.
336///
337static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000338 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000339 ScalarEvolution &SE) {
340 // Find the addrecs.
341 SmallVector<const SCEV *, 8> AddRecs;
342 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
343 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
344 const SCEV *Start = A->getStart();
345 if (Start->isZero()) break;
Dan Gohman1d2ded72010-05-03 22:09:21 +0000346 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000347 AddRecs.push_back(SE.getAddRecExpr(Zero,
348 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000349 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000350 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000351 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
352 Ops[i] = Zero;
Dan Gohmandd41bba2010-06-21 19:47:52 +0000353 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000354 e += Add->getNumOperands();
355 } else {
356 Ops[i] = Start;
357 }
358 }
359 if (!AddRecs.empty()) {
360 // Add the addrecs onto the end of the list.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000361 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000362 // Resort the operand list, moving any constants to the front.
363 SimplifyAddOperands(Ops, Ty, SE);
364 }
365}
366
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000367/// expandAddToGEP - Expand an addition expression with a pointer type into
368/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
369/// BasicAliasAnalysis and other passes analyze the result. See the rules
370/// for getelementptr vs. inttoptr in
371/// http://llvm.org/docs/LangRef.html#pointeraliasing
372/// for details.
Dan Gohman16e96c02009-07-20 17:44:17 +0000373///
Dan Gohman510bffc2010-01-19 22:26:02 +0000374/// Design note: The correctness of using getelementptr here depends on
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000375/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
376/// they may introduce pointer arithmetic which may not be safely converted
377/// into getelementptr.
Dan Gohman291c2e02009-05-24 18:06:31 +0000378///
379/// Design note: It might seem desirable for this function to be more
380/// loop-aware. If some of the indices are loop-invariant while others
381/// aren't, it might seem desirable to emit multiple GEPs, keeping the
382/// loop-invariant portions of the overall computation outside the loop.
383/// However, there are a few reasons this is not done here. Hoisting simple
384/// arithmetic is a low-level optimization that often isn't very
385/// important until late in the optimization process. In fact, passes
386/// like InstructionCombining will combine GEPs, even if it means
387/// pushing loop-invariant computation down into loops, so even if the
388/// GEPs were split here, the work would quickly be undone. The
389/// LoopStrengthReduction pass, which is usually run quite late (and
390/// after the last InstructionCombining pass), takes care of hoisting
391/// loop-invariant portions of expressions, after considering what
392/// can be folded using target addressing modes.
393///
Dan Gohmanaf752342009-07-07 17:06:11 +0000394Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
395 const SCEV *const *op_end,
Chris Lattner229907c2011-07-18 04:54:35 +0000396 PointerType *PTy,
397 Type *Ty,
Dan Gohman26494912009-05-19 02:15:55 +0000398 Value *V) {
David Blaikie156d46e2015-03-24 23:34:31 +0000399 Type *OriginalElTy = PTy->getElementType();
400 Type *ElTy = OriginalElTy;
Dan Gohman26494912009-05-19 02:15:55 +0000401 SmallVector<Value *, 4> GepIndices;
Dan Gohmanaf752342009-07-07 17:06:11 +0000402 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman26494912009-05-19 02:15:55 +0000403 bool AnyNonZeroIndices = false;
Dan Gohman26494912009-05-19 02:15:55 +0000404
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000405 // Split AddRecs up into parts as either of the parts may be usable
406 // without the other.
407 SplitAddRecs(Ops, Ty, SE);
408
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000409 Type *IntPtrTy = DL.getIntPtrType(PTy);
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000410
Bob Wilson2107eb72009-12-04 01:33:04 +0000411 // Descend down the pointer's type and attempt to convert the other
Dan Gohman26494912009-05-19 02:15:55 +0000412 // operands into GEP indices, at each level. The first index in a GEP
413 // indexes into the array implied by the pointer operand; the rest of
414 // the indices index into the element or field type selected by the
415 // preceding index.
416 for (;;) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000417 // If the scale size is not 0, attempt to factor out a scale for
418 // array indexing.
Dan Gohmanaf752342009-07-07 17:06:11 +0000419 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman9f4ea222010-01-28 06:32:46 +0000420 if (ElTy->isSized()) {
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000421 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
Dan Gohman9f4ea222010-01-28 06:32:46 +0000422 if (!ElSize->isZero()) {
423 SmallVector<const SCEV *, 8> NewOps;
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000424 for (const SCEV *Op : Ops) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000425 const SCEV *Remainder = SE.getConstant(Ty, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000426 if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
Dan Gohman9f4ea222010-01-28 06:32:46 +0000427 // Op now has ElSize factored out.
428 ScaledOps.push_back(Op);
429 if (!Remainder->isZero())
430 NewOps.push_back(Remainder);
431 AnyNonZeroIndices = true;
432 } else {
433 // The operand was not divisible, so add it to the list of operands
434 // we'll scan next iteration.
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000435 NewOps.push_back(Op);
Dan Gohman9f4ea222010-01-28 06:32:46 +0000436 }
Dan Gohman26494912009-05-19 02:15:55 +0000437 }
Dan Gohman9f4ea222010-01-28 06:32:46 +0000438 // If we made any changes, update Ops.
439 if (!ScaledOps.empty()) {
440 Ops = NewOps;
441 SimplifyAddOperands(Ops, Ty, SE);
442 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000443 }
Dan Gohman26494912009-05-19 02:15:55 +0000444 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000445
446 // Record the scaled array index for this level of the type. If
447 // we didn't find any operands that could be factored, tentatively
448 // assume that element zero was selected (since the zero offset
449 // would obviously be folded away).
Dan Gohman26494912009-05-19 02:15:55 +0000450 Value *Scaled = ScaledOps.empty() ?
Owen Anderson5a1acd92009-07-31 20:28:14 +0000451 Constant::getNullValue(Ty) :
Dan Gohman26494912009-05-19 02:15:55 +0000452 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
453 GepIndices.push_back(Scaled);
454
455 // Collect struct field index operands.
Chris Lattner229907c2011-07-18 04:54:35 +0000456 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000457 bool FoundFieldNo = false;
458 // An empty struct has no fields.
459 if (STy->getNumElements() == 0) break;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000460 // Field offsets are known. See if a constant offset falls within any of
461 // the struct fields.
462 if (Ops.empty())
463 break;
464 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
465 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
466 const StructLayout &SL = *DL.getStructLayout(STy);
467 uint64_t FullOffset = C->getValue()->getZExtValue();
468 if (FullOffset < SL.getSizeInBytes()) {
469 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
470 GepIndices.push_back(
471 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
472 ElTy = STy->getTypeAtIndex(ElIdx);
473 Ops[0] =
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000474 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000475 AnyNonZeroIndices = true;
476 FoundFieldNo = true;
Dan Gohman26494912009-05-19 02:15:55 +0000477 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000478 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000479 // If no struct field offsets were found, tentatively assume that
480 // field zero was selected (since the zero offset would obviously
481 // be folded away).
482 if (!FoundFieldNo) {
483 ElTy = STy->getTypeAtIndex(0u);
484 GepIndices.push_back(
485 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
486 }
Dan Gohman26494912009-05-19 02:15:55 +0000487 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000488
Chris Lattner229907c2011-07-18 04:54:35 +0000489 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000490 ElTy = ATy->getElementType();
491 else
492 break;
Dan Gohman26494912009-05-19 02:15:55 +0000493 }
494
Dan Gohman8b0a4192010-03-01 17:49:51 +0000495 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman26494912009-05-19 02:15:55 +0000496 // the base to i8* and do an ugly getelementptr with that. It's still
497 // better than ptrtoint+arithmetic+inttoptr at least.
498 if (!AnyNonZeroIndices) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000499 // Cast the base to i8*.
Dan Gohman26494912009-05-19 02:15:55 +0000500 V = InsertNoopCastOfTo(V,
Duncan Sands9ed7b162009-10-06 15:40:36 +0000501 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000502
Rafael Espindola729e3aa2012-02-21 03:51:14 +0000503 assert(!isa<Instruction>(V) ||
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000504 SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
Rafael Espindola7d445e92012-02-21 01:19:51 +0000505
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000506 // Expand the operands for a plain byte offset.
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000507 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman26494912009-05-19 02:15:55 +0000508
509 // Fold a GEP with constant operands.
510 if (Constant *CLHS = dyn_cast<Constant>(V))
511 if (Constant *CRHS = dyn_cast<Constant>(Idx))
David Blaikie4a2e73b2015-04-02 18:55:32 +0000512 return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
513 CLHS, CRHS);
Dan Gohman26494912009-05-19 02:15:55 +0000514
515 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
516 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000517 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
518 // Scanning starts from the last instruction before the insertion point.
519 BasicBlock::iterator IP = Builder.GetInsertPoint();
520 if (IP != BlockBegin) {
Dan Gohman26494912009-05-19 02:15:55 +0000521 --IP;
522 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000523 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
524 // generated code.
525 if (isa<DbgInfoIntrinsic>(IP))
526 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000527 if (IP->getOpcode() == Instruction::GetElementPtr &&
528 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000529 return &*IP;
Dan Gohman26494912009-05-19 02:15:55 +0000530 if (IP == BlockBegin) break;
531 }
532 }
533
Dan Gohman29707de2010-03-03 05:29:13 +0000534 // Save the original insertion point so we can restore it when we're done.
Geoff Berry0c095172016-06-01 20:03:09 +0000535 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohman29707de2010-03-03 05:29:13 +0000536
537 // Move the insertion point out of as many loops as we can.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000538 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000539 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
540 BasicBlock *Preheader = L->getLoopPreheader();
541 if (!Preheader) break;
542
543 // Ok, move up a level.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000544 Builder.SetInsertPoint(Preheader->getTerminator());
Dan Gohman29707de2010-03-03 05:29:13 +0000545 }
546
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000547 // Emit a GEP.
David Blaikie93c54442015-04-03 19:41:44 +0000548 Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
Dan Gohman51ad99d2010-01-21 02:09:26 +0000549 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000550
Dan Gohman26494912009-05-19 02:15:55 +0000551 return GEP;
552 }
553
Geoff Berry0c095172016-06-01 20:03:09 +0000554 {
555 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohman29707de2010-03-03 05:29:13 +0000556
Geoff Berry0c095172016-06-01 20:03:09 +0000557 // Move the insertion point out of as many loops as we can.
558 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
559 if (!L->isLoopInvariant(V)) break;
Dan Gohman29707de2010-03-03 05:29:13 +0000560
David Majnemer0a16c222016-08-11 21:15:00 +0000561 bool AnyIndexNotLoopInvariant = any_of(
562 GepIndices, [L](Value *Op) { return !L->isLoopInvariant(Op); });
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000563
Geoff Berry0c095172016-06-01 20:03:09 +0000564 if (AnyIndexNotLoopInvariant)
565 break;
Dan Gohman29707de2010-03-03 05:29:13 +0000566
Geoff Berry0c095172016-06-01 20:03:09 +0000567 BasicBlock *Preheader = L->getLoopPreheader();
568 if (!Preheader) break;
Dan Gohman29707de2010-03-03 05:29:13 +0000569
Geoff Berry0c095172016-06-01 20:03:09 +0000570 // Ok, move up a level.
571 Builder.SetInsertPoint(Preheader->getTerminator());
572 }
573
574 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
575 // because ScalarEvolution may have changed the address arithmetic to
576 // compute a value which is beyond the end of the allocated object.
577 Value *Casted = V;
578 if (V->getType() != PTy)
579 Casted = InsertNoopCastOfTo(Casted, PTy);
580 Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep");
581 Ops.push_back(SE.getUnknown(GEP));
582 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000583 }
584
Dan Gohman26494912009-05-19 02:15:55 +0000585 return expand(SE.getAddExpr(Ops));
586}
587
Dan Gohman29707de2010-03-03 05:29:13 +0000588/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
589/// SCEV expansion. If they are nested, this is the most nested. If they are
590/// neighboring, pick the later.
591static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
592 DominatorTree &DT) {
593 if (!A) return B;
594 if (!B) return A;
595 if (A->contains(B)) return B;
596 if (B->contains(A)) return A;
597 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
598 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
599 return A; // Arbitrarily break the tie.
600}
601
Dan Gohman8ea83d82010-11-18 00:34:22 +0000602/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman29707de2010-03-03 05:29:13 +0000603/// expression, according to PickMostRelevantLoop.
Dan Gohman8ea83d82010-11-18 00:34:22 +0000604const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
605 // Test whether we've already computed the most relevant loop for this SCEV.
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000606 auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
Dan Gohman8ea83d82010-11-18 00:34:22 +0000607 if (!Pair.second)
608 return Pair.first->second;
609
Dan Gohman29707de2010-03-03 05:29:13 +0000610 if (isa<SCEVConstant>(S))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000611 // A constant has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000612 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000613 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
614 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000615 return Pair.first->second = SE.LI.getLoopFor(I->getParent());
Dan Gohman8ea83d82010-11-18 00:34:22 +0000616 // A non-instruction has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000617 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000618 }
619 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
Craig Topper9f008862014-04-15 04:59:12 +0000620 const Loop *L = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000621 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
622 L = AR->getLoop();
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000623 for (const SCEV *Op : N->operands())
624 L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
Dan Gohman8ea83d82010-11-18 00:34:22 +0000625 return RelevantLoops[N] = L;
Dan Gohman29707de2010-03-03 05:29:13 +0000626 }
Dan Gohman8ea83d82010-11-18 00:34:22 +0000627 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
628 const Loop *Result = getRelevantLoop(C->getOperand());
629 return RelevantLoops[C] = Result;
630 }
631 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000632 const Loop *Result = PickMostRelevantLoop(
633 getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
Dan Gohman8ea83d82010-11-18 00:34:22 +0000634 return RelevantLoops[D] = Result;
635 }
Dan Gohman29707de2010-03-03 05:29:13 +0000636 llvm_unreachable("Unexpected SCEV type!");
637}
638
Dan Gohmanb29cda92010-04-15 17:08:50 +0000639namespace {
640
Dan Gohman29707de2010-03-03 05:29:13 +0000641/// LoopCompare - Compare loops by PickMostRelevantLoop.
642class LoopCompare {
643 DominatorTree &DT;
644public:
645 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
646
647 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
648 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000649 // Keep pointer operands sorted at the end.
650 if (LHS.second->getType()->isPointerTy() !=
651 RHS.second->getType()->isPointerTy())
652 return LHS.second->getType()->isPointerTy();
653
Dan Gohman29707de2010-03-03 05:29:13 +0000654 // Compare loops with PickMostRelevantLoop.
655 if (LHS.first != RHS.first)
656 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
657
658 // If one operand is a non-constant negative and the other is not,
659 // put the non-constant negative on the right so that a sub can
660 // be used instead of a negate and add.
Andrew Trick881a7762012-01-07 00:27:31 +0000661 if (LHS.second->isNonConstantNegative()) {
662 if (!RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000663 return false;
Andrew Trick881a7762012-01-07 00:27:31 +0000664 } else if (RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000665 return true;
666
667 // Otherwise they are equivalent according to this comparison.
668 return false;
669 }
670};
671
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000672}
Dan Gohmanb29cda92010-04-15 17:08:50 +0000673
Dan Gohman056857a2009-04-18 17:56:28 +0000674Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000675 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman5bafe382009-09-26 16:11:57 +0000676
Dan Gohman29707de2010-03-03 05:29:13 +0000677 // Collect all the add operands in a loop, along with their associated loops.
678 // Iterate in reverse so that constants are emitted last, all else equal, and
679 // so that pointer operands are inserted first, which the code below relies on
680 // to form more involved GEPs.
681 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
682 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
683 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000684 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohman5bafe382009-09-26 16:11:57 +0000685
Dan Gohman29707de2010-03-03 05:29:13 +0000686 // Sort by loop. Use a stable sort so that constants follow non-constants and
687 // pointer operands precede non-pointer operands.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000688 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
Dan Gohman26494912009-05-19 02:15:55 +0000689
Dan Gohman29707de2010-03-03 05:29:13 +0000690 // Emit instructions to add all the operands. Hoist as much as possible
691 // out of loops, and form meaningful getelementptrs where possible.
Craig Topper9f008862014-04-15 04:59:12 +0000692 Value *Sum = nullptr;
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000693 for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
Dan Gohman29707de2010-03-03 05:29:13 +0000694 const Loop *CurLoop = I->first;
695 const SCEV *Op = I->second;
696 if (!Sum) {
697 // This is the first operand. Just expand it.
698 Sum = expand(Op);
699 ++I;
Chris Lattner229907c2011-07-18 04:54:35 +0000700 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000701 // The running sum expression is a pointer. Try to form a getelementptr
702 // at this level with that as the base.
703 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000704 for (; I != E && I->first == CurLoop; ++I) {
705 // If the operand is SCEVUnknown and not instructions, peek through
706 // it, to enable more of it to be folded into the GEP.
707 const SCEV *X = I->second;
708 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
709 if (!isa<Instruction>(U->getValue()))
710 X = SE.getSCEV(U->getValue());
711 NewOps.push_back(X);
712 }
Dan Gohman29707de2010-03-03 05:29:13 +0000713 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattner229907c2011-07-18 04:54:35 +0000714 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000715 // The running sum is an integer, and there's a pointer at this level.
Dan Gohman3295a6e2010-04-09 19:14:31 +0000716 // Try to form a getelementptr. If the running sum is instructions,
717 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman29707de2010-03-03 05:29:13 +0000718 SmallVector<const SCEV *, 4> NewOps;
Dan Gohman3295a6e2010-04-09 19:14:31 +0000719 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
720 SE.getSCEV(Sum));
Dan Gohman29707de2010-03-03 05:29:13 +0000721 for (++I; I != E && I->first == CurLoop; ++I)
722 NewOps.push_back(I->second);
723 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trick881a7762012-01-07 00:27:31 +0000724 } else if (Op->isNonConstantNegative()) {
Dan Gohman29707de2010-03-03 05:29:13 +0000725 // Instead of doing a negate and add, just do a subtract.
Dan Gohman2850b412010-03-03 04:36:42 +0000726 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000727 Sum = InsertNoopCastOfTo(Sum, Ty);
728 Sum = InsertBinop(Instruction::Sub, Sum, W);
729 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000730 } else {
Dan Gohman29707de2010-03-03 05:29:13 +0000731 // A simple add.
Dan Gohman2850b412010-03-03 04:36:42 +0000732 Value *W = expandCodeFor(Op, Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000733 Sum = InsertNoopCastOfTo(Sum, Ty);
734 // Canonicalize a constant to the RHS.
735 if (isa<Constant>(Sum)) std::swap(Sum, W);
736 Sum = InsertBinop(Instruction::Add, Sum, W);
737 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000738 }
739 }
Dan Gohman29707de2010-03-03 05:29:13 +0000740
741 return Sum;
Dan Gohman095ca742008-06-18 16:37:11 +0000742}
Dan Gohman26494912009-05-19 02:15:55 +0000743
Dan Gohman056857a2009-04-18 17:56:28 +0000744Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000745 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +0000746
Dan Gohman29707de2010-03-03 05:29:13 +0000747 // Collect all the mul operands in a loop, along with their associated loops.
748 // Iterate in reverse so that constants are emitted last, all else equal.
749 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
750 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
751 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000752 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman2bca4d92005-07-30 00:12:19 +0000753
Dan Gohman29707de2010-03-03 05:29:13 +0000754 // Sort by loop. Use a stable sort so that constants follow non-constants.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000755 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
Dan Gohman29707de2010-03-03 05:29:13 +0000756
757 // Emit instructions to mul all the operands. Hoist as much as possible
758 // out of loops.
Craig Topper9f008862014-04-15 04:59:12 +0000759 Value *Prod = nullptr;
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000760 for (const auto &I : OpsAndLoops) {
761 const SCEV *Op = I.second;
Dan Gohman29707de2010-03-03 05:29:13 +0000762 if (!Prod) {
763 // This is the first operand. Just expand it.
764 Prod = expand(Op);
Dan Gohman29707de2010-03-03 05:29:13 +0000765 } else if (Op->isAllOnesValue()) {
766 // Instead of doing a multiply by negative one, just do a negate.
767 Prod = InsertNoopCastOfTo(Prod, Ty);
768 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
Dan Gohman29707de2010-03-03 05:29:13 +0000769 } else {
770 // A simple mul.
771 Value *W = expandCodeFor(Op, Ty);
772 Prod = InsertNoopCastOfTo(Prod, Ty);
773 // Canonicalize a constant to the RHS.
774 if (isa<Constant>(Prod)) std::swap(Prod, W);
Jingyue Wu6f72aed2015-06-24 19:28:40 +0000775 const APInt *RHS;
776 if (match(W, m_Power2(RHS))) {
777 // Canonicalize Prod*(1<<C) to Prod<<C.
778 assert(!Ty->isVectorTy() && "vector types are not SCEVable");
779 Prod = InsertBinop(Instruction::Shl, Prod,
780 ConstantInt::get(Ty, RHS->logBase2()));
781 } else {
782 Prod = InsertBinop(Instruction::Mul, Prod, W);
783 }
Dan Gohman29707de2010-03-03 05:29:13 +0000784 }
Dan Gohman0a40ad92009-04-16 03:18:22 +0000785 }
786
Dan Gohman29707de2010-03-03 05:29:13 +0000787 return Prod;
Nate Begeman2bca4d92005-07-30 00:12:19 +0000788}
789
Dan Gohman056857a2009-04-18 17:56:28 +0000790Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000791 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +0000792
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000793 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman056857a2009-04-18 17:56:28 +0000794 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000795 const APInt &RHS = SC->getAPInt();
Nick Lewycky3c947042008-07-08 05:05:37 +0000796 if (RHS.isPowerOf2())
797 return InsertBinop(Instruction::LShr, LHS,
Owen Andersonedb4a702009-07-24 23:12:02 +0000798 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky3c947042008-07-08 05:05:37 +0000799 }
800
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000801 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman830fd382009-06-27 21:18:18 +0000802 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky3c947042008-07-08 05:05:37 +0000803}
804
Dan Gohman291c2e02009-05-24 18:06:31 +0000805/// Move parts of Base into Rest to leave Base with the minimal
806/// expression that provides a pointer operand suitable for a
807/// GEP expansion.
Dan Gohmanaf752342009-07-07 17:06:11 +0000808static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman291c2e02009-05-24 18:06:31 +0000809 ScalarEvolution &SE) {
810 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
811 Base = A->getStart();
812 Rest = SE.getAddExpr(Rest,
Dan Gohman1d2ded72010-05-03 22:09:21 +0000813 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman291c2e02009-05-24 18:06:31 +0000814 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000815 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000816 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman291c2e02009-05-24 18:06:31 +0000817 }
818 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
819 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohmanaf752342009-07-07 17:06:11 +0000820 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman291c2e02009-05-24 18:06:31 +0000821 NewAddOps.back() = Rest;
822 Rest = SE.getAddExpr(NewAddOps);
823 ExposePointerBase(Base, Rest, SE);
824 }
825}
826
Andrew Trick7fb669a2011-10-07 23:46:21 +0000827/// Determine if this is a well-behaved chain of instructions leading back to
828/// the PHI. If so, it may be reused by expanded expressions.
829bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
830 const Loop *L) {
831 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
832 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
833 return false;
834 // If any of the operands don't dominate the insert position, bail.
835 // Addrec operands are always loop-invariant, so this can only happen
836 // if there are instructions which haven't been hoisted.
837 if (L == IVIncInsertLoop) {
838 for (User::op_iterator OI = IncV->op_begin()+1,
839 OE = IncV->op_end(); OI != OE; ++OI)
840 if (Instruction *OInst = dyn_cast<Instruction>(OI))
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000841 if (!SE.DT.dominates(OInst, IVIncInsertPos))
Andrew Trick7fb669a2011-10-07 23:46:21 +0000842 return false;
843 }
844 // Advance to the next instruction.
845 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
846 if (!IncV)
847 return false;
848
849 if (IncV->mayHaveSideEffects())
850 return false;
851
852 if (IncV != PN)
853 return true;
854
855 return isNormalAddRecExprPHI(PN, IncV, L);
856}
857
Andrew Trickc908b432012-01-20 07:41:13 +0000858/// getIVIncOperand returns an induction variable increment's induction
859/// variable operand.
860///
861/// If allowScale is set, any type of GEP is allowed as long as the nonIV
862/// operands dominate InsertPos.
863///
864/// If allowScale is not set, ensure that a GEP increment conforms to one of the
865/// simple patterns generated by getAddRecExprPHILiterally and
866/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
867Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
868 Instruction *InsertPos,
869 bool allowScale) {
870 if (IncV == InsertPos)
Craig Topper9f008862014-04-15 04:59:12 +0000871 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000872
873 switch (IncV->getOpcode()) {
874 default:
Craig Topper9f008862014-04-15 04:59:12 +0000875 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000876 // Check for a simple Add/Sub or GEP of a loop invariant step.
877 case Instruction::Add:
878 case Instruction::Sub: {
879 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000880 if (!OInst || SE.DT.dominates(OInst, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000881 return dyn_cast<Instruction>(IncV->getOperand(0));
Craig Topper9f008862014-04-15 04:59:12 +0000882 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000883 }
884 case Instruction::BitCast:
885 return dyn_cast<Instruction>(IncV->getOperand(0));
886 case Instruction::GetElementPtr:
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000887 for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) {
Andrew Trickc908b432012-01-20 07:41:13 +0000888 if (isa<Constant>(*I))
889 continue;
890 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000891 if (!SE.DT.dominates(OInst, InsertPos))
Craig Topper9f008862014-04-15 04:59:12 +0000892 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000893 }
894 if (allowScale) {
895 // allow any kind of GEP as long as it can be hoisted.
896 continue;
897 }
898 // This must be a pointer addition of constants (pretty), which is already
899 // handled, or some number of address-size elements (ugly). Ugly geps
900 // have 2 operands. i1* is used by the expander to represent an
901 // address-size element.
902 if (IncV->getNumOperands() != 2)
Craig Topper9f008862014-04-15 04:59:12 +0000903 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000904 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
905 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
906 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
Craig Topper9f008862014-04-15 04:59:12 +0000907 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000908 break;
909 }
910 return dyn_cast<Instruction>(IncV->getOperand(0));
911 }
912}
913
Geoff Berry0c095172016-06-01 20:03:09 +0000914/// If the insert point of the current builder or any of the builders on the
915/// stack of saved builders has 'I' as its insert point, update it to point to
916/// the instruction after 'I'. This is intended to be used when the instruction
917/// 'I' is being moved. If this fixup is not done and 'I' is moved to a
918/// different block, the inconsistent insert point (with a mismatched
919/// Instruction and Block) can lead to an instruction being inserted in a block
920/// other than its parent.
921void SCEVExpander::fixupInsertPoints(Instruction *I) {
922 BasicBlock::iterator It(*I);
923 BasicBlock::iterator NewInsertPt = std::next(It);
924 if (Builder.GetInsertPoint() == It)
925 Builder.SetInsertPoint(&*NewInsertPt);
926 for (auto *InsertPtGuard : InsertPointGuards)
927 if (InsertPtGuard->GetInsertPoint() == It)
928 InsertPtGuard->SetInsertPoint(NewInsertPt);
929}
930
Andrew Trickc908b432012-01-20 07:41:13 +0000931/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
932/// it available to other uses in this loop. Recursively hoist any operands,
933/// until we reach a value that dominates InsertPos.
934bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000935 if (SE.DT.dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000936 return true;
937
938 // InsertPos must itself dominate IncV so that IncV's new position satisfies
939 // its existing users.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000940 if (isa<PHINode>(InsertPos) ||
941 !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
Andrew Trickc908b432012-01-20 07:41:13 +0000942 return false;
943
Sanjoy Dasb771eb62015-12-08 00:13:17 +0000944 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
945 return false;
946
Andrew Trickc908b432012-01-20 07:41:13 +0000947 // Check that the chain of IV operands leading back to Phi can be hoisted.
948 SmallVector<Instruction*, 4> IVIncs;
949 for(;;) {
950 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
951 if (!Oper)
952 return false;
953 // IncV is safe to hoist.
954 IVIncs.push_back(IncV);
955 IncV = Oper;
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000956 if (SE.DT.dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000957 break;
958 }
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000959 for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) {
Geoff Berry0c095172016-06-01 20:03:09 +0000960 fixupInsertPoints(*I);
Andrew Trickc908b432012-01-20 07:41:13 +0000961 (*I)->moveBefore(InsertPos);
962 }
963 return true;
964}
965
Andrew Trick7fb669a2011-10-07 23:46:21 +0000966/// Determine if this cyclic phi is in a form that would have been generated by
967/// LSR. We don't care if the phi was actually expanded in this pass, as long
968/// as it is in a low-cost form, for example, no implied multiplication. This
969/// should match any patterns generated by getAddRecExprPHILiterally and
970/// expandAddtoGEP.
971bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trickfd4ca0f2011-10-15 06:19:55 +0000972 const Loop *L) {
Andrew Trickc908b432012-01-20 07:41:13 +0000973 for(Instruction *IVOper = IncV;
974 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
975 /*allowScale=*/false));) {
976 if (IVOper == PN)
977 return true;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000978 }
Andrew Trickc908b432012-01-20 07:41:13 +0000979 return false;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000980}
981
Andrew Trickceafa2c2011-11-30 06:07:54 +0000982/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
983/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
984/// need to materialize IV increments elsewhere to handle difficult situations.
985Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
986 Type *ExpandTy, Type *IntTy,
987 bool useSubtract) {
988 Value *IncV;
989 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
990 if (ExpandTy->isPointerTy()) {
991 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
992 // If the step isn't constant, don't use an implicitly scaled GEP, because
993 // that would require a multiply inside the loop.
994 if (!isa<ConstantInt>(StepV))
995 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
996 GEPPtrTy->getAddressSpace());
997 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
998 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
999 if (IncV->getType() != PN->getType()) {
1000 IncV = Builder.CreateBitCast(IncV, PN->getType());
1001 rememberInstruction(IncV);
1002 }
1003 } else {
1004 IncV = useSubtract ?
1005 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1006 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1007 rememberInstruction(IncV);
1008 }
1009 return IncV;
1010}
1011
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001012/// \brief Hoist the addrec instruction chain rooted in the loop phi above the
1013/// position. This routine assumes that this is possible (has been checked).
Geoff Berry0c095172016-06-01 20:03:09 +00001014void SCEVExpander::hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
1015 Instruction *Pos, PHINode *LoopPhi) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001016 do {
1017 if (DT->dominates(InstToHoist, Pos))
1018 break;
1019 // Make sure the increment is where we want it. But don't move it
1020 // down past a potential existing post-inc user.
Geoff Berry0c095172016-06-01 20:03:09 +00001021 fixupInsertPoints(InstToHoist);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001022 InstToHoist->moveBefore(Pos);
1023 Pos = InstToHoist;
1024 InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
1025 } while (InstToHoist != LoopPhi);
1026}
1027
1028/// \brief Check whether we can cheaply express the requested SCEV in terms of
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001029/// the available PHI SCEV by truncation and/or inversion of the step.
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001030static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1031 const SCEVAddRecExpr *Phi,
1032 const SCEVAddRecExpr *Requested,
1033 bool &InvertStep) {
1034 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1035 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1036
1037 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1038 return false;
1039
1040 // Try truncate it if necessary.
1041 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1042 if (!Phi)
1043 return false;
1044
1045 // Check whether truncation will help.
1046 if (Phi == Requested) {
1047 InvertStep = false;
1048 return true;
1049 }
1050
1051 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1052 if (SE.getAddExpr(Requested->getStart(),
1053 SE.getNegativeSCEV(Requested)) == Phi) {
1054 InvertStep = true;
1055 return true;
1056 }
1057
1058 return false;
1059}
1060
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001061static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1062 if (!isa<IntegerType>(AR->getType()))
1063 return false;
1064
1065 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1066 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1067 const SCEV *Step = AR->getStepRecurrence(SE);
1068 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1069 SE.getSignExtendExpr(AR, WideTy));
1070 const SCEV *ExtendAfterOp =
1071 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1072 return ExtendAfterOp == OpAfterExtend;
1073}
1074
1075static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1076 if (!isa<IntegerType>(AR->getType()))
1077 return false;
1078
1079 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1080 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1081 const SCEV *Step = AR->getStepRecurrence(SE);
1082 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1083 SE.getZeroExtendExpr(AR, WideTy));
1084 const SCEV *ExtendAfterOp =
1085 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1086 return ExtendAfterOp == OpAfterExtend;
1087}
1088
Dan Gohman51ad99d2010-01-21 02:09:26 +00001089/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1090/// the base addrec, which is the addrec without any non-loop-dominating
1091/// values, and return the PHI.
1092PHINode *
1093SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1094 const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001095 Type *ExpandTy,
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001096 Type *IntTy,
1097 Type *&TruncTy,
1098 bool &InvertStep) {
Benjamin Kramera7606b992011-07-16 22:26:27 +00001099 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trick244e2c32011-07-16 00:59:39 +00001100
Dan Gohman51ad99d2010-01-21 02:09:26 +00001101 // Reuse a previously-inserted PHI, if present.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001102 BasicBlock *LatchBlock = L->getLoopLatch();
1103 if (LatchBlock) {
Craig Topper9f008862014-04-15 04:59:12 +00001104 PHINode *AddRecPhiMatch = nullptr;
1105 Instruction *IncV = nullptr;
1106 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001107 InvertStep = false;
1108
1109 // Only try partially matching scevs that need truncation and/or
1110 // step-inversion if we know this loop is outside the current loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001111 bool TryNonMatchingSCEV =
1112 IVIncInsertLoop &&
1113 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001114
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00001115 for (auto &I : *L->getHeader()) {
1116 auto *PN = dyn_cast<PHINode>(&I);
1117 if (!PN || !SE.isSCEVable(PN->getType()))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001118 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001119
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001120 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
1121 if (!PhiSCEV)
1122 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001123
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001124 bool IsMatchingSCEV = PhiSCEV == Normalized;
1125 // We only handle truncation and inversion of phi recurrences for the
1126 // expanded expression if the expanded expression's loop dominates the
1127 // loop we insert to. Check now, so we can bail out early.
1128 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1129 continue;
1130
1131 Instruction *TempIncV =
1132 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1133
1134 // Check whether we can reuse this PHI node.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001135 if (LSRMode) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001136 if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001137 continue;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001138 if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1139 continue;
1140 } else {
1141 if (!isNormalAddRecExprPHI(PN, TempIncV, L))
Andrew Trickc908b432012-01-20 07:41:13 +00001142 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001143 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001144
1145 // Stop if we have found an exact match SCEV.
1146 if (IsMatchingSCEV) {
1147 IncV = TempIncV;
Craig Topper9f008862014-04-15 04:59:12 +00001148 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001149 InvertStep = false;
1150 AddRecPhiMatch = PN;
1151 break;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001152 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001153
1154 // Try whether the phi can be translated into the requested form
1155 // (truncated and/or offset by a constant).
1156 if ((!TruncTy || InvertStep) &&
1157 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1158 // Record the phi node. But don't stop we might find an exact match
1159 // later.
1160 AddRecPhiMatch = PN;
1161 IncV = TempIncV;
1162 TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1163 }
1164 }
1165
1166 if (AddRecPhiMatch) {
1167 // Potentially, move the increment. We have made sure in
1168 // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1169 if (L == IVIncInsertLoop)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001170 hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001171
Andrew Trick7fb669a2011-10-07 23:46:21 +00001172 // Ok, the add recurrence looks usable.
1173 // Remember this PHI, even in post-inc mode.
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001174 InsertedValues.insert(AddRecPhiMatch);
Andrew Trick7fb669a2011-10-07 23:46:21 +00001175 // Remember the increment.
1176 rememberInstruction(IncV);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001177 return AddRecPhiMatch;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001178 }
1179 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001180
1181 // Save the original insertion point so we can restore it when we're done.
Geoff Berry0c095172016-06-01 20:03:09 +00001182 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001183
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001184 // Another AddRec may need to be recursively expanded below. For example, if
1185 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1186 // loop. Remove this loop from the PostIncLoops set before expanding such
1187 // AddRecs. Otherwise, we cannot find a valid position for the step
1188 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1189 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1190 // so it's not worth implementing SmallPtrSet::swap.
1191 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1192 PostIncLoops.clear();
1193
Dan Gohman51ad99d2010-01-21 02:09:26 +00001194 // Expand code for the start value.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001195 Value *StartV =
1196 expandCodeFor(Normalized->getStart(), ExpandTy, &L->getHeader()->front());
Dan Gohman51ad99d2010-01-21 02:09:26 +00001197
Andrew Trick244e2c32011-07-16 00:59:39 +00001198 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramera7606b992011-07-16 22:26:27 +00001199 assert(!isa<Instruction>(StartV) ||
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001200 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1201 L->getHeader()));
Andrew Trick244e2c32011-07-16 00:59:39 +00001202
Andrew Trickceafa2c2011-11-30 06:07:54 +00001203 // Expand code for the step value. Do this before creating the PHI so that PHI
1204 // reuse code doesn't see an incomplete PHI.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001205 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001206 // If the stride is negative, insert a sub instead of an add for the increment
1207 // (unless it's a constant, because subtracts of constants are canonicalized
1208 // to adds).
Andrew Trick881a7762012-01-07 00:27:31 +00001209 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001210 if (useSubtract)
Dan Gohman51ad99d2010-01-21 02:09:26 +00001211 Step = SE.getNegativeSCEV(Step);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001212 // Expand the step somewhere that dominates the loop header.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001213 Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
Dan Gohman51ad99d2010-01-21 02:09:26 +00001214
Sanjoy Das54ef8952015-02-26 19:51:35 +00001215 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1216 // we actually do emit an addition. It does not apply if we emit a
1217 // subtraction.
1218 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1219 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1220
Dan Gohman51ad99d2010-01-21 02:09:26 +00001221 // Create the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001222 BasicBlock *Header = L->getHeader();
1223 Builder.SetInsertPoint(Header, Header->begin());
1224 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick411daa52011-06-28 05:07:32 +00001225 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trick154d78a2011-06-28 05:41:52 +00001226 Twine(IVName) + ".iv");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001227 rememberInstruction(PN);
1228
1229 // Create the step instructions and populate the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001230 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001231 BasicBlock *Pred = *HPI;
1232
1233 // Add a start value.
1234 if (!L->contains(Pred)) {
1235 PN->addIncoming(StartV, Pred);
1236 continue;
1237 }
1238
Andrew Trickceafa2c2011-11-30 06:07:54 +00001239 // Create a step value and add it to the PHI.
1240 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1241 // instructions at IVIncInsertPos.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001242 Instruction *InsertPos = L == IVIncInsertLoop ?
1243 IVIncInsertPos : Pred->getTerminator();
Devang Patelc3239d32011-07-05 21:48:22 +00001244 Builder.SetInsertPoint(InsertPos);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001245 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001246
Andrew Trick8eaae282013-07-14 02:50:07 +00001247 if (isa<OverflowingBinaryOperator>(IncV)) {
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001248 if (IncrementIsNUW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001249 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001250 if (IncrementIsNSW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001251 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1252 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001253 PN->addIncoming(IncV, Pred);
1254 }
1255
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001256 // After expanding subexpressions, restore the PostIncLoops set so the caller
1257 // can ensure that IVIncrement dominates the current uses.
1258 PostIncLoops = SavedPostIncLoops;
1259
Dan Gohman51ad99d2010-01-21 02:09:26 +00001260 // Remember this PHI, even in post-inc mode.
1261 InsertedValues.insert(PN);
1262
1263 return PN;
1264}
1265
1266Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001267 Type *STy = S->getType();
1268 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001269 const Loop *L = S->getLoop();
1270
1271 // Determine a normalized form of this expression, which is the expression
1272 // before any post-inc adjustment is made.
1273 const SCEVAddRecExpr *Normalized = S;
Dan Gohmand006ab92010-04-07 22:27:08 +00001274 if (PostIncLoops.count(L)) {
1275 PostIncLoopSet Loops;
1276 Loops.insert(L);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001277 Normalized = cast<SCEVAddRecExpr>(TransformForPostIncUse(
1278 Normalize, S, nullptr, nullptr, Loops, SE, SE.DT));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001279 }
1280
1281 // Strip off any non-loop-dominating component from the addrec start.
1282 const SCEV *Start = Normalized->getStart();
Craig Topper9f008862014-04-15 04:59:12 +00001283 const SCEV *PostLoopOffset = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001284 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001285 PostLoopOffset = Start;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001286 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick8b55b732011-03-14 16:50:06 +00001287 Normalized = cast<SCEVAddRecExpr>(
1288 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1289 Normalized->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001290 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001291 }
1292
1293 // Strip off any non-loop-dominating component from the addrec step.
1294 const SCEV *Step = Normalized->getStepRecurrence(SE);
Craig Topper9f008862014-04-15 04:59:12 +00001295 const SCEV *PostLoopScale = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001296 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001297 PostLoopScale = Step;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001298 Step = SE.getConstant(Normalized->getType(), 1);
Keno Fischer1efc3b72016-07-13 01:28:12 +00001299 if (!Start->isZero()) {
1300 // The normalization below assumes that Start is constant zero, so if
1301 // it isn't re-associate Start to PostLoopOffset.
1302 assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?");
1303 PostLoopOffset = Start;
1304 Start = SE.getConstant(Normalized->getType(), 0);
1305 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001306 Normalized =
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001307 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1308 Start, Step, Normalized->getLoop(),
1309 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001310 }
1311
1312 // Expand the core addrec. If we need post-loop scaling, force it to
1313 // expand to an integer type to avoid the need for additional casting.
Chris Lattner229907c2011-07-18 04:54:35 +00001314 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001315 // In some cases, we decide to reuse an existing phi node but need to truncate
1316 // it and/or invert the step.
Craig Topper9f008862014-04-15 04:59:12 +00001317 Type *TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001318 bool InvertStep = false;
1319 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
1320 TruncTy, InvertStep);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001321
Dan Gohman8b0a4192010-03-01 17:49:51 +00001322 // Accommodate post-inc mode, if necessary.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001323 Value *Result;
Dan Gohmand006ab92010-04-07 22:27:08 +00001324 if (!PostIncLoops.count(L))
Dan Gohman51ad99d2010-01-21 02:09:26 +00001325 Result = PN;
1326 else {
1327 // In PostInc mode, use the post-incremented value.
1328 BasicBlock *LatchBlock = L->getLoopLatch();
1329 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1330 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick870c1a32011-10-13 21:55:29 +00001331
1332 // For an expansion to use the postinc form, the client must call
1333 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1334 // or dominated by IVIncInsertPos.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001335 if (isa<Instruction>(Result) &&
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001336 !SE.DT.dominates(cast<Instruction>(Result),
1337 &*Builder.GetInsertPoint())) {
Andrew Trickceafa2c2011-11-30 06:07:54 +00001338 // The induction variable's postinc expansion does not dominate this use.
1339 // IVUsers tries to prevent this case, so it is rare. However, it can
1340 // happen when an IVUser outside the loop is not dominated by the latch
1341 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1342 // all cases. Consider a phi outide whose operand is replaced during
1343 // expansion with the value of the postinc user. Without fundamentally
1344 // changing the way postinc users are tracked, the only remedy is
1345 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1346 // but hopefully expandCodeFor handles that.
1347 bool useSubtract =
Andrew Trick881a7762012-01-07 00:27:31 +00001348 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001349 if (useSubtract)
1350 Step = SE.getNegativeSCEV(Step);
Benjamin Kramer6e931522013-09-30 15:40:17 +00001351 Value *StepV;
1352 {
1353 // Expand the step somewhere that dominates the loop header.
Geoff Berry0c095172016-06-01 20:03:09 +00001354 SCEVInsertPointGuard Guard(Builder, this);
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001355 StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
Benjamin Kramer6e931522013-09-30 15:40:17 +00001356 }
Andrew Trickceafa2c2011-11-30 06:07:54 +00001357 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1358 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001359 }
1360
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001361 // We have decided to reuse an induction variable of a dominating loop. Apply
1362 // truncation and/or invertion of the step.
1363 if (TruncTy) {
1364 Type *ResTy = Result->getType();
1365 // Normalize the result type.
1366 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1367 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1368 // Truncate the result.
1369 if (TruncTy != Result->getType()) {
1370 Result = Builder.CreateTrunc(Result, TruncTy);
1371 rememberInstruction(Result);
1372 }
1373 // Invert the result.
1374 if (InvertStep) {
1375 Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1376 Result);
1377 rememberInstruction(Result);
1378 }
1379 }
1380
Dan Gohman51ad99d2010-01-21 02:09:26 +00001381 // Re-apply any non-loop-dominating scale.
1382 if (PostLoopScale) {
Andrew Trick57243da2013-10-25 21:35:56 +00001383 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
Dan Gohman1a8674e2010-02-12 20:39:25 +00001384 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001385 Result = Builder.CreateMul(Result,
1386 expandCodeFor(PostLoopScale, IntTy));
1387 rememberInstruction(Result);
1388 }
1389
1390 // Re-apply any non-loop-dominating offset.
1391 if (PostLoopOffset) {
Chris Lattner229907c2011-07-18 04:54:35 +00001392 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001393 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1394 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1395 } else {
Dan Gohman1a8674e2010-02-12 20:39:25 +00001396 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001397 Result = Builder.CreateAdd(Result,
1398 expandCodeFor(PostLoopOffset, IntTy));
1399 rememberInstruction(Result);
1400 }
1401 }
1402
1403 return Result;
1404}
1405
Dan Gohman056857a2009-04-18 17:56:28 +00001406Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001407 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1408
Chris Lattner229907c2011-07-18 04:54:35 +00001409 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +00001410 const Loop *L = S->getLoop();
Nate Begeman2bca4d92005-07-30 00:12:19 +00001411
Dan Gohman426901a2009-06-13 16:25:49 +00001412 // First check for an existing canonical IV in a suitable type.
Craig Topper9f008862014-04-15 04:59:12 +00001413 PHINode *CanonicalIV = nullptr;
Dan Gohman426901a2009-06-13 16:25:49 +00001414 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman31158752010-07-20 16:46:58 +00001415 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman426901a2009-06-13 16:25:49 +00001416 CanonicalIV = PN;
1417
1418 // Rewrite an AddRec in terms of the canonical induction variable, if
1419 // its type is more narrow.
1420 if (CanonicalIV &&
1421 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1422 SE.getTypeSizeInBits(Ty)) {
Dan Gohman00524492010-03-18 01:17:13 +00001423 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1424 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1425 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00001426 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001427 S->getNoWrapFlags(SCEV::FlagNW)));
David Majnemer235acde2015-10-27 19:48:28 +00001428 BasicBlock::iterator NewInsertPt =
1429 findInsertPointAfter(cast<Instruction>(V), Builder.GetInsertBlock());
Craig Topper9f008862014-04-15 04:59:12 +00001430 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001431 &*NewInsertPt);
Dan Gohman426901a2009-06-13 16:25:49 +00001432 return V;
1433 }
1434
Nate Begeman2bca4d92005-07-30 00:12:19 +00001435 // {X,+,F} --> X + {0,+,F}
Dan Gohmanbe928e32008-06-18 16:23:07 +00001436 if (!S->getStart()->isZero()) {
Dan Gohman00524492010-03-18 01:17:13 +00001437 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohman1d2ded72010-05-03 22:09:21 +00001438 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001439 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1440 S->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +00001441
1442 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1443 // comments on expandAddToGEP for details.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001444 const SCEV *Base = S->getStart();
1445 const SCEV *RestArray[1] = { Rest };
1446 // Dig into the expression to find the pointer base for a GEP.
1447 ExposePointerBase(Base, RestArray[0], SE);
1448 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattner229907c2011-07-18 04:54:35 +00001449 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001450 // Make sure the Base isn't something exotic, such as a multiplied
1451 // or divided pointer value. In those cases, the result type isn't
1452 // actually a pointer type.
1453 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1454 Value *StartV = expand(Base);
1455 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1456 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman291c2e02009-05-24 18:06:31 +00001457 }
1458 }
1459
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001460 // Just do a normal add. Pre-expand the operands to suppress folding.
Patrik Hagglund96f13af2016-06-20 10:19:04 +00001461 //
1462 // The LHS and RHS values are factored out of the expand call to make the
1463 // output independent of the argument evaluation order.
1464 const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1465 const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1466 return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001467 }
1468
Dan Gohmancd838702010-07-26 18:28:14 +00001469 // If we don't yet have a canonical IV, create one.
1470 if (!CanonicalIV) {
Nate Begeman2bca4d92005-07-30 00:12:19 +00001471 // Create and insert the PHI node for the induction variable in the
1472 // specified loop.
1473 BasicBlock *Header = L->getHeader();
Jay Foade0938d82011-03-30 11:19:20 +00001474 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad52131342011-03-30 11:28:46 +00001475 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001476 &Header->front());
Dan Gohmancd838702010-07-26 18:28:14 +00001477 rememberInstruction(CanonicalIV);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001478
Hal Finkel3f5279c2013-08-18 00:16:23 +00001479 SmallSet<BasicBlock *, 4> PredSeen;
Owen Andersonedb4a702009-07-24 23:12:02 +00001480 Constant *One = ConstantInt::get(Ty, 1);
Jay Foade0938d82011-03-30 11:19:20 +00001481 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greife82532a2010-07-09 15:40:10 +00001482 BasicBlock *HP = *HPI;
David Blaikie70573dc2014-11-19 07:49:26 +00001483 if (!PredSeen.insert(HP).second) {
Hal Finkel36eff0f2014-07-31 19:13:38 +00001484 // There must be an incoming value for each predecessor, even the
1485 // duplicates!
1486 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
Hal Finkel3f5279c2013-08-18 00:16:23 +00001487 continue;
Hal Finkel36eff0f2014-07-31 19:13:38 +00001488 }
Hal Finkel3f5279c2013-08-18 00:16:23 +00001489
Gabor Greife82532a2010-07-09 15:40:10 +00001490 if (L->contains(HP)) {
Dan Gohman510bffc2010-01-19 22:26:02 +00001491 // Insert a unit add instruction right before the terminator
1492 // corresponding to the back-edge.
Dan Gohmancd838702010-07-26 18:28:14 +00001493 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1494 "indvar.next",
1495 HP->getTerminator());
Devang Patelccf8dbf2011-06-22 20:56:56 +00001496 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohman51ad99d2010-01-21 02:09:26 +00001497 rememberInstruction(Add);
Dan Gohmancd838702010-07-26 18:28:14 +00001498 CanonicalIV->addIncoming(Add, HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001499 } else {
Dan Gohmancd838702010-07-26 18:28:14 +00001500 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001501 }
Gabor Greife82532a2010-07-09 15:40:10 +00001502 }
Nate Begeman2bca4d92005-07-30 00:12:19 +00001503 }
1504
Dan Gohmancd838702010-07-26 18:28:14 +00001505 // {0,+,1} --> Insert a canonical induction variable into the loop!
1506 if (S->isAffine() && S->getOperand(1)->isOne()) {
1507 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1508 "IVs with types different from the canonical IV should "
1509 "already have been handled!");
1510 return CanonicalIV;
1511 }
1512
Dan Gohman426901a2009-06-13 16:25:49 +00001513 // {0,+,F} --> {0,+,1} * F
Nate Begeman2bca4d92005-07-30 00:12:19 +00001514
Chris Lattnerf0b77f92005-10-30 06:24:33 +00001515 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001516 if (S->isAffine()) // {0,+,F} --> i*F
1517 return
1518 expand(SE.getTruncateOrNoop(
Dan Gohmancd838702010-07-26 18:28:14 +00001519 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001520 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohmancd838702010-07-26 18:28:14 +00001521 CanonicalIV->getType())),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001522 Ty));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001523
1524 // If this is a chain of recurrences, turn it into a closed form, using the
1525 // folders, then expandCodeFor the closed form. This allows the folders to
1526 // simplify the expression without having to build a bunch of special code
1527 // into this folder.
Dan Gohmancd838702010-07-26 18:28:14 +00001528 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman2bca4d92005-07-30 00:12:19 +00001529
Dan Gohman426901a2009-06-13 16:25:49 +00001530 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohmanaf752342009-07-07 17:06:11 +00001531 const SCEV *NewS = S;
Dan Gohmancd838702010-07-26 18:28:14 +00001532 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman426901a2009-06-13 16:25:49 +00001533 if (isa<SCEVAddRecExpr>(Ext))
1534 NewS = Ext;
1535
Dan Gohmanaf752342009-07-07 17:06:11 +00001536 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlingf3baad32006-12-07 01:30:32 +00001537 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman2bca4d92005-07-30 00:12:19 +00001538
Dan Gohman426901a2009-06-13 16:25:49 +00001539 // Truncate the result down to the original type, if needed.
Dan Gohmanaf752342009-07-07 17:06:11 +00001540 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohmanfd761132009-06-22 22:08:45 +00001541 return expand(T);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001542}
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001543
Dan Gohman056857a2009-04-18 17:56:28 +00001544Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001545 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001546 Value *V = expandCodeFor(S->getOperand(),
1547 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001548 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001549 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001550 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001551}
1552
Dan Gohman056857a2009-04-18 17:56:28 +00001553Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001554 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001555 Value *V = expandCodeFor(S->getOperand(),
1556 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001557 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001558 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001559 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001560}
1561
Dan Gohman056857a2009-04-18 17:56:28 +00001562Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001563 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001564 Value *V = expandCodeFor(S->getOperand(),
1565 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001566 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001567 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001568 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001569}
1570
Dan Gohman056857a2009-04-18 17:56:28 +00001571Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001572 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001573 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001574 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1575 // In the case of mixed integer and pointer types, do the
1576 // rest of the comparisons as integer.
1577 if (S->getOperand(i)->getType() != Ty) {
1578 Ty = SE.getEffectiveSCEVType(Ty);
1579 LHS = InsertNoopCastOfTo(LHS, Ty);
1580 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001581 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001582 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001583 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001584 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001585 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001586 LHS = Sel;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001587 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001588 // In the case of mixed integer and pointer types, cast the
1589 // final result back to the pointer type.
1590 if (LHS->getType() != S->getType())
1591 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001592 return LHS;
1593}
1594
Dan Gohman056857a2009-04-18 17:56:28 +00001595Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001596 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001597 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001598 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1599 // In the case of mixed integer and pointer types, do the
1600 // rest of the comparisons as integer.
1601 if (S->getOperand(i)->getType() != Ty) {
1602 Ty = SE.getEffectiveSCEVType(Ty);
1603 LHS = InsertNoopCastOfTo(LHS, Ty);
1604 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001605 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001606 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001607 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001608 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001609 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001610 LHS = Sel;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001611 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001612 // In the case of mixed integer and pointer types, cast the
1613 // final result back to the pointer type.
1614 if (LHS->getType() != S->getType())
1615 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001616 return LHS;
1617}
1618
Chris Lattner229907c2011-07-18 04:54:35 +00001619Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickc908b432012-01-20 07:41:13 +00001620 Instruction *IP) {
Geoff Berryd0182802016-08-11 21:05:17 +00001621 setInsertPoint(IP);
Dan Gohman89d4e3c2010-03-19 21:51:03 +00001622 return expandCodeFor(SH, Ty);
1623}
1624
Chris Lattner229907c2011-07-18 04:54:35 +00001625Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman0e4cf892008-06-22 19:09:18 +00001626 // Expand the code for this SCEV.
Dan Gohman0a40ad92009-04-16 03:18:22 +00001627 Value *V = expand(SH);
Dan Gohman26494912009-05-19 02:15:55 +00001628 if (Ty) {
1629 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1630 "non-trivial casts should be done with the SCEVs directly!");
1631 V = InsertNoopCastOfTo(V, Ty);
1632 }
1633 return V;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001634}
1635
Wei Mi785858c2016-08-09 20:37:50 +00001636ScalarEvolution::ValueOffsetPair
1637SCEVExpander::FindValueInExprValueMap(const SCEV *S,
1638 const Instruction *InsertPt) {
1639 SetVector<ScalarEvolution::ValueOffsetPair> *Set = SE.getSCEVValues(S);
Junmo Park6ebdc142016-02-16 06:46:58 +00001640 // If the expansion is not in CanonicalMode, and the SCEV contains any
1641 // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1642 if (CanonicalMode || !SE.containsAddRecurrence(S)) {
1643 // If S is scConstant, it may be worse to reuse an existing Value.
1644 if (S->getSCEVType() != scConstant && Set) {
1645 // Choose a Value from the set which dominates the insertPt.
1646 // insertPt should be inside the Value's parent loop so as not to break
1647 // the LCSSA form.
Wei Mi785858c2016-08-09 20:37:50 +00001648 for (auto const &VOPair : *Set) {
1649 Value *V = VOPair.first;
1650 ConstantInt *Offset = VOPair.second;
Junmo Park6ebdc142016-02-16 06:46:58 +00001651 Instruction *EntInst = nullptr;
Wei Mi785858c2016-08-09 20:37:50 +00001652 if (V && isa<Instruction>(V) && (EntInst = cast<Instruction>(V)) &&
1653 S->getType() == V->getType() &&
Junmo Park6ebdc142016-02-16 06:46:58 +00001654 EntInst->getFunction() == InsertPt->getFunction() &&
1655 SE.DT.dominates(EntInst, InsertPt) &&
1656 (SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
Wei Mi785858c2016-08-09 20:37:50 +00001657 SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
1658 return {V, Offset};
Junmo Park6ebdc142016-02-16 06:46:58 +00001659 }
1660 }
1661 }
Wei Mi785858c2016-08-09 20:37:50 +00001662 return {nullptr, nullptr};
Junmo Park6ebdc142016-02-16 06:46:58 +00001663}
1664
Wei Mia49559b2016-02-04 01:27:38 +00001665// The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1666// or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1667// and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1668// literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1669// the expansion will try to reuse Value from ExprValueMap, and only when it
1670// fails, expand the SCEV literally.
Dan Gohman056857a2009-04-18 17:56:28 +00001671Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001672 // Compute an insertion point for this SCEV object. Hoist the instructions
1673 // as far out in the loop nest as possible.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001674 Instruction *InsertPt = &*Builder.GetInsertPoint();
Sanjoy Dase30a2812016-11-10 07:56:09 +00001675 if (!isa<SCEVUDivExpr>(S)) {
1676 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1677 L = L->getParentLoop())
1678 if (SE.isLoopInvariant(S, L)) {
1679 if (!L)
1680 break;
1681 if (BasicBlock *Preheader = L->getLoopPreheader())
1682 InsertPt = Preheader->getTerminator();
1683 else {
1684 // LSR sets the insertion point for AddRec start/step values to the
1685 // block start to simplify value reuse, even though it's an invalid
1686 // position. SCEVExpander must correct for this in all cases.
1687 InsertPt = &*L->getHeader()->getFirstInsertionPt();
1688 }
1689 } else {
1690 // If the SCEV is computable at this level, insert it into the header
1691 // after the PHIs (and after any other instructions that we've inserted
1692 // there) so that it is guaranteed to dominate any user inside the loop.
1693 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1694 InsertPt = &*L->getHeader()->getFirstInsertionPt();
1695 while (InsertPt->getIterator() != Builder.GetInsertPoint() &&
1696 (isInsertedInstruction(InsertPt) ||
1697 isa<DbgInfoIntrinsic>(InsertPt))) {
1698 InsertPt = &*std::next(InsertPt->getIterator());
1699 }
1700 break;
Andrew Trickcbcc98f2012-01-02 21:25:10 +00001701 }
Sanjoy Dase30a2812016-11-10 07:56:09 +00001702 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001703
Dan Gohmandaafbe62009-06-26 22:53:46 +00001704 // Check to see if we already expanded this here.
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00001705 auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman830fd382009-06-27 21:18:18 +00001706 if (I != InsertedExpressions.end())
Dan Gohmandaafbe62009-06-26 22:53:46 +00001707 return I->second;
Dan Gohman830fd382009-06-27 21:18:18 +00001708
Geoff Berry0c095172016-06-01 20:03:09 +00001709 SCEVInsertPointGuard Guard(Builder, this);
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001710 Builder.SetInsertPoint(InsertPt);
Dan Gohmandaafbe62009-06-26 22:53:46 +00001711
1712 // Expand the expression into instructions.
Wei Mi785858c2016-08-09 20:37:50 +00001713 ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, InsertPt);
1714 Value *V = VO.first;
Junmo Park6ebdc142016-02-16 06:46:58 +00001715
Wei Mia49559b2016-02-04 01:27:38 +00001716 if (!V)
1717 V = visit(S);
Wei Mi24662392016-09-14 04:39:50 +00001718 else if (VO.second) {
1719 if (PointerType *Vty = dyn_cast<PointerType>(V->getType())) {
1720 Type *Ety = Vty->getPointerElementType();
1721 int64_t Offset = VO.second->getSExtValue();
1722 int64_t ESize = SE.getTypeSizeInBits(Ety);
1723 if ((Offset * 8) % ESize == 0) {
1724 ConstantInt *Idx =
1725 ConstantInt::getSigned(VO.second->getType(), -(Offset * 8) / ESize);
1726 V = Builder.CreateGEP(Ety, V, Idx, "scevgep");
1727 } else {
1728 ConstantInt *Idx =
1729 ConstantInt::getSigned(VO.second->getType(), -Offset);
1730 unsigned AS = Vty->getAddressSpace();
1731 V = Builder.CreateBitCast(V, Type::getInt8PtrTy(SE.getContext(), AS));
1732 V = Builder.CreateGEP(Type::getInt8Ty(SE.getContext()), V, Idx,
1733 "uglygep");
1734 V = Builder.CreateBitCast(V, Vty);
1735 }
1736 } else {
1737 V = Builder.CreateSub(V, VO.second);
1738 }
1739 }
Dan Gohmandaafbe62009-06-26 22:53:46 +00001740 // Remember the expanded value for this SCEV at this location.
Andrew Trick870c1a32011-10-13 21:55:29 +00001741 //
1742 // This is independent of PostIncLoops. The mapped value simply materializes
1743 // the expression at this insertion point. If the mapped value happened to be
Alp Tokerf907b892013-12-05 05:44:44 +00001744 // a postinc expansion, it could be reused by a non-postinc user, but only if
Andrew Trick870c1a32011-10-13 21:55:29 +00001745 // its insertion point was already at the head of the loop.
1746 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001747 return V;
1748}
Dan Gohman63964b52009-06-05 16:35:53 +00001749
Dan Gohman6b751732010-02-14 03:12:47 +00001750void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohmanbbfb6ac2010-06-05 00:33:07 +00001751 if (!PostIncLoops.empty())
1752 InsertedPostIncValues.insert(I);
1753 else
Dan Gohman6b751732010-02-14 03:12:47 +00001754 InsertedValues.insert(I);
Dan Gohman6b751732010-02-14 03:12:47 +00001755}
1756
Dan Gohman63964b52009-06-05 16:35:53 +00001757/// getOrInsertCanonicalInductionVariable - This method returns the
1758/// canonical induction variable of the specified type for the specified
1759/// loop (inserting one if there is none). A canonical induction variable
1760/// starts at zero and steps by one on each iteration.
Dan Gohman4fd92432010-07-20 16:44:52 +00001761PHINode *
Dan Gohman63964b52009-06-05 16:35:53 +00001762SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001763 Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001764 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman31158752010-07-20 16:46:58 +00001765
1766 // Build a SCEV for {0,+,1}<L>.
Andrew Trick8b55b732011-03-14 16:50:06 +00001767 // Conservatively use FlagAnyWrap for now.
Dan Gohman1d2ded72010-05-03 22:09:21 +00001768 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick8b55b732011-03-14 16:50:06 +00001769 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman31158752010-07-20 16:46:58 +00001770
1771 // Emit code for it.
Geoff Berry0c095172016-06-01 20:03:09 +00001772 SCEVInsertPointGuard Guard(Builder, this);
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001773 PHINode *V =
1774 cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front()));
Dan Gohman31158752010-07-20 16:46:58 +00001775
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001776 return V;
Dan Gohman63964b52009-06-05 16:35:53 +00001777}
Andrew Trickf9201c52011-10-11 02:28:51 +00001778
Andrew Trickf9201c52011-10-11 02:28:51 +00001779/// replaceCongruentIVs - Check for congruent phis in this loop header and
1780/// replace them with their most canonical representative. Return the number of
1781/// phis eliminated.
1782///
1783/// This does not depend on any SCEVExpander state but should be used in
1784/// the same context that SCEVExpander is used.
1785unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Nadav Rotem4dc976f2012-10-19 21:28:43 +00001786 SmallVectorImpl<WeakVH> &DeadInsts,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001787 const TargetTransformInfo *TTI) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001788 // Find integer phis in order of increasing width.
1789 SmallVector<PHINode*, 8> Phis;
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00001790 for (auto &I : *L->getHeader()) {
1791 if (auto *PN = dyn_cast<PHINode>(&I))
1792 Phis.push_back(PN);
1793 else
1794 break;
Andrew Trick5adedf52012-01-07 01:12:09 +00001795 }
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00001796
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001797 if (TTI)
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001798 std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
1799 // Put pointers at the back and make sure pointer < pointer = false.
1800 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1801 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1802 return RHS->getType()->getPrimitiveSizeInBits() <
1803 LHS->getType()->getPrimitiveSizeInBits();
1804 });
Andrew Trick5adedf52012-01-07 01:12:09 +00001805
Andrew Trickf9201c52011-10-11 02:28:51 +00001806 unsigned NumElim = 0;
1807 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Eric Christopher572e03a2015-06-19 01:53:21 +00001808 // Process phis from wide to narrow. Map wide phis to their truncation
Andrew Trick5adedf52012-01-07 01:12:09 +00001809 // so narrow phis can reuse them.
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00001810 for (PHINode *Phi : Phis) {
Silviu Baranga308a7c72015-11-03 16:27:04 +00001811 auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1812 if (Value *V = SimplifyInstruction(PN, DL, &SE.TLI, &SE.DT, &SE.AC))
1813 return V;
1814 if (!SE.isSCEVable(PN->getType()))
1815 return nullptr;
1816 auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1817 if (!Const)
1818 return nullptr;
1819 return Const->getValue();
1820 };
1821
Benjamin Kramera225ed82012-10-19 16:37:30 +00001822 // Fold constant phis. They may be congruent to other constant phis and
1823 // would confuse the logic below that expects proper IVs.
Silviu Baranga308a7c72015-11-03 16:27:04 +00001824 if (Value *V = SimplifyPHINode(Phi)) {
1825 if (V->getType() != Phi->getType())
1826 continue;
Benjamin Kramera225ed82012-10-19 16:37:30 +00001827 Phi->replaceAllUsesWith(V);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001828 DeadInsts.emplace_back(Phi);
Benjamin Kramera225ed82012-10-19 16:37:30 +00001829 ++NumElim;
1830 DEBUG_WITH_TYPE(DebugType, dbgs()
1831 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1832 continue;
1833 }
1834
Andrew Trickf9201c52011-10-11 02:28:51 +00001835 if (!SE.isSCEVable(Phi->getType()))
1836 continue;
1837
1838 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1839 if (!OrigPhiRef) {
1840 OrigPhiRef = Phi;
Sanjoy Das0b6518d2016-05-10 00:32:31 +00001841 if (Phi->getType()->isIntegerTy() && TTI &&
1842 TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001843 // This phi can be freely truncated to the narrowest phi type. Map the
1844 // truncated expression to it so it will be reused for narrow types.
1845 const SCEV *TruncExpr =
1846 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1847 ExprToIVMap[TruncExpr] = Phi;
1848 }
Andrew Trickf9201c52011-10-11 02:28:51 +00001849 continue;
1850 }
1851
Andrew Trick5adedf52012-01-07 01:12:09 +00001852 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1853 // sense.
1854 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trickf9201c52011-10-11 02:28:51 +00001855 continue;
1856
1857 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
Sanjoy Das4e8c8032016-05-11 17:41:41 +00001858 Instruction *OrigInc = dyn_cast<Instruction>(
1859 OrigPhiRef->getIncomingValueForBlock(LatchBlock));
Andrew Trickf9201c52011-10-11 02:28:51 +00001860 Instruction *IsomorphicInc =
Sanjoy Das4e8c8032016-05-11 17:41:41 +00001861 dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
Andrew Trickf9201c52011-10-11 02:28:51 +00001862
Sanjoy Das4e8c8032016-05-11 17:41:41 +00001863 if (OrigInc && IsomorphicInc) {
1864 // If this phi has the same width but is more canonical, replace the
1865 // original with it. As part of the "more canonical" determination,
1866 // respect a prior decision to use an IV chain.
1867 if (OrigPhiRef->getType() == Phi->getType() &&
1868 !(ChainedPhis.count(Phi) ||
1869 isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
1870 (ChainedPhis.count(Phi) ||
1871 isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1872 std::swap(OrigPhiRef, Phi);
1873 std::swap(OrigInc, IsomorphicInc);
Andrew Trick5adedf52012-01-07 01:12:09 +00001874 }
Sanjoy Das4e8c8032016-05-11 17:41:41 +00001875 // Replacing the congruent phi is sufficient because acyclic
1876 // redundancy elimination, CSE/GVN, should handle the
1877 // rest. However, once SCEV proves that a phi is congruent,
1878 // it's often the head of an IV user cycle that is isomorphic
1879 // with the original phi. It's worth eagerly cleaning up the
1880 // common case of a single IV increment so that DeleteDeadPHIs
1881 // can remove cycles that had postinc uses.
1882 const SCEV *TruncExpr =
1883 SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
1884 if (OrigInc != IsomorphicInc &&
1885 TruncExpr == SE.getSCEV(IsomorphicInc) &&
1886 SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
1887 hoistIVInc(OrigInc, IsomorphicInc)) {
1888 DEBUG_WITH_TYPE(DebugType,
1889 dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1890 << *IsomorphicInc << '\n');
1891 Value *NewInc = OrigInc;
1892 if (OrigInc->getType() != IsomorphicInc->getType()) {
1893 Instruction *IP = nullptr;
1894 if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1895 IP = &*PN->getParent()->getFirstInsertionPt();
1896 else
1897 IP = OrigInc->getNextNode();
1898
1899 IRBuilder<> Builder(IP);
1900 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1901 NewInc = Builder.CreateTruncOrBitCast(
1902 OrigInc, IsomorphicInc->getType(), IVName);
1903 }
1904 IsomorphicInc->replaceAllUsesWith(NewInc);
1905 DeadInsts.emplace_back(IsomorphicInc);
1906 }
Andrew Trickf9201c52011-10-11 02:28:51 +00001907 }
1908 }
Sanjoy Das0b6518d2016-05-10 00:32:31 +00001909 DEBUG_WITH_TYPE(DebugType, dbgs() << "INDVARS: Eliminated congruent iv: "
1910 << *Phi << '\n');
Andrew Trickf9201c52011-10-11 02:28:51 +00001911 ++NumElim;
Andrew Trick5adedf52012-01-07 01:12:09 +00001912 Value *NewIV = OrigPhiRef;
1913 if (OrigPhiRef->getType() != Phi->getType()) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001914 IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
Andrew Trick5adedf52012-01-07 01:12:09 +00001915 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1916 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1917 }
1918 Phi->replaceAllUsesWith(NewIV);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001919 DeadInsts.emplace_back(Phi);
Andrew Trickf9201c52011-10-11 02:28:51 +00001920 }
1921 return NumElim;
1922}
Andrew Trick653513b2012-07-13 23:33:10 +00001923
Wei Mi57543502016-08-09 20:40:03 +00001924Value *SCEVExpander::getExactExistingExpansion(const SCEV *S,
1925 const Instruction *At, Loop *L) {
1926 Optional<ScalarEvolution::ValueOffsetPair> VO =
1927 getRelatedExistingExpansion(S, At, L);
1928 if (VO && VO.getValue().second == nullptr)
1929 return VO.getValue().first;
1930 return nullptr;
1931}
1932
1933Optional<ScalarEvolution::ValueOffsetPair>
1934SCEVExpander::getRelatedExistingExpansion(const SCEV *S, const Instruction *At,
1935 Loop *L) {
Igor Laevsky4709c032015-08-10 18:23:58 +00001936 using namespace llvm::PatternMatch;
1937
Igor Laevsky06044f92015-08-17 16:37:04 +00001938 SmallVector<BasicBlock *, 4> ExitingBlocks;
1939 L->getExitingBlocks(ExitingBlocks);
Igor Laevsky4709c032015-08-10 18:23:58 +00001940
Igor Laevsky06044f92015-08-17 16:37:04 +00001941 // Look for suitable value in simple conditions at the loop exits.
1942 for (BasicBlock *BB : ExitingBlocks) {
Igor Laevsky4709c032015-08-10 18:23:58 +00001943 ICmpInst::Predicate Pred;
1944 Instruction *LHS, *RHS;
1945 BasicBlock *TrueBB, *FalseBB;
1946
1947 if (!match(BB->getTerminator(),
1948 m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1949 TrueBB, FalseBB)))
1950 continue;
1951
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001952 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
Wei Mi57543502016-08-09 20:40:03 +00001953 return ScalarEvolution::ValueOffsetPair(LHS, nullptr);
Igor Laevsky4709c032015-08-10 18:23:58 +00001954
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001955 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
Wei Mi57543502016-08-09 20:40:03 +00001956 return ScalarEvolution::ValueOffsetPair(RHS, nullptr);
Igor Laevsky4709c032015-08-10 18:23:58 +00001957 }
1958
Junmo Park6ebdc142016-02-16 06:46:58 +00001959 // Use expand's logic which is used for reusing a previous Value in
1960 // ExprValueMap.
Wei Mi57543502016-08-09 20:40:03 +00001961 ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, At);
1962 if (VO.first)
1963 return VO;
Junmo Park6ebdc142016-02-16 06:46:58 +00001964
Igor Laevsky4709c032015-08-10 18:23:58 +00001965 // There is potential to make this significantly smarter, but this simple
1966 // heuristic already gets some interesting cases.
1967
1968 // Can not find suitable value.
Wei Mi57543502016-08-09 20:40:03 +00001969 return None;
Igor Laevsky4709c032015-08-10 18:23:58 +00001970}
1971
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001972bool SCEVExpander::isHighCostExpansionHelper(
Igor Laevsky4709c032015-08-10 18:23:58 +00001973 const SCEV *S, Loop *L, const Instruction *At,
1974 SmallPtrSetImpl<const SCEV *> &Processed) {
1975
1976 // If we can find an existing value for this scev avaliable at the point "At"
1977 // then consider the expression cheap.
Wei Mi57543502016-08-09 20:40:03 +00001978 if (At && getRelatedExistingExpansion(S, At, L))
Igor Laevsky4709c032015-08-10 18:23:58 +00001979 return false;
Wei Mie2538b52015-05-28 21:49:07 +00001980
1981 // Zero/One operand expressions
1982 switch (S->getSCEVType()) {
1983 case scUnknown:
1984 case scConstant:
1985 return false;
1986 case scTruncate:
Igor Laevsky4709c032015-08-10 18:23:58 +00001987 return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
1988 L, At, Processed);
Wei Mie2538b52015-05-28 21:49:07 +00001989 case scZeroExtend:
1990 return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
Igor Laevsky4709c032015-08-10 18:23:58 +00001991 L, At, Processed);
Wei Mie2538b52015-05-28 21:49:07 +00001992 case scSignExtend:
1993 return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
Igor Laevsky4709c032015-08-10 18:23:58 +00001994 L, At, Processed);
Wei Mie2538b52015-05-28 21:49:07 +00001995 }
1996
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001997 if (!Processed.insert(S).second)
1998 return false;
1999
Sanjoy Dasa9f1e272015-04-14 03:20:32 +00002000 if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
2001 // If the divisor is a power of two and the SCEV type fits in a native
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002002 // integer, consider the division cheap irrespective of whether it occurs in
Sanjoy Dasa9f1e272015-04-14 03:20:32 +00002003 // the user code since it can be lowered into a right shift.
2004 if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002005 if (SC->getAPInt().isPowerOf2()) {
Sanjoy Dasa9f1e272015-04-14 03:20:32 +00002006 const DataLayout &DL =
2007 L->getHeader()->getParent()->getParent()->getDataLayout();
2008 unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
2009 return DL.isIllegalInteger(Width);
2010 }
2011
2012 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
2013 // HowManyLessThans produced to compute a precise expression, rather than a
2014 // UDiv from the user's code. If we can't find a UDiv in the code with some
2015 // simple searching, assume the former consider UDivExpr expensive to
2016 // compute.
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00002017 BasicBlock *ExitingBB = L->getExitingBlock();
2018 if (!ExitingBB)
2019 return true;
2020
Igor Laevsky06044f92015-08-17 16:37:04 +00002021 // At the beginning of this function we already tried to find existing value
2022 // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern
2023 // involving division. This is just a simple search heuristic.
2024 if (!At)
2025 At = &ExitingBB->back();
Wei Mi57543502016-08-09 20:40:03 +00002026 if (!getRelatedExistingExpansion(
Igor Laevsky06044f92015-08-17 16:37:04 +00002027 SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L))
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00002028 return true;
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00002029 }
2030
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00002031 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
2032 // the exit condition.
2033 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
2034 return true;
2035
Wei Mie2538b52015-05-28 21:49:07 +00002036 // Recurse past nary expressions, which commonly occur in the
2037 // BackedgeTakenCount. They may already exist in program code, and if not,
2038 // they are not too expensive rematerialize.
2039 if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00002040 for (auto *Op : NAry->operands())
2041 if (isHighCostExpansionHelper(Op, L, At, Processed))
Wei Mie2538b52015-05-28 21:49:07 +00002042 return true;
Wei Mie2538b52015-05-28 21:49:07 +00002043 }
2044
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00002045 // If we haven't recognized an expensive SCEV pattern, assume it's an
2046 // expression produced by program code.
2047 return false;
2048}
2049
Silviu Barangae3c05342015-11-02 14:41:02 +00002050Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
2051 Instruction *IP) {
2052 assert(IP);
2053 switch (Pred->getKind()) {
2054 case SCEVPredicate::P_Union:
2055 return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2056 case SCEVPredicate::P_Equal:
2057 return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002058 case SCEVPredicate::P_Wrap: {
2059 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2060 return expandWrapPredicate(AddRecPred, IP);
2061 }
Silviu Barangae3c05342015-11-02 14:41:02 +00002062 }
2063 llvm_unreachable("Unknown SCEV predicate type");
2064}
2065
2066Value *SCEVExpander::expandEqualPredicate(const SCEVEqualPredicate *Pred,
2067 Instruction *IP) {
2068 Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP);
2069 Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP);
2070
2071 Builder.SetInsertPoint(IP);
2072 auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
2073 return I;
2074}
2075
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002076Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
2077 Instruction *Loc, bool Signed) {
2078 assert(AR->isAffine() && "Cannot generate RT check for "
2079 "non-affine expression");
2080
Silviu Baranga6f444df2016-04-08 14:29:09 +00002081 SCEVUnionPredicate Pred;
2082 const SCEV *ExitCount =
2083 SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002084
2085 assert(ExitCount != SE.getCouldNotCompute() && "Invalid loop count");
2086
Silviu Baranga795c6292016-04-25 09:27:16 +00002087 const SCEV *Step = AR->getStepRecurrence(SE);
2088 const SCEV *Start = AR->getStart();
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002089
Silviu Baranga795c6292016-04-25 09:27:16 +00002090 unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2091 unsigned DstBits = SE.getTypeSizeInBits(AR->getType());
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002092
Silviu Baranga795c6292016-04-25 09:27:16 +00002093 // The expression {Start,+,Step} has nusw/nssw if
2094 // Step < 0, Start - |Step| * Backedge <= Start
2095 // Step >= 0, Start + |Step| * Backedge > Start
2096 // and |Step| * Backedge doesn't unsigned overflow.
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002097
Silviu Baranga795c6292016-04-25 09:27:16 +00002098 IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits);
2099 Builder.SetInsertPoint(Loc);
2100 Value *TripCountVal = expandCodeFor(ExitCount, CountTy, Loc);
2101
2102 IntegerType *Ty =
2103 IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(AR->getType()));
2104
2105 Value *StepValue = expandCodeFor(Step, Ty, Loc);
2106 Value *NegStepValue = expandCodeFor(SE.getNegativeSCEV(Step), Ty, Loc);
2107 Value *StartValue = expandCodeFor(Start, Ty, Loc);
2108
2109 ConstantInt *Zero =
2110 ConstantInt::get(Loc->getContext(), APInt::getNullValue(DstBits));
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002111
2112 Builder.SetInsertPoint(Loc);
Silviu Baranga795c6292016-04-25 09:27:16 +00002113 // Compute |Step|
2114 Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2115 Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002116
Silviu Baranga795c6292016-04-25 09:27:16 +00002117 // Get the backedge taken count and truncate or extended to the AR type.
2118 Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2119 auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
2120 Intrinsic::umul_with_overflow, Ty);
2121
2122 // Compute |Step| * Backedge
2123 CallInst *Mul = Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2124 Value *MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2125 Value *OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2126
2127 // Compute:
2128 // Start + |Step| * Backedge < Start
2129 // Start - |Step| * Backedge > Start
2130 Value *Add = Builder.CreateAdd(StartValue, MulV);
2131 Value *Sub = Builder.CreateSub(StartValue, MulV);
2132
2133 Value *EndCompareGT = Builder.CreateICmp(
2134 Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
2135
2136 Value *EndCompareLT = Builder.CreateICmp(
2137 Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
2138
2139 // Select the answer based on the sign of Step.
2140 Value *EndCheck =
2141 Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2142
2143 // If the backedge taken count type is larger than the AR type,
2144 // check that we don't drop any bits by truncating it. If we are
2145 // droping bits, then we have overflow (unless the step is zero).
2146 if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
2147 auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2148 auto *BackedgeCheck =
2149 Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2150 ConstantInt::get(Loc->getContext(), MaxVal));
2151 BackedgeCheck = Builder.CreateAnd(
2152 BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2153
2154 EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2155 }
2156
2157 EndCheck = Builder.CreateOr(EndCheck, OfMul);
2158 return EndCheck;
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002159}
2160
2161Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
2162 Instruction *IP) {
2163 const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2164 Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2165
2166 // Add a check for NUSW
2167 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
2168 NUSWCheck = generateOverflowCheck(A, IP, false);
2169
2170 // Add a check for NSSW
2171 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
2172 NSSWCheck = generateOverflowCheck(A, IP, true);
2173
2174 if (NUSWCheck && NSSWCheck)
2175 return Builder.CreateOr(NUSWCheck, NSSWCheck);
2176
2177 if (NUSWCheck)
2178 return NUSWCheck;
2179
2180 if (NSSWCheck)
2181 return NSSWCheck;
2182
2183 return ConstantInt::getFalse(IP->getContext());
2184}
2185
Silviu Barangae3c05342015-11-02 14:41:02 +00002186Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
2187 Instruction *IP) {
2188 auto *BoolType = IntegerType::get(IP->getContext(), 1);
2189 Value *Check = ConstantInt::getNullValue(BoolType);
2190
2191 // Loop over all checks in this set.
2192 for (auto Pred : Union->getPredicates()) {
2193 auto *NextCheck = expandCodeForPredicate(Pred, IP);
2194 Builder.SetInsertPoint(IP);
2195 Check = Builder.CreateOr(Check, NextCheck);
2196 }
2197
2198 return Check;
2199}
2200
Andrew Trick653513b2012-07-13 23:33:10 +00002201namespace {
2202// Search for a SCEV subexpression that is not safe to expand. Any expression
2203// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2204// UDiv expressions. We don't know if the UDiv is derived from an IR divide
2205// instruction, but the important thing is that we prove the denominator is
2206// nonzero before expansion.
2207//
2208// IVUsers already checks that IV-derived expressions are safe. So this check is
2209// only needed when the expression includes some subexpression that is not IV
2210// derived.
2211//
2212// Currently, we only allow division by a nonzero constant here. If this is
2213// inadequate, we could easily allow division by SCEVUnknown by using
2214// ValueTracking to check isKnownNonZero().
Andrew Trick57243da2013-10-25 21:35:56 +00002215//
2216// We cannot generally expand recurrences unless the step dominates the loop
2217// header. The expander handles the special case of affine recurrences by
2218// scaling the recurrence outside the loop, but this technique isn't generally
2219// applicable. Expanding a nested recurrence outside a loop requires computing
2220// binomial coefficients. This could be done, but the recurrence has to be in a
2221// perfectly reduced form, which can't be guaranteed.
Andrew Trick653513b2012-07-13 23:33:10 +00002222struct SCEVFindUnsafe {
Andrew Trick57243da2013-10-25 21:35:56 +00002223 ScalarEvolution &SE;
Andrew Trick653513b2012-07-13 23:33:10 +00002224 bool IsUnsafe;
2225
Andrew Trick57243da2013-10-25 21:35:56 +00002226 SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
Andrew Trick653513b2012-07-13 23:33:10 +00002227
2228 bool follow(const SCEV *S) {
Andrew Trick57243da2013-10-25 21:35:56 +00002229 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2230 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
2231 if (!SC || SC->getValue()->isZero()) {
2232 IsUnsafe = true;
2233 return false;
2234 }
2235 }
2236 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2237 const SCEV *Step = AR->getStepRecurrence(SE);
2238 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
2239 IsUnsafe = true;
2240 return false;
2241 }
2242 }
2243 return true;
Andrew Trick653513b2012-07-13 23:33:10 +00002244 }
2245 bool isDone() const { return IsUnsafe; }
2246};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002247}
Andrew Trick653513b2012-07-13 23:33:10 +00002248
2249namespace llvm {
Andrew Trick57243da2013-10-25 21:35:56 +00002250bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
2251 SCEVFindUnsafe Search(SE);
Andrew Trick653513b2012-07-13 23:33:10 +00002252 visitAll(S, Search);
2253 return !Search.IsUnsafe;
2254}
2255}