1*9880d681SAndroid Build Coastguard Worker //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file contains the implementation of the scalar evolution expander,
11*9880d681SAndroid Build Coastguard Worker // which is used to generate the code corresponding to a given scalar evolution
12*9880d681SAndroid Build Coastguard Worker // expression.
13*9880d681SAndroid Build Coastguard Worker //
14*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
15*9880d681SAndroid Build Coastguard Worker
16*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolutionExpander.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/STLExtras.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallSet.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetTransformInfo.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
30*9880d681SAndroid Build Coastguard Worker
31*9880d681SAndroid Build Coastguard Worker using namespace llvm;
32*9880d681SAndroid Build Coastguard Worker using namespace PatternMatch;
33*9880d681SAndroid Build Coastguard Worker
34*9880d681SAndroid Build Coastguard Worker /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
35*9880d681SAndroid Build Coastguard Worker /// reusing an existing cast if a suitable one exists, moving an existing
36*9880d681SAndroid Build Coastguard Worker /// cast if a suitable one exists but isn't in the right place, or
37*9880d681SAndroid Build Coastguard Worker /// creating a new one.
ReuseOrCreateCast(Value * V,Type * Ty,Instruction::CastOps Op,BasicBlock::iterator IP)38*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
39*9880d681SAndroid Build Coastguard Worker Instruction::CastOps Op,
40*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator IP) {
41*9880d681SAndroid Build Coastguard Worker // This function must be called with the builder having a valid insertion
42*9880d681SAndroid Build Coastguard Worker // point. It doesn't need to be the actual IP where the uses of the returned
43*9880d681SAndroid Build Coastguard Worker // cast will be added, but it must dominate such IP.
44*9880d681SAndroid Build Coastguard Worker // We use this precondition to produce a cast that will dominate all its
45*9880d681SAndroid Build Coastguard Worker // uses. In particular, this is crucial for the case where the builder's
46*9880d681SAndroid Build Coastguard Worker // insertion point *is* the point where we were asked to put the cast.
47*9880d681SAndroid Build Coastguard Worker // Since we don't know the builder's insertion point is actually
48*9880d681SAndroid Build Coastguard Worker // where the uses will be added (only that it dominates it), we are
49*9880d681SAndroid Build Coastguard Worker // not allowed to move it.
50*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator BIP = Builder.GetInsertPoint();
51*9880d681SAndroid Build Coastguard Worker
52*9880d681SAndroid Build Coastguard Worker Instruction *Ret = nullptr;
53*9880d681SAndroid Build Coastguard Worker
54*9880d681SAndroid Build Coastguard Worker // Check to see if there is already a cast!
55*9880d681SAndroid Build Coastguard Worker for (User *U : V->users())
56*9880d681SAndroid Build Coastguard Worker if (U->getType() == Ty)
57*9880d681SAndroid Build Coastguard Worker if (CastInst *CI = dyn_cast<CastInst>(U))
58*9880d681SAndroid Build Coastguard Worker if (CI->getOpcode() == Op) {
59*9880d681SAndroid Build Coastguard Worker // If the cast isn't where we want it, create a new cast at IP.
60*9880d681SAndroid Build Coastguard Worker // Likewise, do not reuse a cast at BIP because it must dominate
61*9880d681SAndroid Build Coastguard Worker // instructions that might be inserted before BIP.
62*9880d681SAndroid Build Coastguard Worker if (BasicBlock::iterator(CI) != IP || BIP == IP) {
63*9880d681SAndroid Build Coastguard Worker // Create a new cast, and leave the old cast in place in case
64*9880d681SAndroid Build Coastguard Worker // it is being used as an insert point. Clear its operand
65*9880d681SAndroid Build Coastguard Worker // so that it doesn't hold anything live.
66*9880d681SAndroid Build Coastguard Worker Ret = CastInst::Create(Op, V, Ty, "", &*IP);
67*9880d681SAndroid Build Coastguard Worker Ret->takeName(CI);
68*9880d681SAndroid Build Coastguard Worker CI->replaceAllUsesWith(Ret);
69*9880d681SAndroid Build Coastguard Worker CI->setOperand(0, UndefValue::get(V->getType()));
70*9880d681SAndroid Build Coastguard Worker break;
71*9880d681SAndroid Build Coastguard Worker }
72*9880d681SAndroid Build Coastguard Worker Ret = CI;
73*9880d681SAndroid Build Coastguard Worker break;
74*9880d681SAndroid Build Coastguard Worker }
75*9880d681SAndroid Build Coastguard Worker
76*9880d681SAndroid Build Coastguard Worker // Create a new cast.
77*9880d681SAndroid Build Coastguard Worker if (!Ret)
78*9880d681SAndroid Build Coastguard Worker Ret = CastInst::Create(Op, V, Ty, V->getName(), &*IP);
79*9880d681SAndroid Build Coastguard Worker
80*9880d681SAndroid Build Coastguard Worker // We assert at the end of the function since IP might point to an
81*9880d681SAndroid Build Coastguard Worker // instruction with different dominance properties than a cast
82*9880d681SAndroid Build Coastguard Worker // (an invoke for example) and not dominate BIP (but the cast does).
83*9880d681SAndroid Build Coastguard Worker assert(SE.DT.dominates(Ret, &*BIP));
84*9880d681SAndroid Build Coastguard Worker
85*9880d681SAndroid Build Coastguard Worker rememberInstruction(Ret);
86*9880d681SAndroid Build Coastguard Worker return Ret;
87*9880d681SAndroid Build Coastguard Worker }
88*9880d681SAndroid Build Coastguard Worker
findInsertPointAfter(Instruction * I,BasicBlock * MustDominate)89*9880d681SAndroid Build Coastguard Worker static BasicBlock::iterator findInsertPointAfter(Instruction *I,
90*9880d681SAndroid Build Coastguard Worker BasicBlock *MustDominate) {
91*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator IP = ++I->getIterator();
92*9880d681SAndroid Build Coastguard Worker if (auto *II = dyn_cast<InvokeInst>(I))
93*9880d681SAndroid Build Coastguard Worker IP = II->getNormalDest()->begin();
94*9880d681SAndroid Build Coastguard Worker
95*9880d681SAndroid Build Coastguard Worker while (isa<PHINode>(IP))
96*9880d681SAndroid Build Coastguard Worker ++IP;
97*9880d681SAndroid Build Coastguard Worker
98*9880d681SAndroid Build Coastguard Worker if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
99*9880d681SAndroid Build Coastguard Worker ++IP;
100*9880d681SAndroid Build Coastguard Worker } else if (isa<CatchSwitchInst>(IP)) {
101*9880d681SAndroid Build Coastguard Worker IP = MustDominate->getFirstInsertionPt();
102*9880d681SAndroid Build Coastguard Worker } else {
103*9880d681SAndroid Build Coastguard Worker assert(!IP->isEHPad() && "unexpected eh pad!");
104*9880d681SAndroid Build Coastguard Worker }
105*9880d681SAndroid Build Coastguard Worker
106*9880d681SAndroid Build Coastguard Worker return IP;
107*9880d681SAndroid Build Coastguard Worker }
108*9880d681SAndroid Build Coastguard Worker
109*9880d681SAndroid Build Coastguard Worker /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
110*9880d681SAndroid Build Coastguard Worker /// which must be possible with a noop cast, doing what we can to share
111*9880d681SAndroid Build Coastguard Worker /// the casts.
InsertNoopCastOfTo(Value * V,Type * Ty)112*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
113*9880d681SAndroid Build Coastguard Worker Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
114*9880d681SAndroid Build Coastguard Worker assert((Op == Instruction::BitCast ||
115*9880d681SAndroid Build Coastguard Worker Op == Instruction::PtrToInt ||
116*9880d681SAndroid Build Coastguard Worker Op == Instruction::IntToPtr) &&
117*9880d681SAndroid Build Coastguard Worker "InsertNoopCastOfTo cannot perform non-noop casts!");
118*9880d681SAndroid Build Coastguard Worker assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
119*9880d681SAndroid Build Coastguard Worker "InsertNoopCastOfTo cannot change sizes!");
120*9880d681SAndroid Build Coastguard Worker
121*9880d681SAndroid Build Coastguard Worker // Short-circuit unnecessary bitcasts.
122*9880d681SAndroid Build Coastguard Worker if (Op == Instruction::BitCast) {
123*9880d681SAndroid Build Coastguard Worker if (V->getType() == Ty)
124*9880d681SAndroid Build Coastguard Worker return V;
125*9880d681SAndroid Build Coastguard Worker if (CastInst *CI = dyn_cast<CastInst>(V)) {
126*9880d681SAndroid Build Coastguard Worker if (CI->getOperand(0)->getType() == Ty)
127*9880d681SAndroid Build Coastguard Worker return CI->getOperand(0);
128*9880d681SAndroid Build Coastguard Worker }
129*9880d681SAndroid Build Coastguard Worker }
130*9880d681SAndroid Build Coastguard Worker // Short-circuit unnecessary inttoptr<->ptrtoint casts.
131*9880d681SAndroid Build Coastguard Worker if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
132*9880d681SAndroid Build Coastguard Worker SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
133*9880d681SAndroid Build Coastguard Worker if (CastInst *CI = dyn_cast<CastInst>(V))
134*9880d681SAndroid Build Coastguard Worker if ((CI->getOpcode() == Instruction::PtrToInt ||
135*9880d681SAndroid Build Coastguard Worker CI->getOpcode() == Instruction::IntToPtr) &&
136*9880d681SAndroid Build Coastguard Worker SE.getTypeSizeInBits(CI->getType()) ==
137*9880d681SAndroid Build Coastguard Worker SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
138*9880d681SAndroid Build Coastguard Worker return CI->getOperand(0);
139*9880d681SAndroid Build Coastguard Worker if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
140*9880d681SAndroid Build Coastguard Worker if ((CE->getOpcode() == Instruction::PtrToInt ||
141*9880d681SAndroid Build Coastguard Worker CE->getOpcode() == Instruction::IntToPtr) &&
142*9880d681SAndroid Build Coastguard Worker SE.getTypeSizeInBits(CE->getType()) ==
143*9880d681SAndroid Build Coastguard Worker SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
144*9880d681SAndroid Build Coastguard Worker return CE->getOperand(0);
145*9880d681SAndroid Build Coastguard Worker }
146*9880d681SAndroid Build Coastguard Worker
147*9880d681SAndroid Build Coastguard Worker // Fold a cast of a constant.
148*9880d681SAndroid Build Coastguard Worker if (Constant *C = dyn_cast<Constant>(V))
149*9880d681SAndroid Build Coastguard Worker return ConstantExpr::getCast(Op, C, Ty);
150*9880d681SAndroid Build Coastguard Worker
151*9880d681SAndroid Build Coastguard Worker // Cast the argument at the beginning of the entry block, after
152*9880d681SAndroid Build Coastguard Worker // any bitcasts of other arguments.
153*9880d681SAndroid Build Coastguard Worker if (Argument *A = dyn_cast<Argument>(V)) {
154*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
155*9880d681SAndroid Build Coastguard Worker while ((isa<BitCastInst>(IP) &&
156*9880d681SAndroid Build Coastguard Worker isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
157*9880d681SAndroid Build Coastguard Worker cast<BitCastInst>(IP)->getOperand(0) != A) ||
158*9880d681SAndroid Build Coastguard Worker isa<DbgInfoIntrinsic>(IP))
159*9880d681SAndroid Build Coastguard Worker ++IP;
160*9880d681SAndroid Build Coastguard Worker return ReuseOrCreateCast(A, Ty, Op, IP);
161*9880d681SAndroid Build Coastguard Worker }
162*9880d681SAndroid Build Coastguard Worker
163*9880d681SAndroid Build Coastguard Worker // Cast the instruction immediately after the instruction.
164*9880d681SAndroid Build Coastguard Worker Instruction *I = cast<Instruction>(V);
165*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator IP = findInsertPointAfter(I, Builder.GetInsertBlock());
166*9880d681SAndroid Build Coastguard Worker return ReuseOrCreateCast(I, Ty, Op, IP);
167*9880d681SAndroid Build Coastguard Worker }
168*9880d681SAndroid Build Coastguard Worker
169*9880d681SAndroid Build Coastguard Worker /// InsertBinop - Insert the specified binary operator, doing a small amount
170*9880d681SAndroid Build Coastguard Worker /// of work to avoid inserting an obviously redundant operation.
InsertBinop(Instruction::BinaryOps Opcode,Value * LHS,Value * RHS)171*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
172*9880d681SAndroid Build Coastguard Worker Value *LHS, Value *RHS) {
173*9880d681SAndroid Build Coastguard Worker // Fold a binop with constant operands.
174*9880d681SAndroid Build Coastguard Worker if (Constant *CLHS = dyn_cast<Constant>(LHS))
175*9880d681SAndroid Build Coastguard Worker if (Constant *CRHS = dyn_cast<Constant>(RHS))
176*9880d681SAndroid Build Coastguard Worker return ConstantExpr::get(Opcode, CLHS, CRHS);
177*9880d681SAndroid Build Coastguard Worker
178*9880d681SAndroid Build Coastguard Worker // Do a quick scan to see if we have this binop nearby. If so, reuse it.
179*9880d681SAndroid Build Coastguard Worker unsigned ScanLimit = 6;
180*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
181*9880d681SAndroid Build Coastguard Worker // Scanning starts from the last instruction before the insertion point.
182*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator IP = Builder.GetInsertPoint();
183*9880d681SAndroid Build Coastguard Worker if (IP != BlockBegin) {
184*9880d681SAndroid Build Coastguard Worker --IP;
185*9880d681SAndroid Build Coastguard Worker for (; ScanLimit; --IP, --ScanLimit) {
186*9880d681SAndroid Build Coastguard Worker // Don't count dbg.value against the ScanLimit, to avoid perturbing the
187*9880d681SAndroid Build Coastguard Worker // generated code.
188*9880d681SAndroid Build Coastguard Worker if (isa<DbgInfoIntrinsic>(IP))
189*9880d681SAndroid Build Coastguard Worker ScanLimit++;
190*9880d681SAndroid Build Coastguard Worker if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
191*9880d681SAndroid Build Coastguard Worker IP->getOperand(1) == RHS)
192*9880d681SAndroid Build Coastguard Worker return &*IP;
193*9880d681SAndroid Build Coastguard Worker if (IP == BlockBegin) break;
194*9880d681SAndroid Build Coastguard Worker }
195*9880d681SAndroid Build Coastguard Worker }
196*9880d681SAndroid Build Coastguard Worker
197*9880d681SAndroid Build Coastguard Worker // Save the original insertion point so we can restore it when we're done.
198*9880d681SAndroid Build Coastguard Worker DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
199*9880d681SAndroid Build Coastguard Worker SCEVInsertPointGuard Guard(Builder, this);
200*9880d681SAndroid Build Coastguard Worker
201*9880d681SAndroid Build Coastguard Worker // Move the insertion point out of as many loops as we can.
202*9880d681SAndroid Build Coastguard Worker while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
203*9880d681SAndroid Build Coastguard Worker if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
204*9880d681SAndroid Build Coastguard Worker BasicBlock *Preheader = L->getLoopPreheader();
205*9880d681SAndroid Build Coastguard Worker if (!Preheader) break;
206*9880d681SAndroid Build Coastguard Worker
207*9880d681SAndroid Build Coastguard Worker // Ok, move up a level.
208*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(Preheader->getTerminator());
209*9880d681SAndroid Build Coastguard Worker }
210*9880d681SAndroid Build Coastguard Worker
211*9880d681SAndroid Build Coastguard Worker // If we haven't found this binop, insert it.
212*9880d681SAndroid Build Coastguard Worker Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
213*9880d681SAndroid Build Coastguard Worker BO->setDebugLoc(Loc);
214*9880d681SAndroid Build Coastguard Worker rememberInstruction(BO);
215*9880d681SAndroid Build Coastguard Worker
216*9880d681SAndroid Build Coastguard Worker return BO;
217*9880d681SAndroid Build Coastguard Worker }
218*9880d681SAndroid Build Coastguard Worker
219*9880d681SAndroid Build Coastguard Worker /// FactorOutConstant - Test if S is divisible by Factor, using signed
220*9880d681SAndroid Build Coastguard Worker /// division. If so, update S with Factor divided out and return true.
221*9880d681SAndroid Build Coastguard Worker /// S need not be evenly divisible if a reasonable remainder can be
222*9880d681SAndroid Build Coastguard Worker /// computed.
223*9880d681SAndroid Build Coastguard Worker /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
224*9880d681SAndroid Build Coastguard Worker /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
225*9880d681SAndroid Build Coastguard Worker /// check to see if the divide was folded.
FactorOutConstant(const SCEV * & S,const SCEV * & Remainder,const SCEV * Factor,ScalarEvolution & SE,const DataLayout & DL)226*9880d681SAndroid Build Coastguard Worker static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
227*9880d681SAndroid Build Coastguard Worker const SCEV *Factor, ScalarEvolution &SE,
228*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
229*9880d681SAndroid Build Coastguard Worker // Everything is divisible by one.
230*9880d681SAndroid Build Coastguard Worker if (Factor->isOne())
231*9880d681SAndroid Build Coastguard Worker return true;
232*9880d681SAndroid Build Coastguard Worker
233*9880d681SAndroid Build Coastguard Worker // x/x == 1.
234*9880d681SAndroid Build Coastguard Worker if (S == Factor) {
235*9880d681SAndroid Build Coastguard Worker S = SE.getConstant(S->getType(), 1);
236*9880d681SAndroid Build Coastguard Worker return true;
237*9880d681SAndroid Build Coastguard Worker }
238*9880d681SAndroid Build Coastguard Worker
239*9880d681SAndroid Build Coastguard Worker // For a Constant, check for a multiple of the given factor.
240*9880d681SAndroid Build Coastguard Worker if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
241*9880d681SAndroid Build Coastguard Worker // 0/x == 0.
242*9880d681SAndroid Build Coastguard Worker if (C->isZero())
243*9880d681SAndroid Build Coastguard Worker return true;
244*9880d681SAndroid Build Coastguard Worker // Check for divisibility.
245*9880d681SAndroid Build Coastguard Worker if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
246*9880d681SAndroid Build Coastguard Worker ConstantInt *CI =
247*9880d681SAndroid Build Coastguard Worker ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
248*9880d681SAndroid Build Coastguard Worker // If the quotient is zero and the remainder is non-zero, reject
249*9880d681SAndroid Build Coastguard Worker // the value at this scale. It will be considered for subsequent
250*9880d681SAndroid Build Coastguard Worker // smaller scales.
251*9880d681SAndroid Build Coastguard Worker if (!CI->isZero()) {
252*9880d681SAndroid Build Coastguard Worker const SCEV *Div = SE.getConstant(CI);
253*9880d681SAndroid Build Coastguard Worker S = Div;
254*9880d681SAndroid Build Coastguard Worker Remainder = SE.getAddExpr(
255*9880d681SAndroid Build Coastguard Worker Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
256*9880d681SAndroid Build Coastguard Worker return true;
257*9880d681SAndroid Build Coastguard Worker }
258*9880d681SAndroid Build Coastguard Worker }
259*9880d681SAndroid Build Coastguard Worker }
260*9880d681SAndroid Build Coastguard Worker
261*9880d681SAndroid Build Coastguard Worker // In a Mul, check if there is a constant operand which is a multiple
262*9880d681SAndroid Build Coastguard Worker // of the given factor.
263*9880d681SAndroid Build Coastguard Worker if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
264*9880d681SAndroid Build Coastguard Worker // Size is known, check if there is a constant operand which is a multiple
265*9880d681SAndroid Build Coastguard Worker // of the given factor. If so, we can factor it.
266*9880d681SAndroid Build Coastguard Worker const SCEVConstant *FC = cast<SCEVConstant>(Factor);
267*9880d681SAndroid Build Coastguard Worker if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
268*9880d681SAndroid Build Coastguard Worker if (!C->getAPInt().srem(FC->getAPInt())) {
269*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
270*9880d681SAndroid Build Coastguard Worker NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
271*9880d681SAndroid Build Coastguard Worker S = SE.getMulExpr(NewMulOps);
272*9880d681SAndroid Build Coastguard Worker return true;
273*9880d681SAndroid Build Coastguard Worker }
274*9880d681SAndroid Build Coastguard Worker }
275*9880d681SAndroid Build Coastguard Worker
276*9880d681SAndroid Build Coastguard Worker // In an AddRec, check if both start and step are divisible.
277*9880d681SAndroid Build Coastguard Worker if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
278*9880d681SAndroid Build Coastguard Worker const SCEV *Step = A->getStepRecurrence(SE);
279*9880d681SAndroid Build Coastguard Worker const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
280*9880d681SAndroid Build Coastguard Worker if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
281*9880d681SAndroid Build Coastguard Worker return false;
282*9880d681SAndroid Build Coastguard Worker if (!StepRem->isZero())
283*9880d681SAndroid Build Coastguard Worker return false;
284*9880d681SAndroid Build Coastguard Worker const SCEV *Start = A->getStart();
285*9880d681SAndroid Build Coastguard Worker if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
286*9880d681SAndroid Build Coastguard Worker return false;
287*9880d681SAndroid Build Coastguard Worker S = SE.getAddRecExpr(Start, Step, A->getLoop(),
288*9880d681SAndroid Build Coastguard Worker A->getNoWrapFlags(SCEV::FlagNW));
289*9880d681SAndroid Build Coastguard Worker return true;
290*9880d681SAndroid Build Coastguard Worker }
291*9880d681SAndroid Build Coastguard Worker
292*9880d681SAndroid Build Coastguard Worker return false;
293*9880d681SAndroid Build Coastguard Worker }
294*9880d681SAndroid Build Coastguard Worker
295*9880d681SAndroid Build Coastguard Worker /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
296*9880d681SAndroid Build Coastguard Worker /// is the number of SCEVAddRecExprs present, which are kept at the end of
297*9880d681SAndroid Build Coastguard Worker /// the list.
298*9880d681SAndroid Build Coastguard Worker ///
SimplifyAddOperands(SmallVectorImpl<const SCEV * > & Ops,Type * Ty,ScalarEvolution & SE)299*9880d681SAndroid Build Coastguard Worker static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
300*9880d681SAndroid Build Coastguard Worker Type *Ty,
301*9880d681SAndroid Build Coastguard Worker ScalarEvolution &SE) {
302*9880d681SAndroid Build Coastguard Worker unsigned NumAddRecs = 0;
303*9880d681SAndroid Build Coastguard Worker for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
304*9880d681SAndroid Build Coastguard Worker ++NumAddRecs;
305*9880d681SAndroid Build Coastguard Worker // Group Ops into non-addrecs and addrecs.
306*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
307*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
308*9880d681SAndroid Build Coastguard Worker // Let ScalarEvolution sort and simplify the non-addrecs list.
309*9880d681SAndroid Build Coastguard Worker const SCEV *Sum = NoAddRecs.empty() ?
310*9880d681SAndroid Build Coastguard Worker SE.getConstant(Ty, 0) :
311*9880d681SAndroid Build Coastguard Worker SE.getAddExpr(NoAddRecs);
312*9880d681SAndroid Build Coastguard Worker // If it returned an add, use the operands. Otherwise it simplified
313*9880d681SAndroid Build Coastguard Worker // the sum into a single value, so just use that.
314*9880d681SAndroid Build Coastguard Worker Ops.clear();
315*9880d681SAndroid Build Coastguard Worker if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
316*9880d681SAndroid Build Coastguard Worker Ops.append(Add->op_begin(), Add->op_end());
317*9880d681SAndroid Build Coastguard Worker else if (!Sum->isZero())
318*9880d681SAndroid Build Coastguard Worker Ops.push_back(Sum);
319*9880d681SAndroid Build Coastguard Worker // Then append the addrecs.
320*9880d681SAndroid Build Coastguard Worker Ops.append(AddRecs.begin(), AddRecs.end());
321*9880d681SAndroid Build Coastguard Worker }
322*9880d681SAndroid Build Coastguard Worker
323*9880d681SAndroid Build Coastguard Worker /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
324*9880d681SAndroid Build Coastguard Worker /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
325*9880d681SAndroid Build Coastguard Worker /// This helps expose more opportunities for folding parts of the expressions
326*9880d681SAndroid Build Coastguard Worker /// into GEP indices.
327*9880d681SAndroid Build Coastguard Worker ///
SplitAddRecs(SmallVectorImpl<const SCEV * > & Ops,Type * Ty,ScalarEvolution & SE)328*9880d681SAndroid Build Coastguard Worker static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
329*9880d681SAndroid Build Coastguard Worker Type *Ty,
330*9880d681SAndroid Build Coastguard Worker ScalarEvolution &SE) {
331*9880d681SAndroid Build Coastguard Worker // Find the addrecs.
332*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 8> AddRecs;
333*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = Ops.size(); i != e; ++i)
334*9880d681SAndroid Build Coastguard Worker while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
335*9880d681SAndroid Build Coastguard Worker const SCEV *Start = A->getStart();
336*9880d681SAndroid Build Coastguard Worker if (Start->isZero()) break;
337*9880d681SAndroid Build Coastguard Worker const SCEV *Zero = SE.getConstant(Ty, 0);
338*9880d681SAndroid Build Coastguard Worker AddRecs.push_back(SE.getAddRecExpr(Zero,
339*9880d681SAndroid Build Coastguard Worker A->getStepRecurrence(SE),
340*9880d681SAndroid Build Coastguard Worker A->getLoop(),
341*9880d681SAndroid Build Coastguard Worker A->getNoWrapFlags(SCEV::FlagNW)));
342*9880d681SAndroid Build Coastguard Worker if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
343*9880d681SAndroid Build Coastguard Worker Ops[i] = Zero;
344*9880d681SAndroid Build Coastguard Worker Ops.append(Add->op_begin(), Add->op_end());
345*9880d681SAndroid Build Coastguard Worker e += Add->getNumOperands();
346*9880d681SAndroid Build Coastguard Worker } else {
347*9880d681SAndroid Build Coastguard Worker Ops[i] = Start;
348*9880d681SAndroid Build Coastguard Worker }
349*9880d681SAndroid Build Coastguard Worker }
350*9880d681SAndroid Build Coastguard Worker if (!AddRecs.empty()) {
351*9880d681SAndroid Build Coastguard Worker // Add the addrecs onto the end of the list.
352*9880d681SAndroid Build Coastguard Worker Ops.append(AddRecs.begin(), AddRecs.end());
353*9880d681SAndroid Build Coastguard Worker // Resort the operand list, moving any constants to the front.
354*9880d681SAndroid Build Coastguard Worker SimplifyAddOperands(Ops, Ty, SE);
355*9880d681SAndroid Build Coastguard Worker }
356*9880d681SAndroid Build Coastguard Worker }
357*9880d681SAndroid Build Coastguard Worker
358*9880d681SAndroid Build Coastguard Worker /// expandAddToGEP - Expand an addition expression with a pointer type into
359*9880d681SAndroid Build Coastguard Worker /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
360*9880d681SAndroid Build Coastguard Worker /// BasicAliasAnalysis and other passes analyze the result. See the rules
361*9880d681SAndroid Build Coastguard Worker /// for getelementptr vs. inttoptr in
362*9880d681SAndroid Build Coastguard Worker /// http://llvm.org/docs/LangRef.html#pointeraliasing
363*9880d681SAndroid Build Coastguard Worker /// for details.
364*9880d681SAndroid Build Coastguard Worker ///
365*9880d681SAndroid Build Coastguard Worker /// Design note: The correctness of using getelementptr here depends on
366*9880d681SAndroid Build Coastguard Worker /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
367*9880d681SAndroid Build Coastguard Worker /// they may introduce pointer arithmetic which may not be safely converted
368*9880d681SAndroid Build Coastguard Worker /// into getelementptr.
369*9880d681SAndroid Build Coastguard Worker ///
370*9880d681SAndroid Build Coastguard Worker /// Design note: It might seem desirable for this function to be more
371*9880d681SAndroid Build Coastguard Worker /// loop-aware. If some of the indices are loop-invariant while others
372*9880d681SAndroid Build Coastguard Worker /// aren't, it might seem desirable to emit multiple GEPs, keeping the
373*9880d681SAndroid Build Coastguard Worker /// loop-invariant portions of the overall computation outside the loop.
374*9880d681SAndroid Build Coastguard Worker /// However, there are a few reasons this is not done here. Hoisting simple
375*9880d681SAndroid Build Coastguard Worker /// arithmetic is a low-level optimization that often isn't very
376*9880d681SAndroid Build Coastguard Worker /// important until late in the optimization process. In fact, passes
377*9880d681SAndroid Build Coastguard Worker /// like InstructionCombining will combine GEPs, even if it means
378*9880d681SAndroid Build Coastguard Worker /// pushing loop-invariant computation down into loops, so even if the
379*9880d681SAndroid Build Coastguard Worker /// GEPs were split here, the work would quickly be undone. The
380*9880d681SAndroid Build Coastguard Worker /// LoopStrengthReduction pass, which is usually run quite late (and
381*9880d681SAndroid Build Coastguard Worker /// after the last InstructionCombining pass), takes care of hoisting
382*9880d681SAndroid Build Coastguard Worker /// loop-invariant portions of expressions, after considering what
383*9880d681SAndroid Build Coastguard Worker /// can be folded using target addressing modes.
384*9880d681SAndroid Build Coastguard Worker ///
expandAddToGEP(const SCEV * const * op_begin,const SCEV * const * op_end,PointerType * PTy,Type * Ty,Value * V)385*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
386*9880d681SAndroid Build Coastguard Worker const SCEV *const *op_end,
387*9880d681SAndroid Build Coastguard Worker PointerType *PTy,
388*9880d681SAndroid Build Coastguard Worker Type *Ty,
389*9880d681SAndroid Build Coastguard Worker Value *V) {
390*9880d681SAndroid Build Coastguard Worker Type *OriginalElTy = PTy->getElementType();
391*9880d681SAndroid Build Coastguard Worker Type *ElTy = OriginalElTy;
392*9880d681SAndroid Build Coastguard Worker SmallVector<Value *, 4> GepIndices;
393*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
394*9880d681SAndroid Build Coastguard Worker bool AnyNonZeroIndices = false;
395*9880d681SAndroid Build Coastguard Worker
396*9880d681SAndroid Build Coastguard Worker // Split AddRecs up into parts as either of the parts may be usable
397*9880d681SAndroid Build Coastguard Worker // without the other.
398*9880d681SAndroid Build Coastguard Worker SplitAddRecs(Ops, Ty, SE);
399*9880d681SAndroid Build Coastguard Worker
400*9880d681SAndroid Build Coastguard Worker Type *IntPtrTy = DL.getIntPtrType(PTy);
401*9880d681SAndroid Build Coastguard Worker
402*9880d681SAndroid Build Coastguard Worker // Descend down the pointer's type and attempt to convert the other
403*9880d681SAndroid Build Coastguard Worker // operands into GEP indices, at each level. The first index in a GEP
404*9880d681SAndroid Build Coastguard Worker // indexes into the array implied by the pointer operand; the rest of
405*9880d681SAndroid Build Coastguard Worker // the indices index into the element or field type selected by the
406*9880d681SAndroid Build Coastguard Worker // preceding index.
407*9880d681SAndroid Build Coastguard Worker for (;;) {
408*9880d681SAndroid Build Coastguard Worker // If the scale size is not 0, attempt to factor out a scale for
409*9880d681SAndroid Build Coastguard Worker // array indexing.
410*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 8> ScaledOps;
411*9880d681SAndroid Build Coastguard Worker if (ElTy->isSized()) {
412*9880d681SAndroid Build Coastguard Worker const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
413*9880d681SAndroid Build Coastguard Worker if (!ElSize->isZero()) {
414*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 8> NewOps;
415*9880d681SAndroid Build Coastguard Worker for (const SCEV *Op : Ops) {
416*9880d681SAndroid Build Coastguard Worker const SCEV *Remainder = SE.getConstant(Ty, 0);
417*9880d681SAndroid Build Coastguard Worker if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
418*9880d681SAndroid Build Coastguard Worker // Op now has ElSize factored out.
419*9880d681SAndroid Build Coastguard Worker ScaledOps.push_back(Op);
420*9880d681SAndroid Build Coastguard Worker if (!Remainder->isZero())
421*9880d681SAndroid Build Coastguard Worker NewOps.push_back(Remainder);
422*9880d681SAndroid Build Coastguard Worker AnyNonZeroIndices = true;
423*9880d681SAndroid Build Coastguard Worker } else {
424*9880d681SAndroid Build Coastguard Worker // The operand was not divisible, so add it to the list of operands
425*9880d681SAndroid Build Coastguard Worker // we'll scan next iteration.
426*9880d681SAndroid Build Coastguard Worker NewOps.push_back(Op);
427*9880d681SAndroid Build Coastguard Worker }
428*9880d681SAndroid Build Coastguard Worker }
429*9880d681SAndroid Build Coastguard Worker // If we made any changes, update Ops.
430*9880d681SAndroid Build Coastguard Worker if (!ScaledOps.empty()) {
431*9880d681SAndroid Build Coastguard Worker Ops = NewOps;
432*9880d681SAndroid Build Coastguard Worker SimplifyAddOperands(Ops, Ty, SE);
433*9880d681SAndroid Build Coastguard Worker }
434*9880d681SAndroid Build Coastguard Worker }
435*9880d681SAndroid Build Coastguard Worker }
436*9880d681SAndroid Build Coastguard Worker
437*9880d681SAndroid Build Coastguard Worker // Record the scaled array index for this level of the type. If
438*9880d681SAndroid Build Coastguard Worker // we didn't find any operands that could be factored, tentatively
439*9880d681SAndroid Build Coastguard Worker // assume that element zero was selected (since the zero offset
440*9880d681SAndroid Build Coastguard Worker // would obviously be folded away).
441*9880d681SAndroid Build Coastguard Worker Value *Scaled = ScaledOps.empty() ?
442*9880d681SAndroid Build Coastguard Worker Constant::getNullValue(Ty) :
443*9880d681SAndroid Build Coastguard Worker expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
444*9880d681SAndroid Build Coastguard Worker GepIndices.push_back(Scaled);
445*9880d681SAndroid Build Coastguard Worker
446*9880d681SAndroid Build Coastguard Worker // Collect struct field index operands.
447*9880d681SAndroid Build Coastguard Worker while (StructType *STy = dyn_cast<StructType>(ElTy)) {
448*9880d681SAndroid Build Coastguard Worker bool FoundFieldNo = false;
449*9880d681SAndroid Build Coastguard Worker // An empty struct has no fields.
450*9880d681SAndroid Build Coastguard Worker if (STy->getNumElements() == 0) break;
451*9880d681SAndroid Build Coastguard Worker // Field offsets are known. See if a constant offset falls within any of
452*9880d681SAndroid Build Coastguard Worker // the struct fields.
453*9880d681SAndroid Build Coastguard Worker if (Ops.empty())
454*9880d681SAndroid Build Coastguard Worker break;
455*9880d681SAndroid Build Coastguard Worker if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
456*9880d681SAndroid Build Coastguard Worker if (SE.getTypeSizeInBits(C->getType()) <= 64) {
457*9880d681SAndroid Build Coastguard Worker const StructLayout &SL = *DL.getStructLayout(STy);
458*9880d681SAndroid Build Coastguard Worker uint64_t FullOffset = C->getValue()->getZExtValue();
459*9880d681SAndroid Build Coastguard Worker if (FullOffset < SL.getSizeInBytes()) {
460*9880d681SAndroid Build Coastguard Worker unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
461*9880d681SAndroid Build Coastguard Worker GepIndices.push_back(
462*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
463*9880d681SAndroid Build Coastguard Worker ElTy = STy->getTypeAtIndex(ElIdx);
464*9880d681SAndroid Build Coastguard Worker Ops[0] =
465*9880d681SAndroid Build Coastguard Worker SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
466*9880d681SAndroid Build Coastguard Worker AnyNonZeroIndices = true;
467*9880d681SAndroid Build Coastguard Worker FoundFieldNo = true;
468*9880d681SAndroid Build Coastguard Worker }
469*9880d681SAndroid Build Coastguard Worker }
470*9880d681SAndroid Build Coastguard Worker // If no struct field offsets were found, tentatively assume that
471*9880d681SAndroid Build Coastguard Worker // field zero was selected (since the zero offset would obviously
472*9880d681SAndroid Build Coastguard Worker // be folded away).
473*9880d681SAndroid Build Coastguard Worker if (!FoundFieldNo) {
474*9880d681SAndroid Build Coastguard Worker ElTy = STy->getTypeAtIndex(0u);
475*9880d681SAndroid Build Coastguard Worker GepIndices.push_back(
476*9880d681SAndroid Build Coastguard Worker Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
477*9880d681SAndroid Build Coastguard Worker }
478*9880d681SAndroid Build Coastguard Worker }
479*9880d681SAndroid Build Coastguard Worker
480*9880d681SAndroid Build Coastguard Worker if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
481*9880d681SAndroid Build Coastguard Worker ElTy = ATy->getElementType();
482*9880d681SAndroid Build Coastguard Worker else
483*9880d681SAndroid Build Coastguard Worker break;
484*9880d681SAndroid Build Coastguard Worker }
485*9880d681SAndroid Build Coastguard Worker
486*9880d681SAndroid Build Coastguard Worker // If none of the operands were convertible to proper GEP indices, cast
487*9880d681SAndroid Build Coastguard Worker // the base to i8* and do an ugly getelementptr with that. It's still
488*9880d681SAndroid Build Coastguard Worker // better than ptrtoint+arithmetic+inttoptr at least.
489*9880d681SAndroid Build Coastguard Worker if (!AnyNonZeroIndices) {
490*9880d681SAndroid Build Coastguard Worker // Cast the base to i8*.
491*9880d681SAndroid Build Coastguard Worker V = InsertNoopCastOfTo(V,
492*9880d681SAndroid Build Coastguard Worker Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
493*9880d681SAndroid Build Coastguard Worker
494*9880d681SAndroid Build Coastguard Worker assert(!isa<Instruction>(V) ||
495*9880d681SAndroid Build Coastguard Worker SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
496*9880d681SAndroid Build Coastguard Worker
497*9880d681SAndroid Build Coastguard Worker // Expand the operands for a plain byte offset.
498*9880d681SAndroid Build Coastguard Worker Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
499*9880d681SAndroid Build Coastguard Worker
500*9880d681SAndroid Build Coastguard Worker // Fold a GEP with constant operands.
501*9880d681SAndroid Build Coastguard Worker if (Constant *CLHS = dyn_cast<Constant>(V))
502*9880d681SAndroid Build Coastguard Worker if (Constant *CRHS = dyn_cast<Constant>(Idx))
503*9880d681SAndroid Build Coastguard Worker return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
504*9880d681SAndroid Build Coastguard Worker CLHS, CRHS);
505*9880d681SAndroid Build Coastguard Worker
506*9880d681SAndroid Build Coastguard Worker // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
507*9880d681SAndroid Build Coastguard Worker unsigned ScanLimit = 6;
508*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
509*9880d681SAndroid Build Coastguard Worker // Scanning starts from the last instruction before the insertion point.
510*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator IP = Builder.GetInsertPoint();
511*9880d681SAndroid Build Coastguard Worker if (IP != BlockBegin) {
512*9880d681SAndroid Build Coastguard Worker --IP;
513*9880d681SAndroid Build Coastguard Worker for (; ScanLimit; --IP, --ScanLimit) {
514*9880d681SAndroid Build Coastguard Worker // Don't count dbg.value against the ScanLimit, to avoid perturbing the
515*9880d681SAndroid Build Coastguard Worker // generated code.
516*9880d681SAndroid Build Coastguard Worker if (isa<DbgInfoIntrinsic>(IP))
517*9880d681SAndroid Build Coastguard Worker ScanLimit++;
518*9880d681SAndroid Build Coastguard Worker if (IP->getOpcode() == Instruction::GetElementPtr &&
519*9880d681SAndroid Build Coastguard Worker IP->getOperand(0) == V && IP->getOperand(1) == Idx)
520*9880d681SAndroid Build Coastguard Worker return &*IP;
521*9880d681SAndroid Build Coastguard Worker if (IP == BlockBegin) break;
522*9880d681SAndroid Build Coastguard Worker }
523*9880d681SAndroid Build Coastguard Worker }
524*9880d681SAndroid Build Coastguard Worker
525*9880d681SAndroid Build Coastguard Worker // Save the original insertion point so we can restore it when we're done.
526*9880d681SAndroid Build Coastguard Worker SCEVInsertPointGuard Guard(Builder, this);
527*9880d681SAndroid Build Coastguard Worker
528*9880d681SAndroid Build Coastguard Worker // Move the insertion point out of as many loops as we can.
529*9880d681SAndroid Build Coastguard Worker while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
530*9880d681SAndroid Build Coastguard Worker if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
531*9880d681SAndroid Build Coastguard Worker BasicBlock *Preheader = L->getLoopPreheader();
532*9880d681SAndroid Build Coastguard Worker if (!Preheader) break;
533*9880d681SAndroid Build Coastguard Worker
534*9880d681SAndroid Build Coastguard Worker // Ok, move up a level.
535*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(Preheader->getTerminator());
536*9880d681SAndroid Build Coastguard Worker }
537*9880d681SAndroid Build Coastguard Worker
538*9880d681SAndroid Build Coastguard Worker // Emit a GEP.
539*9880d681SAndroid Build Coastguard Worker Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
540*9880d681SAndroid Build Coastguard Worker rememberInstruction(GEP);
541*9880d681SAndroid Build Coastguard Worker
542*9880d681SAndroid Build Coastguard Worker return GEP;
543*9880d681SAndroid Build Coastguard Worker }
544*9880d681SAndroid Build Coastguard Worker
545*9880d681SAndroid Build Coastguard Worker {
546*9880d681SAndroid Build Coastguard Worker SCEVInsertPointGuard Guard(Builder, this);
547*9880d681SAndroid Build Coastguard Worker
548*9880d681SAndroid Build Coastguard Worker // Move the insertion point out of as many loops as we can.
549*9880d681SAndroid Build Coastguard Worker while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
550*9880d681SAndroid Build Coastguard Worker if (!L->isLoopInvariant(V)) break;
551*9880d681SAndroid Build Coastguard Worker
552*9880d681SAndroid Build Coastguard Worker bool AnyIndexNotLoopInvariant =
553*9880d681SAndroid Build Coastguard Worker std::any_of(GepIndices.begin(), GepIndices.end(),
554*9880d681SAndroid Build Coastguard Worker [L](Value *Op) { return !L->isLoopInvariant(Op); });
555*9880d681SAndroid Build Coastguard Worker
556*9880d681SAndroid Build Coastguard Worker if (AnyIndexNotLoopInvariant)
557*9880d681SAndroid Build Coastguard Worker break;
558*9880d681SAndroid Build Coastguard Worker
559*9880d681SAndroid Build Coastguard Worker BasicBlock *Preheader = L->getLoopPreheader();
560*9880d681SAndroid Build Coastguard Worker if (!Preheader) break;
561*9880d681SAndroid Build Coastguard Worker
562*9880d681SAndroid Build Coastguard Worker // Ok, move up a level.
563*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(Preheader->getTerminator());
564*9880d681SAndroid Build Coastguard Worker }
565*9880d681SAndroid Build Coastguard Worker
566*9880d681SAndroid Build Coastguard Worker // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
567*9880d681SAndroid Build Coastguard Worker // because ScalarEvolution may have changed the address arithmetic to
568*9880d681SAndroid Build Coastguard Worker // compute a value which is beyond the end of the allocated object.
569*9880d681SAndroid Build Coastguard Worker Value *Casted = V;
570*9880d681SAndroid Build Coastguard Worker if (V->getType() != PTy)
571*9880d681SAndroid Build Coastguard Worker Casted = InsertNoopCastOfTo(Casted, PTy);
572*9880d681SAndroid Build Coastguard Worker Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep");
573*9880d681SAndroid Build Coastguard Worker Ops.push_back(SE.getUnknown(GEP));
574*9880d681SAndroid Build Coastguard Worker rememberInstruction(GEP);
575*9880d681SAndroid Build Coastguard Worker }
576*9880d681SAndroid Build Coastguard Worker
577*9880d681SAndroid Build Coastguard Worker return expand(SE.getAddExpr(Ops));
578*9880d681SAndroid Build Coastguard Worker }
579*9880d681SAndroid Build Coastguard Worker
580*9880d681SAndroid Build Coastguard Worker /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
581*9880d681SAndroid Build Coastguard Worker /// SCEV expansion. If they are nested, this is the most nested. If they are
582*9880d681SAndroid Build Coastguard Worker /// neighboring, pick the later.
PickMostRelevantLoop(const Loop * A,const Loop * B,DominatorTree & DT)583*9880d681SAndroid Build Coastguard Worker static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
584*9880d681SAndroid Build Coastguard Worker DominatorTree &DT) {
585*9880d681SAndroid Build Coastguard Worker if (!A) return B;
586*9880d681SAndroid Build Coastguard Worker if (!B) return A;
587*9880d681SAndroid Build Coastguard Worker if (A->contains(B)) return B;
588*9880d681SAndroid Build Coastguard Worker if (B->contains(A)) return A;
589*9880d681SAndroid Build Coastguard Worker if (DT.dominates(A->getHeader(), B->getHeader())) return B;
590*9880d681SAndroid Build Coastguard Worker if (DT.dominates(B->getHeader(), A->getHeader())) return A;
591*9880d681SAndroid Build Coastguard Worker return A; // Arbitrarily break the tie.
592*9880d681SAndroid Build Coastguard Worker }
593*9880d681SAndroid Build Coastguard Worker
594*9880d681SAndroid Build Coastguard Worker /// getRelevantLoop - Get the most relevant loop associated with the given
595*9880d681SAndroid Build Coastguard Worker /// expression, according to PickMostRelevantLoop.
getRelevantLoop(const SCEV * S)596*9880d681SAndroid Build Coastguard Worker const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
597*9880d681SAndroid Build Coastguard Worker // Test whether we've already computed the most relevant loop for this SCEV.
598*9880d681SAndroid Build Coastguard Worker auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
599*9880d681SAndroid Build Coastguard Worker if (!Pair.second)
600*9880d681SAndroid Build Coastguard Worker return Pair.first->second;
601*9880d681SAndroid Build Coastguard Worker
602*9880d681SAndroid Build Coastguard Worker if (isa<SCEVConstant>(S))
603*9880d681SAndroid Build Coastguard Worker // A constant has no relevant loops.
604*9880d681SAndroid Build Coastguard Worker return nullptr;
605*9880d681SAndroid Build Coastguard Worker if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
606*9880d681SAndroid Build Coastguard Worker if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
607*9880d681SAndroid Build Coastguard Worker return Pair.first->second = SE.LI.getLoopFor(I->getParent());
608*9880d681SAndroid Build Coastguard Worker // A non-instruction has no relevant loops.
609*9880d681SAndroid Build Coastguard Worker return nullptr;
610*9880d681SAndroid Build Coastguard Worker }
611*9880d681SAndroid Build Coastguard Worker if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
612*9880d681SAndroid Build Coastguard Worker const Loop *L = nullptr;
613*9880d681SAndroid Build Coastguard Worker if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
614*9880d681SAndroid Build Coastguard Worker L = AR->getLoop();
615*9880d681SAndroid Build Coastguard Worker for (const SCEV *Op : N->operands())
616*9880d681SAndroid Build Coastguard Worker L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
617*9880d681SAndroid Build Coastguard Worker return RelevantLoops[N] = L;
618*9880d681SAndroid Build Coastguard Worker }
619*9880d681SAndroid Build Coastguard Worker if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
620*9880d681SAndroid Build Coastguard Worker const Loop *Result = getRelevantLoop(C->getOperand());
621*9880d681SAndroid Build Coastguard Worker return RelevantLoops[C] = Result;
622*9880d681SAndroid Build Coastguard Worker }
623*9880d681SAndroid Build Coastguard Worker if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
624*9880d681SAndroid Build Coastguard Worker const Loop *Result = PickMostRelevantLoop(
625*9880d681SAndroid Build Coastguard Worker getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
626*9880d681SAndroid Build Coastguard Worker return RelevantLoops[D] = Result;
627*9880d681SAndroid Build Coastguard Worker }
628*9880d681SAndroid Build Coastguard Worker llvm_unreachable("Unexpected SCEV type!");
629*9880d681SAndroid Build Coastguard Worker }
630*9880d681SAndroid Build Coastguard Worker
631*9880d681SAndroid Build Coastguard Worker namespace {
632*9880d681SAndroid Build Coastguard Worker
633*9880d681SAndroid Build Coastguard Worker /// LoopCompare - Compare loops by PickMostRelevantLoop.
634*9880d681SAndroid Build Coastguard Worker class LoopCompare {
635*9880d681SAndroid Build Coastguard Worker DominatorTree &DT;
636*9880d681SAndroid Build Coastguard Worker public:
LoopCompare(DominatorTree & dt)637*9880d681SAndroid Build Coastguard Worker explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
638*9880d681SAndroid Build Coastguard Worker
operator ()(std::pair<const Loop *,const SCEV * > LHS,std::pair<const Loop *,const SCEV * > RHS) const639*9880d681SAndroid Build Coastguard Worker bool operator()(std::pair<const Loop *, const SCEV *> LHS,
640*9880d681SAndroid Build Coastguard Worker std::pair<const Loop *, const SCEV *> RHS) const {
641*9880d681SAndroid Build Coastguard Worker // Keep pointer operands sorted at the end.
642*9880d681SAndroid Build Coastguard Worker if (LHS.second->getType()->isPointerTy() !=
643*9880d681SAndroid Build Coastguard Worker RHS.second->getType()->isPointerTy())
644*9880d681SAndroid Build Coastguard Worker return LHS.second->getType()->isPointerTy();
645*9880d681SAndroid Build Coastguard Worker
646*9880d681SAndroid Build Coastguard Worker // Compare loops with PickMostRelevantLoop.
647*9880d681SAndroid Build Coastguard Worker if (LHS.first != RHS.first)
648*9880d681SAndroid Build Coastguard Worker return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
649*9880d681SAndroid Build Coastguard Worker
650*9880d681SAndroid Build Coastguard Worker // If one operand is a non-constant negative and the other is not,
651*9880d681SAndroid Build Coastguard Worker // put the non-constant negative on the right so that a sub can
652*9880d681SAndroid Build Coastguard Worker // be used instead of a negate and add.
653*9880d681SAndroid Build Coastguard Worker if (LHS.second->isNonConstantNegative()) {
654*9880d681SAndroid Build Coastguard Worker if (!RHS.second->isNonConstantNegative())
655*9880d681SAndroid Build Coastguard Worker return false;
656*9880d681SAndroid Build Coastguard Worker } else if (RHS.second->isNonConstantNegative())
657*9880d681SAndroid Build Coastguard Worker return true;
658*9880d681SAndroid Build Coastguard Worker
659*9880d681SAndroid Build Coastguard Worker // Otherwise they are equivalent according to this comparison.
660*9880d681SAndroid Build Coastguard Worker return false;
661*9880d681SAndroid Build Coastguard Worker }
662*9880d681SAndroid Build Coastguard Worker };
663*9880d681SAndroid Build Coastguard Worker
664*9880d681SAndroid Build Coastguard Worker }
665*9880d681SAndroid Build Coastguard Worker
visitAddExpr(const SCEVAddExpr * S)666*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
667*9880d681SAndroid Build Coastguard Worker Type *Ty = SE.getEffectiveSCEVType(S->getType());
668*9880d681SAndroid Build Coastguard Worker
669*9880d681SAndroid Build Coastguard Worker // Collect all the add operands in a loop, along with their associated loops.
670*9880d681SAndroid Build Coastguard Worker // Iterate in reverse so that constants are emitted last, all else equal, and
671*9880d681SAndroid Build Coastguard Worker // so that pointer operands are inserted first, which the code below relies on
672*9880d681SAndroid Build Coastguard Worker // to form more involved GEPs.
673*9880d681SAndroid Build Coastguard Worker SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
674*9880d681SAndroid Build Coastguard Worker for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
675*9880d681SAndroid Build Coastguard Worker E(S->op_begin()); I != E; ++I)
676*9880d681SAndroid Build Coastguard Worker OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
677*9880d681SAndroid Build Coastguard Worker
678*9880d681SAndroid Build Coastguard Worker // Sort by loop. Use a stable sort so that constants follow non-constants and
679*9880d681SAndroid Build Coastguard Worker // pointer operands precede non-pointer operands.
680*9880d681SAndroid Build Coastguard Worker std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
681*9880d681SAndroid Build Coastguard Worker
682*9880d681SAndroid Build Coastguard Worker // Emit instructions to add all the operands. Hoist as much as possible
683*9880d681SAndroid Build Coastguard Worker // out of loops, and form meaningful getelementptrs where possible.
684*9880d681SAndroid Build Coastguard Worker Value *Sum = nullptr;
685*9880d681SAndroid Build Coastguard Worker for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
686*9880d681SAndroid Build Coastguard Worker const Loop *CurLoop = I->first;
687*9880d681SAndroid Build Coastguard Worker const SCEV *Op = I->second;
688*9880d681SAndroid Build Coastguard Worker if (!Sum) {
689*9880d681SAndroid Build Coastguard Worker // This is the first operand. Just expand it.
690*9880d681SAndroid Build Coastguard Worker Sum = expand(Op);
691*9880d681SAndroid Build Coastguard Worker ++I;
692*9880d681SAndroid Build Coastguard Worker } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
693*9880d681SAndroid Build Coastguard Worker // The running sum expression is a pointer. Try to form a getelementptr
694*9880d681SAndroid Build Coastguard Worker // at this level with that as the base.
695*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 4> NewOps;
696*9880d681SAndroid Build Coastguard Worker for (; I != E && I->first == CurLoop; ++I) {
697*9880d681SAndroid Build Coastguard Worker // If the operand is SCEVUnknown and not instructions, peek through
698*9880d681SAndroid Build Coastguard Worker // it, to enable more of it to be folded into the GEP.
699*9880d681SAndroid Build Coastguard Worker const SCEV *X = I->second;
700*9880d681SAndroid Build Coastguard Worker if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
701*9880d681SAndroid Build Coastguard Worker if (!isa<Instruction>(U->getValue()))
702*9880d681SAndroid Build Coastguard Worker X = SE.getSCEV(U->getValue());
703*9880d681SAndroid Build Coastguard Worker NewOps.push_back(X);
704*9880d681SAndroid Build Coastguard Worker }
705*9880d681SAndroid Build Coastguard Worker Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
706*9880d681SAndroid Build Coastguard Worker } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
707*9880d681SAndroid Build Coastguard Worker // The running sum is an integer, and there's a pointer at this level.
708*9880d681SAndroid Build Coastguard Worker // Try to form a getelementptr. If the running sum is instructions,
709*9880d681SAndroid Build Coastguard Worker // use a SCEVUnknown to avoid re-analyzing them.
710*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 4> NewOps;
711*9880d681SAndroid Build Coastguard Worker NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
712*9880d681SAndroid Build Coastguard Worker SE.getSCEV(Sum));
713*9880d681SAndroid Build Coastguard Worker for (++I; I != E && I->first == CurLoop; ++I)
714*9880d681SAndroid Build Coastguard Worker NewOps.push_back(I->second);
715*9880d681SAndroid Build Coastguard Worker Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
716*9880d681SAndroid Build Coastguard Worker } else if (Op->isNonConstantNegative()) {
717*9880d681SAndroid Build Coastguard Worker // Instead of doing a negate and add, just do a subtract.
718*9880d681SAndroid Build Coastguard Worker Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
719*9880d681SAndroid Build Coastguard Worker Sum = InsertNoopCastOfTo(Sum, Ty);
720*9880d681SAndroid Build Coastguard Worker Sum = InsertBinop(Instruction::Sub, Sum, W);
721*9880d681SAndroid Build Coastguard Worker ++I;
722*9880d681SAndroid Build Coastguard Worker } else {
723*9880d681SAndroid Build Coastguard Worker // A simple add.
724*9880d681SAndroid Build Coastguard Worker Value *W = expandCodeFor(Op, Ty);
725*9880d681SAndroid Build Coastguard Worker Sum = InsertNoopCastOfTo(Sum, Ty);
726*9880d681SAndroid Build Coastguard Worker // Canonicalize a constant to the RHS.
727*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(Sum)) std::swap(Sum, W);
728*9880d681SAndroid Build Coastguard Worker Sum = InsertBinop(Instruction::Add, Sum, W);
729*9880d681SAndroid Build Coastguard Worker ++I;
730*9880d681SAndroid Build Coastguard Worker }
731*9880d681SAndroid Build Coastguard Worker }
732*9880d681SAndroid Build Coastguard Worker
733*9880d681SAndroid Build Coastguard Worker return Sum;
734*9880d681SAndroid Build Coastguard Worker }
735*9880d681SAndroid Build Coastguard Worker
visitMulExpr(const SCEVMulExpr * S)736*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
737*9880d681SAndroid Build Coastguard Worker Type *Ty = SE.getEffectiveSCEVType(S->getType());
738*9880d681SAndroid Build Coastguard Worker
739*9880d681SAndroid Build Coastguard Worker // Collect all the mul operands in a loop, along with their associated loops.
740*9880d681SAndroid Build Coastguard Worker // Iterate in reverse so that constants are emitted last, all else equal.
741*9880d681SAndroid Build Coastguard Worker SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
742*9880d681SAndroid Build Coastguard Worker for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
743*9880d681SAndroid Build Coastguard Worker E(S->op_begin()); I != E; ++I)
744*9880d681SAndroid Build Coastguard Worker OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
745*9880d681SAndroid Build Coastguard Worker
746*9880d681SAndroid Build Coastguard Worker // Sort by loop. Use a stable sort so that constants follow non-constants.
747*9880d681SAndroid Build Coastguard Worker std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
748*9880d681SAndroid Build Coastguard Worker
749*9880d681SAndroid Build Coastguard Worker // Emit instructions to mul all the operands. Hoist as much as possible
750*9880d681SAndroid Build Coastguard Worker // out of loops.
751*9880d681SAndroid Build Coastguard Worker Value *Prod = nullptr;
752*9880d681SAndroid Build Coastguard Worker for (const auto &I : OpsAndLoops) {
753*9880d681SAndroid Build Coastguard Worker const SCEV *Op = I.second;
754*9880d681SAndroid Build Coastguard Worker if (!Prod) {
755*9880d681SAndroid Build Coastguard Worker // This is the first operand. Just expand it.
756*9880d681SAndroid Build Coastguard Worker Prod = expand(Op);
757*9880d681SAndroid Build Coastguard Worker } else if (Op->isAllOnesValue()) {
758*9880d681SAndroid Build Coastguard Worker // Instead of doing a multiply by negative one, just do a negate.
759*9880d681SAndroid Build Coastguard Worker Prod = InsertNoopCastOfTo(Prod, Ty);
760*9880d681SAndroid Build Coastguard Worker Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
761*9880d681SAndroid Build Coastguard Worker } else {
762*9880d681SAndroid Build Coastguard Worker // A simple mul.
763*9880d681SAndroid Build Coastguard Worker Value *W = expandCodeFor(Op, Ty);
764*9880d681SAndroid Build Coastguard Worker Prod = InsertNoopCastOfTo(Prod, Ty);
765*9880d681SAndroid Build Coastguard Worker // Canonicalize a constant to the RHS.
766*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(Prod)) std::swap(Prod, W);
767*9880d681SAndroid Build Coastguard Worker const APInt *RHS;
768*9880d681SAndroid Build Coastguard Worker if (match(W, m_Power2(RHS))) {
769*9880d681SAndroid Build Coastguard Worker // Canonicalize Prod*(1<<C) to Prod<<C.
770*9880d681SAndroid Build Coastguard Worker assert(!Ty->isVectorTy() && "vector types are not SCEVable");
771*9880d681SAndroid Build Coastguard Worker Prod = InsertBinop(Instruction::Shl, Prod,
772*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Ty, RHS->logBase2()));
773*9880d681SAndroid Build Coastguard Worker } else {
774*9880d681SAndroid Build Coastguard Worker Prod = InsertBinop(Instruction::Mul, Prod, W);
775*9880d681SAndroid Build Coastguard Worker }
776*9880d681SAndroid Build Coastguard Worker }
777*9880d681SAndroid Build Coastguard Worker }
778*9880d681SAndroid Build Coastguard Worker
779*9880d681SAndroid Build Coastguard Worker return Prod;
780*9880d681SAndroid Build Coastguard Worker }
781*9880d681SAndroid Build Coastguard Worker
visitUDivExpr(const SCEVUDivExpr * S)782*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
783*9880d681SAndroid Build Coastguard Worker Type *Ty = SE.getEffectiveSCEVType(S->getType());
784*9880d681SAndroid Build Coastguard Worker
785*9880d681SAndroid Build Coastguard Worker Value *LHS = expandCodeFor(S->getLHS(), Ty);
786*9880d681SAndroid Build Coastguard Worker if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
787*9880d681SAndroid Build Coastguard Worker const APInt &RHS = SC->getAPInt();
788*9880d681SAndroid Build Coastguard Worker if (RHS.isPowerOf2())
789*9880d681SAndroid Build Coastguard Worker return InsertBinop(Instruction::LShr, LHS,
790*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Ty, RHS.logBase2()));
791*9880d681SAndroid Build Coastguard Worker }
792*9880d681SAndroid Build Coastguard Worker
793*9880d681SAndroid Build Coastguard Worker Value *RHS = expandCodeFor(S->getRHS(), Ty);
794*9880d681SAndroid Build Coastguard Worker return InsertBinop(Instruction::UDiv, LHS, RHS);
795*9880d681SAndroid Build Coastguard Worker }
796*9880d681SAndroid Build Coastguard Worker
797*9880d681SAndroid Build Coastguard Worker /// Move parts of Base into Rest to leave Base with the minimal
798*9880d681SAndroid Build Coastguard Worker /// expression that provides a pointer operand suitable for a
799*9880d681SAndroid Build Coastguard Worker /// GEP expansion.
ExposePointerBase(const SCEV * & Base,const SCEV * & Rest,ScalarEvolution & SE)800*9880d681SAndroid Build Coastguard Worker static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
801*9880d681SAndroid Build Coastguard Worker ScalarEvolution &SE) {
802*9880d681SAndroid Build Coastguard Worker while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
803*9880d681SAndroid Build Coastguard Worker Base = A->getStart();
804*9880d681SAndroid Build Coastguard Worker Rest = SE.getAddExpr(Rest,
805*9880d681SAndroid Build Coastguard Worker SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
806*9880d681SAndroid Build Coastguard Worker A->getStepRecurrence(SE),
807*9880d681SAndroid Build Coastguard Worker A->getLoop(),
808*9880d681SAndroid Build Coastguard Worker A->getNoWrapFlags(SCEV::FlagNW)));
809*9880d681SAndroid Build Coastguard Worker }
810*9880d681SAndroid Build Coastguard Worker if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
811*9880d681SAndroid Build Coastguard Worker Base = A->getOperand(A->getNumOperands()-1);
812*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
813*9880d681SAndroid Build Coastguard Worker NewAddOps.back() = Rest;
814*9880d681SAndroid Build Coastguard Worker Rest = SE.getAddExpr(NewAddOps);
815*9880d681SAndroid Build Coastguard Worker ExposePointerBase(Base, Rest, SE);
816*9880d681SAndroid Build Coastguard Worker }
817*9880d681SAndroid Build Coastguard Worker }
818*9880d681SAndroid Build Coastguard Worker
819*9880d681SAndroid Build Coastguard Worker /// Determine if this is a well-behaved chain of instructions leading back to
820*9880d681SAndroid Build Coastguard Worker /// the PHI. If so, it may be reused by expanded expressions.
isNormalAddRecExprPHI(PHINode * PN,Instruction * IncV,const Loop * L)821*9880d681SAndroid Build Coastguard Worker bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
822*9880d681SAndroid Build Coastguard Worker const Loop *L) {
823*9880d681SAndroid Build Coastguard Worker if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
824*9880d681SAndroid Build Coastguard Worker (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
825*9880d681SAndroid Build Coastguard Worker return false;
826*9880d681SAndroid Build Coastguard Worker // If any of the operands don't dominate the insert position, bail.
827*9880d681SAndroid Build Coastguard Worker // Addrec operands are always loop-invariant, so this can only happen
828*9880d681SAndroid Build Coastguard Worker // if there are instructions which haven't been hoisted.
829*9880d681SAndroid Build Coastguard Worker if (L == IVIncInsertLoop) {
830*9880d681SAndroid Build Coastguard Worker for (User::op_iterator OI = IncV->op_begin()+1,
831*9880d681SAndroid Build Coastguard Worker OE = IncV->op_end(); OI != OE; ++OI)
832*9880d681SAndroid Build Coastguard Worker if (Instruction *OInst = dyn_cast<Instruction>(OI))
833*9880d681SAndroid Build Coastguard Worker if (!SE.DT.dominates(OInst, IVIncInsertPos))
834*9880d681SAndroid Build Coastguard Worker return false;
835*9880d681SAndroid Build Coastguard Worker }
836*9880d681SAndroid Build Coastguard Worker // Advance to the next instruction.
837*9880d681SAndroid Build Coastguard Worker IncV = dyn_cast<Instruction>(IncV->getOperand(0));
838*9880d681SAndroid Build Coastguard Worker if (!IncV)
839*9880d681SAndroid Build Coastguard Worker return false;
840*9880d681SAndroid Build Coastguard Worker
841*9880d681SAndroid Build Coastguard Worker if (IncV->mayHaveSideEffects())
842*9880d681SAndroid Build Coastguard Worker return false;
843*9880d681SAndroid Build Coastguard Worker
844*9880d681SAndroid Build Coastguard Worker if (IncV != PN)
845*9880d681SAndroid Build Coastguard Worker return true;
846*9880d681SAndroid Build Coastguard Worker
847*9880d681SAndroid Build Coastguard Worker return isNormalAddRecExprPHI(PN, IncV, L);
848*9880d681SAndroid Build Coastguard Worker }
849*9880d681SAndroid Build Coastguard Worker
850*9880d681SAndroid Build Coastguard Worker /// getIVIncOperand returns an induction variable increment's induction
851*9880d681SAndroid Build Coastguard Worker /// variable operand.
852*9880d681SAndroid Build Coastguard Worker ///
853*9880d681SAndroid Build Coastguard Worker /// If allowScale is set, any type of GEP is allowed as long as the nonIV
854*9880d681SAndroid Build Coastguard Worker /// operands dominate InsertPos.
855*9880d681SAndroid Build Coastguard Worker ///
856*9880d681SAndroid Build Coastguard Worker /// If allowScale is not set, ensure that a GEP increment conforms to one of the
857*9880d681SAndroid Build Coastguard Worker /// simple patterns generated by getAddRecExprPHILiterally and
858*9880d681SAndroid Build Coastguard Worker /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
getIVIncOperand(Instruction * IncV,Instruction * InsertPos,bool allowScale)859*9880d681SAndroid Build Coastguard Worker Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
860*9880d681SAndroid Build Coastguard Worker Instruction *InsertPos,
861*9880d681SAndroid Build Coastguard Worker bool allowScale) {
862*9880d681SAndroid Build Coastguard Worker if (IncV == InsertPos)
863*9880d681SAndroid Build Coastguard Worker return nullptr;
864*9880d681SAndroid Build Coastguard Worker
865*9880d681SAndroid Build Coastguard Worker switch (IncV->getOpcode()) {
866*9880d681SAndroid Build Coastguard Worker default:
867*9880d681SAndroid Build Coastguard Worker return nullptr;
868*9880d681SAndroid Build Coastguard Worker // Check for a simple Add/Sub or GEP of a loop invariant step.
869*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
870*9880d681SAndroid Build Coastguard Worker case Instruction::Sub: {
871*9880d681SAndroid Build Coastguard Worker Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
872*9880d681SAndroid Build Coastguard Worker if (!OInst || SE.DT.dominates(OInst, InsertPos))
873*9880d681SAndroid Build Coastguard Worker return dyn_cast<Instruction>(IncV->getOperand(0));
874*9880d681SAndroid Build Coastguard Worker return nullptr;
875*9880d681SAndroid Build Coastguard Worker }
876*9880d681SAndroid Build Coastguard Worker case Instruction::BitCast:
877*9880d681SAndroid Build Coastguard Worker return dyn_cast<Instruction>(IncV->getOperand(0));
878*9880d681SAndroid Build Coastguard Worker case Instruction::GetElementPtr:
879*9880d681SAndroid Build Coastguard Worker for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) {
880*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(*I))
881*9880d681SAndroid Build Coastguard Worker continue;
882*9880d681SAndroid Build Coastguard Worker if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
883*9880d681SAndroid Build Coastguard Worker if (!SE.DT.dominates(OInst, InsertPos))
884*9880d681SAndroid Build Coastguard Worker return nullptr;
885*9880d681SAndroid Build Coastguard Worker }
886*9880d681SAndroid Build Coastguard Worker if (allowScale) {
887*9880d681SAndroid Build Coastguard Worker // allow any kind of GEP as long as it can be hoisted.
888*9880d681SAndroid Build Coastguard Worker continue;
889*9880d681SAndroid Build Coastguard Worker }
890*9880d681SAndroid Build Coastguard Worker // This must be a pointer addition of constants (pretty), which is already
891*9880d681SAndroid Build Coastguard Worker // handled, or some number of address-size elements (ugly). Ugly geps
892*9880d681SAndroid Build Coastguard Worker // have 2 operands. i1* is used by the expander to represent an
893*9880d681SAndroid Build Coastguard Worker // address-size element.
894*9880d681SAndroid Build Coastguard Worker if (IncV->getNumOperands() != 2)
895*9880d681SAndroid Build Coastguard Worker return nullptr;
896*9880d681SAndroid Build Coastguard Worker unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
897*9880d681SAndroid Build Coastguard Worker if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
898*9880d681SAndroid Build Coastguard Worker && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
899*9880d681SAndroid Build Coastguard Worker return nullptr;
900*9880d681SAndroid Build Coastguard Worker break;
901*9880d681SAndroid Build Coastguard Worker }
902*9880d681SAndroid Build Coastguard Worker return dyn_cast<Instruction>(IncV->getOperand(0));
903*9880d681SAndroid Build Coastguard Worker }
904*9880d681SAndroid Build Coastguard Worker }
905*9880d681SAndroid Build Coastguard Worker
906*9880d681SAndroid Build Coastguard Worker /// If the insert point of the current builder or any of the builders on the
907*9880d681SAndroid Build Coastguard Worker /// stack of saved builders has 'I' as its insert point, update it to point to
908*9880d681SAndroid Build Coastguard Worker /// the instruction after 'I'. This is intended to be used when the instruction
909*9880d681SAndroid Build Coastguard Worker /// 'I' is being moved. If this fixup is not done and 'I' is moved to a
910*9880d681SAndroid Build Coastguard Worker /// different block, the inconsistent insert point (with a mismatched
911*9880d681SAndroid Build Coastguard Worker /// Instruction and Block) can lead to an instruction being inserted in a block
912*9880d681SAndroid Build Coastguard Worker /// other than its parent.
fixupInsertPoints(Instruction * I)913*9880d681SAndroid Build Coastguard Worker void SCEVExpander::fixupInsertPoints(Instruction *I) {
914*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator It(*I);
915*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator NewInsertPt = std::next(It);
916*9880d681SAndroid Build Coastguard Worker if (Builder.GetInsertPoint() == It)
917*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(&*NewInsertPt);
918*9880d681SAndroid Build Coastguard Worker for (auto *InsertPtGuard : InsertPointGuards)
919*9880d681SAndroid Build Coastguard Worker if (InsertPtGuard->GetInsertPoint() == It)
920*9880d681SAndroid Build Coastguard Worker InsertPtGuard->SetInsertPoint(NewInsertPt);
921*9880d681SAndroid Build Coastguard Worker }
922*9880d681SAndroid Build Coastguard Worker
923*9880d681SAndroid Build Coastguard Worker /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
924*9880d681SAndroid Build Coastguard Worker /// it available to other uses in this loop. Recursively hoist any operands,
925*9880d681SAndroid Build Coastguard Worker /// until we reach a value that dominates InsertPos.
hoistIVInc(Instruction * IncV,Instruction * InsertPos)926*9880d681SAndroid Build Coastguard Worker bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
927*9880d681SAndroid Build Coastguard Worker if (SE.DT.dominates(IncV, InsertPos))
928*9880d681SAndroid Build Coastguard Worker return true;
929*9880d681SAndroid Build Coastguard Worker
930*9880d681SAndroid Build Coastguard Worker // InsertPos must itself dominate IncV so that IncV's new position satisfies
931*9880d681SAndroid Build Coastguard Worker // its existing users.
932*9880d681SAndroid Build Coastguard Worker if (isa<PHINode>(InsertPos) ||
933*9880d681SAndroid Build Coastguard Worker !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
934*9880d681SAndroid Build Coastguard Worker return false;
935*9880d681SAndroid Build Coastguard Worker
936*9880d681SAndroid Build Coastguard Worker if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
937*9880d681SAndroid Build Coastguard Worker return false;
938*9880d681SAndroid Build Coastguard Worker
939*9880d681SAndroid Build Coastguard Worker // Check that the chain of IV operands leading back to Phi can be hoisted.
940*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction*, 4> IVIncs;
941*9880d681SAndroid Build Coastguard Worker for(;;) {
942*9880d681SAndroid Build Coastguard Worker Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
943*9880d681SAndroid Build Coastguard Worker if (!Oper)
944*9880d681SAndroid Build Coastguard Worker return false;
945*9880d681SAndroid Build Coastguard Worker // IncV is safe to hoist.
946*9880d681SAndroid Build Coastguard Worker IVIncs.push_back(IncV);
947*9880d681SAndroid Build Coastguard Worker IncV = Oper;
948*9880d681SAndroid Build Coastguard Worker if (SE.DT.dominates(IncV, InsertPos))
949*9880d681SAndroid Build Coastguard Worker break;
950*9880d681SAndroid Build Coastguard Worker }
951*9880d681SAndroid Build Coastguard Worker for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) {
952*9880d681SAndroid Build Coastguard Worker fixupInsertPoints(*I);
953*9880d681SAndroid Build Coastguard Worker (*I)->moveBefore(InsertPos);
954*9880d681SAndroid Build Coastguard Worker }
955*9880d681SAndroid Build Coastguard Worker return true;
956*9880d681SAndroid Build Coastguard Worker }
957*9880d681SAndroid Build Coastguard Worker
958*9880d681SAndroid Build Coastguard Worker /// Determine if this cyclic phi is in a form that would have been generated by
959*9880d681SAndroid Build Coastguard Worker /// LSR. We don't care if the phi was actually expanded in this pass, as long
960*9880d681SAndroid Build Coastguard Worker /// as it is in a low-cost form, for example, no implied multiplication. This
961*9880d681SAndroid Build Coastguard Worker /// should match any patterns generated by getAddRecExprPHILiterally and
962*9880d681SAndroid Build Coastguard Worker /// expandAddtoGEP.
isExpandedAddRecExprPHI(PHINode * PN,Instruction * IncV,const Loop * L)963*9880d681SAndroid Build Coastguard Worker bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
964*9880d681SAndroid Build Coastguard Worker const Loop *L) {
965*9880d681SAndroid Build Coastguard Worker for(Instruction *IVOper = IncV;
966*9880d681SAndroid Build Coastguard Worker (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
967*9880d681SAndroid Build Coastguard Worker /*allowScale=*/false));) {
968*9880d681SAndroid Build Coastguard Worker if (IVOper == PN)
969*9880d681SAndroid Build Coastguard Worker return true;
970*9880d681SAndroid Build Coastguard Worker }
971*9880d681SAndroid Build Coastguard Worker return false;
972*9880d681SAndroid Build Coastguard Worker }
973*9880d681SAndroid Build Coastguard Worker
974*9880d681SAndroid Build Coastguard Worker /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
975*9880d681SAndroid Build Coastguard Worker /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
976*9880d681SAndroid Build Coastguard Worker /// need to materialize IV increments elsewhere to handle difficult situations.
expandIVInc(PHINode * PN,Value * StepV,const Loop * L,Type * ExpandTy,Type * IntTy,bool useSubtract)977*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
978*9880d681SAndroid Build Coastguard Worker Type *ExpandTy, Type *IntTy,
979*9880d681SAndroid Build Coastguard Worker bool useSubtract) {
980*9880d681SAndroid Build Coastguard Worker Value *IncV;
981*9880d681SAndroid Build Coastguard Worker // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
982*9880d681SAndroid Build Coastguard Worker if (ExpandTy->isPointerTy()) {
983*9880d681SAndroid Build Coastguard Worker PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
984*9880d681SAndroid Build Coastguard Worker // If the step isn't constant, don't use an implicitly scaled GEP, because
985*9880d681SAndroid Build Coastguard Worker // that would require a multiply inside the loop.
986*9880d681SAndroid Build Coastguard Worker if (!isa<ConstantInt>(StepV))
987*9880d681SAndroid Build Coastguard Worker GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
988*9880d681SAndroid Build Coastguard Worker GEPPtrTy->getAddressSpace());
989*9880d681SAndroid Build Coastguard Worker const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
990*9880d681SAndroid Build Coastguard Worker IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
991*9880d681SAndroid Build Coastguard Worker if (IncV->getType() != PN->getType()) {
992*9880d681SAndroid Build Coastguard Worker IncV = Builder.CreateBitCast(IncV, PN->getType());
993*9880d681SAndroid Build Coastguard Worker rememberInstruction(IncV);
994*9880d681SAndroid Build Coastguard Worker }
995*9880d681SAndroid Build Coastguard Worker } else {
996*9880d681SAndroid Build Coastguard Worker IncV = useSubtract ?
997*9880d681SAndroid Build Coastguard Worker Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
998*9880d681SAndroid Build Coastguard Worker Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
999*9880d681SAndroid Build Coastguard Worker rememberInstruction(IncV);
1000*9880d681SAndroid Build Coastguard Worker }
1001*9880d681SAndroid Build Coastguard Worker return IncV;
1002*9880d681SAndroid Build Coastguard Worker }
1003*9880d681SAndroid Build Coastguard Worker
1004*9880d681SAndroid Build Coastguard Worker /// \brief Hoist the addrec instruction chain rooted in the loop phi above the
1005*9880d681SAndroid Build Coastguard Worker /// position. This routine assumes that this is possible (has been checked).
hoistBeforePos(DominatorTree * DT,Instruction * InstToHoist,Instruction * Pos,PHINode * LoopPhi)1006*9880d681SAndroid Build Coastguard Worker void SCEVExpander::hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
1007*9880d681SAndroid Build Coastguard Worker Instruction *Pos, PHINode *LoopPhi) {
1008*9880d681SAndroid Build Coastguard Worker do {
1009*9880d681SAndroid Build Coastguard Worker if (DT->dominates(InstToHoist, Pos))
1010*9880d681SAndroid Build Coastguard Worker break;
1011*9880d681SAndroid Build Coastguard Worker // Make sure the increment is where we want it. But don't move it
1012*9880d681SAndroid Build Coastguard Worker // down past a potential existing post-inc user.
1013*9880d681SAndroid Build Coastguard Worker fixupInsertPoints(InstToHoist);
1014*9880d681SAndroid Build Coastguard Worker InstToHoist->moveBefore(Pos);
1015*9880d681SAndroid Build Coastguard Worker Pos = InstToHoist;
1016*9880d681SAndroid Build Coastguard Worker InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
1017*9880d681SAndroid Build Coastguard Worker } while (InstToHoist != LoopPhi);
1018*9880d681SAndroid Build Coastguard Worker }
1019*9880d681SAndroid Build Coastguard Worker
1020*9880d681SAndroid Build Coastguard Worker /// \brief Check whether we can cheaply express the requested SCEV in terms of
1021*9880d681SAndroid Build Coastguard Worker /// the available PHI SCEV by truncation and/or inversion of the step.
canBeCheaplyTransformed(ScalarEvolution & SE,const SCEVAddRecExpr * Phi,const SCEVAddRecExpr * Requested,bool & InvertStep)1022*9880d681SAndroid Build Coastguard Worker static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1023*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *Phi,
1024*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *Requested,
1025*9880d681SAndroid Build Coastguard Worker bool &InvertStep) {
1026*9880d681SAndroid Build Coastguard Worker Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1027*9880d681SAndroid Build Coastguard Worker Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1028*9880d681SAndroid Build Coastguard Worker
1029*9880d681SAndroid Build Coastguard Worker if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1030*9880d681SAndroid Build Coastguard Worker return false;
1031*9880d681SAndroid Build Coastguard Worker
1032*9880d681SAndroid Build Coastguard Worker // Try truncate it if necessary.
1033*9880d681SAndroid Build Coastguard Worker Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1034*9880d681SAndroid Build Coastguard Worker if (!Phi)
1035*9880d681SAndroid Build Coastguard Worker return false;
1036*9880d681SAndroid Build Coastguard Worker
1037*9880d681SAndroid Build Coastguard Worker // Check whether truncation will help.
1038*9880d681SAndroid Build Coastguard Worker if (Phi == Requested) {
1039*9880d681SAndroid Build Coastguard Worker InvertStep = false;
1040*9880d681SAndroid Build Coastguard Worker return true;
1041*9880d681SAndroid Build Coastguard Worker }
1042*9880d681SAndroid Build Coastguard Worker
1043*9880d681SAndroid Build Coastguard Worker // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1044*9880d681SAndroid Build Coastguard Worker if (SE.getAddExpr(Requested->getStart(),
1045*9880d681SAndroid Build Coastguard Worker SE.getNegativeSCEV(Requested)) == Phi) {
1046*9880d681SAndroid Build Coastguard Worker InvertStep = true;
1047*9880d681SAndroid Build Coastguard Worker return true;
1048*9880d681SAndroid Build Coastguard Worker }
1049*9880d681SAndroid Build Coastguard Worker
1050*9880d681SAndroid Build Coastguard Worker return false;
1051*9880d681SAndroid Build Coastguard Worker }
1052*9880d681SAndroid Build Coastguard Worker
IsIncrementNSW(ScalarEvolution & SE,const SCEVAddRecExpr * AR)1053*9880d681SAndroid Build Coastguard Worker static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1054*9880d681SAndroid Build Coastguard Worker if (!isa<IntegerType>(AR->getType()))
1055*9880d681SAndroid Build Coastguard Worker return false;
1056*9880d681SAndroid Build Coastguard Worker
1057*9880d681SAndroid Build Coastguard Worker unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1058*9880d681SAndroid Build Coastguard Worker Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1059*9880d681SAndroid Build Coastguard Worker const SCEV *Step = AR->getStepRecurrence(SE);
1060*9880d681SAndroid Build Coastguard Worker const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1061*9880d681SAndroid Build Coastguard Worker SE.getSignExtendExpr(AR, WideTy));
1062*9880d681SAndroid Build Coastguard Worker const SCEV *ExtendAfterOp =
1063*9880d681SAndroid Build Coastguard Worker SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1064*9880d681SAndroid Build Coastguard Worker return ExtendAfterOp == OpAfterExtend;
1065*9880d681SAndroid Build Coastguard Worker }
1066*9880d681SAndroid Build Coastguard Worker
IsIncrementNUW(ScalarEvolution & SE,const SCEVAddRecExpr * AR)1067*9880d681SAndroid Build Coastguard Worker static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1068*9880d681SAndroid Build Coastguard Worker if (!isa<IntegerType>(AR->getType()))
1069*9880d681SAndroid Build Coastguard Worker return false;
1070*9880d681SAndroid Build Coastguard Worker
1071*9880d681SAndroid Build Coastguard Worker unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1072*9880d681SAndroid Build Coastguard Worker Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1073*9880d681SAndroid Build Coastguard Worker const SCEV *Step = AR->getStepRecurrence(SE);
1074*9880d681SAndroid Build Coastguard Worker const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1075*9880d681SAndroid Build Coastguard Worker SE.getZeroExtendExpr(AR, WideTy));
1076*9880d681SAndroid Build Coastguard Worker const SCEV *ExtendAfterOp =
1077*9880d681SAndroid Build Coastguard Worker SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1078*9880d681SAndroid Build Coastguard Worker return ExtendAfterOp == OpAfterExtend;
1079*9880d681SAndroid Build Coastguard Worker }
1080*9880d681SAndroid Build Coastguard Worker
1081*9880d681SAndroid Build Coastguard Worker /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1082*9880d681SAndroid Build Coastguard Worker /// the base addrec, which is the addrec without any non-loop-dominating
1083*9880d681SAndroid Build Coastguard Worker /// values, and return the PHI.
1084*9880d681SAndroid Build Coastguard Worker PHINode *
getAddRecExprPHILiterally(const SCEVAddRecExpr * Normalized,const Loop * L,Type * ExpandTy,Type * IntTy,Type * & TruncTy,bool & InvertStep)1085*9880d681SAndroid Build Coastguard Worker SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1086*9880d681SAndroid Build Coastguard Worker const Loop *L,
1087*9880d681SAndroid Build Coastguard Worker Type *ExpandTy,
1088*9880d681SAndroid Build Coastguard Worker Type *IntTy,
1089*9880d681SAndroid Build Coastguard Worker Type *&TruncTy,
1090*9880d681SAndroid Build Coastguard Worker bool &InvertStep) {
1091*9880d681SAndroid Build Coastguard Worker assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1092*9880d681SAndroid Build Coastguard Worker
1093*9880d681SAndroid Build Coastguard Worker // Reuse a previously-inserted PHI, if present.
1094*9880d681SAndroid Build Coastguard Worker BasicBlock *LatchBlock = L->getLoopLatch();
1095*9880d681SAndroid Build Coastguard Worker if (LatchBlock) {
1096*9880d681SAndroid Build Coastguard Worker PHINode *AddRecPhiMatch = nullptr;
1097*9880d681SAndroid Build Coastguard Worker Instruction *IncV = nullptr;
1098*9880d681SAndroid Build Coastguard Worker TruncTy = nullptr;
1099*9880d681SAndroid Build Coastguard Worker InvertStep = false;
1100*9880d681SAndroid Build Coastguard Worker
1101*9880d681SAndroid Build Coastguard Worker // Only try partially matching scevs that need truncation and/or
1102*9880d681SAndroid Build Coastguard Worker // step-inversion if we know this loop is outside the current loop.
1103*9880d681SAndroid Build Coastguard Worker bool TryNonMatchingSCEV =
1104*9880d681SAndroid Build Coastguard Worker IVIncInsertLoop &&
1105*9880d681SAndroid Build Coastguard Worker SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1106*9880d681SAndroid Build Coastguard Worker
1107*9880d681SAndroid Build Coastguard Worker for (auto &I : *L->getHeader()) {
1108*9880d681SAndroid Build Coastguard Worker auto *PN = dyn_cast<PHINode>(&I);
1109*9880d681SAndroid Build Coastguard Worker if (!PN || !SE.isSCEVable(PN->getType()))
1110*9880d681SAndroid Build Coastguard Worker continue;
1111*9880d681SAndroid Build Coastguard Worker
1112*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
1113*9880d681SAndroid Build Coastguard Worker if (!PhiSCEV)
1114*9880d681SAndroid Build Coastguard Worker continue;
1115*9880d681SAndroid Build Coastguard Worker
1116*9880d681SAndroid Build Coastguard Worker bool IsMatchingSCEV = PhiSCEV == Normalized;
1117*9880d681SAndroid Build Coastguard Worker // We only handle truncation and inversion of phi recurrences for the
1118*9880d681SAndroid Build Coastguard Worker // expanded expression if the expanded expression's loop dominates the
1119*9880d681SAndroid Build Coastguard Worker // loop we insert to. Check now, so we can bail out early.
1120*9880d681SAndroid Build Coastguard Worker if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1121*9880d681SAndroid Build Coastguard Worker continue;
1122*9880d681SAndroid Build Coastguard Worker
1123*9880d681SAndroid Build Coastguard Worker Instruction *TempIncV =
1124*9880d681SAndroid Build Coastguard Worker cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1125*9880d681SAndroid Build Coastguard Worker
1126*9880d681SAndroid Build Coastguard Worker // Check whether we can reuse this PHI node.
1127*9880d681SAndroid Build Coastguard Worker if (LSRMode) {
1128*9880d681SAndroid Build Coastguard Worker if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
1129*9880d681SAndroid Build Coastguard Worker continue;
1130*9880d681SAndroid Build Coastguard Worker if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1131*9880d681SAndroid Build Coastguard Worker continue;
1132*9880d681SAndroid Build Coastguard Worker } else {
1133*9880d681SAndroid Build Coastguard Worker if (!isNormalAddRecExprPHI(PN, TempIncV, L))
1134*9880d681SAndroid Build Coastguard Worker continue;
1135*9880d681SAndroid Build Coastguard Worker }
1136*9880d681SAndroid Build Coastguard Worker
1137*9880d681SAndroid Build Coastguard Worker // Stop if we have found an exact match SCEV.
1138*9880d681SAndroid Build Coastguard Worker if (IsMatchingSCEV) {
1139*9880d681SAndroid Build Coastguard Worker IncV = TempIncV;
1140*9880d681SAndroid Build Coastguard Worker TruncTy = nullptr;
1141*9880d681SAndroid Build Coastguard Worker InvertStep = false;
1142*9880d681SAndroid Build Coastguard Worker AddRecPhiMatch = PN;
1143*9880d681SAndroid Build Coastguard Worker break;
1144*9880d681SAndroid Build Coastguard Worker }
1145*9880d681SAndroid Build Coastguard Worker
1146*9880d681SAndroid Build Coastguard Worker // Try whether the phi can be translated into the requested form
1147*9880d681SAndroid Build Coastguard Worker // (truncated and/or offset by a constant).
1148*9880d681SAndroid Build Coastguard Worker if ((!TruncTy || InvertStep) &&
1149*9880d681SAndroid Build Coastguard Worker canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1150*9880d681SAndroid Build Coastguard Worker // Record the phi node. But don't stop we might find an exact match
1151*9880d681SAndroid Build Coastguard Worker // later.
1152*9880d681SAndroid Build Coastguard Worker AddRecPhiMatch = PN;
1153*9880d681SAndroid Build Coastguard Worker IncV = TempIncV;
1154*9880d681SAndroid Build Coastguard Worker TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1155*9880d681SAndroid Build Coastguard Worker }
1156*9880d681SAndroid Build Coastguard Worker }
1157*9880d681SAndroid Build Coastguard Worker
1158*9880d681SAndroid Build Coastguard Worker if (AddRecPhiMatch) {
1159*9880d681SAndroid Build Coastguard Worker // Potentially, move the increment. We have made sure in
1160*9880d681SAndroid Build Coastguard Worker // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1161*9880d681SAndroid Build Coastguard Worker if (L == IVIncInsertLoop)
1162*9880d681SAndroid Build Coastguard Worker hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
1163*9880d681SAndroid Build Coastguard Worker
1164*9880d681SAndroid Build Coastguard Worker // Ok, the add recurrence looks usable.
1165*9880d681SAndroid Build Coastguard Worker // Remember this PHI, even in post-inc mode.
1166*9880d681SAndroid Build Coastguard Worker InsertedValues.insert(AddRecPhiMatch);
1167*9880d681SAndroid Build Coastguard Worker // Remember the increment.
1168*9880d681SAndroid Build Coastguard Worker rememberInstruction(IncV);
1169*9880d681SAndroid Build Coastguard Worker return AddRecPhiMatch;
1170*9880d681SAndroid Build Coastguard Worker }
1171*9880d681SAndroid Build Coastguard Worker }
1172*9880d681SAndroid Build Coastguard Worker
1173*9880d681SAndroid Build Coastguard Worker // Save the original insertion point so we can restore it when we're done.
1174*9880d681SAndroid Build Coastguard Worker SCEVInsertPointGuard Guard(Builder, this);
1175*9880d681SAndroid Build Coastguard Worker
1176*9880d681SAndroid Build Coastguard Worker // Another AddRec may need to be recursively expanded below. For example, if
1177*9880d681SAndroid Build Coastguard Worker // this AddRec is quadratic, the StepV may itself be an AddRec in this
1178*9880d681SAndroid Build Coastguard Worker // loop. Remove this loop from the PostIncLoops set before expanding such
1179*9880d681SAndroid Build Coastguard Worker // AddRecs. Otherwise, we cannot find a valid position for the step
1180*9880d681SAndroid Build Coastguard Worker // (i.e. StepV can never dominate its loop header). Ideally, we could do
1181*9880d681SAndroid Build Coastguard Worker // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1182*9880d681SAndroid Build Coastguard Worker // so it's not worth implementing SmallPtrSet::swap.
1183*9880d681SAndroid Build Coastguard Worker PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1184*9880d681SAndroid Build Coastguard Worker PostIncLoops.clear();
1185*9880d681SAndroid Build Coastguard Worker
1186*9880d681SAndroid Build Coastguard Worker // Expand code for the start value.
1187*9880d681SAndroid Build Coastguard Worker Value *StartV =
1188*9880d681SAndroid Build Coastguard Worker expandCodeFor(Normalized->getStart(), ExpandTy, &L->getHeader()->front());
1189*9880d681SAndroid Build Coastguard Worker
1190*9880d681SAndroid Build Coastguard Worker // StartV must be hoisted into L's preheader to dominate the new phi.
1191*9880d681SAndroid Build Coastguard Worker assert(!isa<Instruction>(StartV) ||
1192*9880d681SAndroid Build Coastguard Worker SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1193*9880d681SAndroid Build Coastguard Worker L->getHeader()));
1194*9880d681SAndroid Build Coastguard Worker
1195*9880d681SAndroid Build Coastguard Worker // Expand code for the step value. Do this before creating the PHI so that PHI
1196*9880d681SAndroid Build Coastguard Worker // reuse code doesn't see an incomplete PHI.
1197*9880d681SAndroid Build Coastguard Worker const SCEV *Step = Normalized->getStepRecurrence(SE);
1198*9880d681SAndroid Build Coastguard Worker // If the stride is negative, insert a sub instead of an add for the increment
1199*9880d681SAndroid Build Coastguard Worker // (unless it's a constant, because subtracts of constants are canonicalized
1200*9880d681SAndroid Build Coastguard Worker // to adds).
1201*9880d681SAndroid Build Coastguard Worker bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1202*9880d681SAndroid Build Coastguard Worker if (useSubtract)
1203*9880d681SAndroid Build Coastguard Worker Step = SE.getNegativeSCEV(Step);
1204*9880d681SAndroid Build Coastguard Worker // Expand the step somewhere that dominates the loop header.
1205*9880d681SAndroid Build Coastguard Worker Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1206*9880d681SAndroid Build Coastguard Worker
1207*9880d681SAndroid Build Coastguard Worker // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1208*9880d681SAndroid Build Coastguard Worker // we actually do emit an addition. It does not apply if we emit a
1209*9880d681SAndroid Build Coastguard Worker // subtraction.
1210*9880d681SAndroid Build Coastguard Worker bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1211*9880d681SAndroid Build Coastguard Worker bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1212*9880d681SAndroid Build Coastguard Worker
1213*9880d681SAndroid Build Coastguard Worker // Create the PHI.
1214*9880d681SAndroid Build Coastguard Worker BasicBlock *Header = L->getHeader();
1215*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(Header, Header->begin());
1216*9880d681SAndroid Build Coastguard Worker pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1217*9880d681SAndroid Build Coastguard Worker PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1218*9880d681SAndroid Build Coastguard Worker Twine(IVName) + ".iv");
1219*9880d681SAndroid Build Coastguard Worker rememberInstruction(PN);
1220*9880d681SAndroid Build Coastguard Worker
1221*9880d681SAndroid Build Coastguard Worker // Create the step instructions and populate the PHI.
1222*9880d681SAndroid Build Coastguard Worker for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1223*9880d681SAndroid Build Coastguard Worker BasicBlock *Pred = *HPI;
1224*9880d681SAndroid Build Coastguard Worker
1225*9880d681SAndroid Build Coastguard Worker // Add a start value.
1226*9880d681SAndroid Build Coastguard Worker if (!L->contains(Pred)) {
1227*9880d681SAndroid Build Coastguard Worker PN->addIncoming(StartV, Pred);
1228*9880d681SAndroid Build Coastguard Worker continue;
1229*9880d681SAndroid Build Coastguard Worker }
1230*9880d681SAndroid Build Coastguard Worker
1231*9880d681SAndroid Build Coastguard Worker // Create a step value and add it to the PHI.
1232*9880d681SAndroid Build Coastguard Worker // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1233*9880d681SAndroid Build Coastguard Worker // instructions at IVIncInsertPos.
1234*9880d681SAndroid Build Coastguard Worker Instruction *InsertPos = L == IVIncInsertLoop ?
1235*9880d681SAndroid Build Coastguard Worker IVIncInsertPos : Pred->getTerminator();
1236*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(InsertPos);
1237*9880d681SAndroid Build Coastguard Worker Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1238*9880d681SAndroid Build Coastguard Worker
1239*9880d681SAndroid Build Coastguard Worker if (isa<OverflowingBinaryOperator>(IncV)) {
1240*9880d681SAndroid Build Coastguard Worker if (IncrementIsNUW)
1241*9880d681SAndroid Build Coastguard Worker cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1242*9880d681SAndroid Build Coastguard Worker if (IncrementIsNSW)
1243*9880d681SAndroid Build Coastguard Worker cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1244*9880d681SAndroid Build Coastguard Worker }
1245*9880d681SAndroid Build Coastguard Worker PN->addIncoming(IncV, Pred);
1246*9880d681SAndroid Build Coastguard Worker }
1247*9880d681SAndroid Build Coastguard Worker
1248*9880d681SAndroid Build Coastguard Worker // After expanding subexpressions, restore the PostIncLoops set so the caller
1249*9880d681SAndroid Build Coastguard Worker // can ensure that IVIncrement dominates the current uses.
1250*9880d681SAndroid Build Coastguard Worker PostIncLoops = SavedPostIncLoops;
1251*9880d681SAndroid Build Coastguard Worker
1252*9880d681SAndroid Build Coastguard Worker // Remember this PHI, even in post-inc mode.
1253*9880d681SAndroid Build Coastguard Worker InsertedValues.insert(PN);
1254*9880d681SAndroid Build Coastguard Worker
1255*9880d681SAndroid Build Coastguard Worker return PN;
1256*9880d681SAndroid Build Coastguard Worker }
1257*9880d681SAndroid Build Coastguard Worker
expandAddRecExprLiterally(const SCEVAddRecExpr * S)1258*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1259*9880d681SAndroid Build Coastguard Worker Type *STy = S->getType();
1260*9880d681SAndroid Build Coastguard Worker Type *IntTy = SE.getEffectiveSCEVType(STy);
1261*9880d681SAndroid Build Coastguard Worker const Loop *L = S->getLoop();
1262*9880d681SAndroid Build Coastguard Worker
1263*9880d681SAndroid Build Coastguard Worker // Determine a normalized form of this expression, which is the expression
1264*9880d681SAndroid Build Coastguard Worker // before any post-inc adjustment is made.
1265*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *Normalized = S;
1266*9880d681SAndroid Build Coastguard Worker if (PostIncLoops.count(L)) {
1267*9880d681SAndroid Build Coastguard Worker PostIncLoopSet Loops;
1268*9880d681SAndroid Build Coastguard Worker Loops.insert(L);
1269*9880d681SAndroid Build Coastguard Worker Normalized = cast<SCEVAddRecExpr>(TransformForPostIncUse(
1270*9880d681SAndroid Build Coastguard Worker Normalize, S, nullptr, nullptr, Loops, SE, SE.DT));
1271*9880d681SAndroid Build Coastguard Worker }
1272*9880d681SAndroid Build Coastguard Worker
1273*9880d681SAndroid Build Coastguard Worker // Strip off any non-loop-dominating component from the addrec start.
1274*9880d681SAndroid Build Coastguard Worker const SCEV *Start = Normalized->getStart();
1275*9880d681SAndroid Build Coastguard Worker const SCEV *PostLoopOffset = nullptr;
1276*9880d681SAndroid Build Coastguard Worker if (!SE.properlyDominates(Start, L->getHeader())) {
1277*9880d681SAndroid Build Coastguard Worker PostLoopOffset = Start;
1278*9880d681SAndroid Build Coastguard Worker Start = SE.getConstant(Normalized->getType(), 0);
1279*9880d681SAndroid Build Coastguard Worker Normalized = cast<SCEVAddRecExpr>(
1280*9880d681SAndroid Build Coastguard Worker SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1281*9880d681SAndroid Build Coastguard Worker Normalized->getLoop(),
1282*9880d681SAndroid Build Coastguard Worker Normalized->getNoWrapFlags(SCEV::FlagNW)));
1283*9880d681SAndroid Build Coastguard Worker }
1284*9880d681SAndroid Build Coastguard Worker
1285*9880d681SAndroid Build Coastguard Worker // Strip off any non-loop-dominating component from the addrec step.
1286*9880d681SAndroid Build Coastguard Worker const SCEV *Step = Normalized->getStepRecurrence(SE);
1287*9880d681SAndroid Build Coastguard Worker const SCEV *PostLoopScale = nullptr;
1288*9880d681SAndroid Build Coastguard Worker if (!SE.dominates(Step, L->getHeader())) {
1289*9880d681SAndroid Build Coastguard Worker PostLoopScale = Step;
1290*9880d681SAndroid Build Coastguard Worker Step = SE.getConstant(Normalized->getType(), 1);
1291*9880d681SAndroid Build Coastguard Worker if (!Start->isZero()) {
1292*9880d681SAndroid Build Coastguard Worker // The normalization below assumes that Start is constant zero, so if
1293*9880d681SAndroid Build Coastguard Worker // it isn't re-associate Start to PostLoopOffset.
1294*9880d681SAndroid Build Coastguard Worker assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?");
1295*9880d681SAndroid Build Coastguard Worker PostLoopOffset = Start;
1296*9880d681SAndroid Build Coastguard Worker Start = SE.getConstant(Normalized->getType(), 0);
1297*9880d681SAndroid Build Coastguard Worker }
1298*9880d681SAndroid Build Coastguard Worker Normalized =
1299*9880d681SAndroid Build Coastguard Worker cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1300*9880d681SAndroid Build Coastguard Worker Start, Step, Normalized->getLoop(),
1301*9880d681SAndroid Build Coastguard Worker Normalized->getNoWrapFlags(SCEV::FlagNW)));
1302*9880d681SAndroid Build Coastguard Worker }
1303*9880d681SAndroid Build Coastguard Worker
1304*9880d681SAndroid Build Coastguard Worker // Expand the core addrec. If we need post-loop scaling, force it to
1305*9880d681SAndroid Build Coastguard Worker // expand to an integer type to avoid the need for additional casting.
1306*9880d681SAndroid Build Coastguard Worker Type *ExpandTy = PostLoopScale ? IntTy : STy;
1307*9880d681SAndroid Build Coastguard Worker // In some cases, we decide to reuse an existing phi node but need to truncate
1308*9880d681SAndroid Build Coastguard Worker // it and/or invert the step.
1309*9880d681SAndroid Build Coastguard Worker Type *TruncTy = nullptr;
1310*9880d681SAndroid Build Coastguard Worker bool InvertStep = false;
1311*9880d681SAndroid Build Coastguard Worker PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
1312*9880d681SAndroid Build Coastguard Worker TruncTy, InvertStep);
1313*9880d681SAndroid Build Coastguard Worker
1314*9880d681SAndroid Build Coastguard Worker // Accommodate post-inc mode, if necessary.
1315*9880d681SAndroid Build Coastguard Worker Value *Result;
1316*9880d681SAndroid Build Coastguard Worker if (!PostIncLoops.count(L))
1317*9880d681SAndroid Build Coastguard Worker Result = PN;
1318*9880d681SAndroid Build Coastguard Worker else {
1319*9880d681SAndroid Build Coastguard Worker // In PostInc mode, use the post-incremented value.
1320*9880d681SAndroid Build Coastguard Worker BasicBlock *LatchBlock = L->getLoopLatch();
1321*9880d681SAndroid Build Coastguard Worker assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1322*9880d681SAndroid Build Coastguard Worker Result = PN->getIncomingValueForBlock(LatchBlock);
1323*9880d681SAndroid Build Coastguard Worker
1324*9880d681SAndroid Build Coastguard Worker // For an expansion to use the postinc form, the client must call
1325*9880d681SAndroid Build Coastguard Worker // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1326*9880d681SAndroid Build Coastguard Worker // or dominated by IVIncInsertPos.
1327*9880d681SAndroid Build Coastguard Worker if (isa<Instruction>(Result) &&
1328*9880d681SAndroid Build Coastguard Worker !SE.DT.dominates(cast<Instruction>(Result),
1329*9880d681SAndroid Build Coastguard Worker &*Builder.GetInsertPoint())) {
1330*9880d681SAndroid Build Coastguard Worker // The induction variable's postinc expansion does not dominate this use.
1331*9880d681SAndroid Build Coastguard Worker // IVUsers tries to prevent this case, so it is rare. However, it can
1332*9880d681SAndroid Build Coastguard Worker // happen when an IVUser outside the loop is not dominated by the latch
1333*9880d681SAndroid Build Coastguard Worker // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1334*9880d681SAndroid Build Coastguard Worker // all cases. Consider a phi outide whose operand is replaced during
1335*9880d681SAndroid Build Coastguard Worker // expansion with the value of the postinc user. Without fundamentally
1336*9880d681SAndroid Build Coastguard Worker // changing the way postinc users are tracked, the only remedy is
1337*9880d681SAndroid Build Coastguard Worker // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1338*9880d681SAndroid Build Coastguard Worker // but hopefully expandCodeFor handles that.
1339*9880d681SAndroid Build Coastguard Worker bool useSubtract =
1340*9880d681SAndroid Build Coastguard Worker !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1341*9880d681SAndroid Build Coastguard Worker if (useSubtract)
1342*9880d681SAndroid Build Coastguard Worker Step = SE.getNegativeSCEV(Step);
1343*9880d681SAndroid Build Coastguard Worker Value *StepV;
1344*9880d681SAndroid Build Coastguard Worker {
1345*9880d681SAndroid Build Coastguard Worker // Expand the step somewhere that dominates the loop header.
1346*9880d681SAndroid Build Coastguard Worker SCEVInsertPointGuard Guard(Builder, this);
1347*9880d681SAndroid Build Coastguard Worker StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1348*9880d681SAndroid Build Coastguard Worker }
1349*9880d681SAndroid Build Coastguard Worker Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1350*9880d681SAndroid Build Coastguard Worker }
1351*9880d681SAndroid Build Coastguard Worker }
1352*9880d681SAndroid Build Coastguard Worker
1353*9880d681SAndroid Build Coastguard Worker // We have decided to reuse an induction variable of a dominating loop. Apply
1354*9880d681SAndroid Build Coastguard Worker // truncation and/or invertion of the step.
1355*9880d681SAndroid Build Coastguard Worker if (TruncTy) {
1356*9880d681SAndroid Build Coastguard Worker Type *ResTy = Result->getType();
1357*9880d681SAndroid Build Coastguard Worker // Normalize the result type.
1358*9880d681SAndroid Build Coastguard Worker if (ResTy != SE.getEffectiveSCEVType(ResTy))
1359*9880d681SAndroid Build Coastguard Worker Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1360*9880d681SAndroid Build Coastguard Worker // Truncate the result.
1361*9880d681SAndroid Build Coastguard Worker if (TruncTy != Result->getType()) {
1362*9880d681SAndroid Build Coastguard Worker Result = Builder.CreateTrunc(Result, TruncTy);
1363*9880d681SAndroid Build Coastguard Worker rememberInstruction(Result);
1364*9880d681SAndroid Build Coastguard Worker }
1365*9880d681SAndroid Build Coastguard Worker // Invert the result.
1366*9880d681SAndroid Build Coastguard Worker if (InvertStep) {
1367*9880d681SAndroid Build Coastguard Worker Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1368*9880d681SAndroid Build Coastguard Worker Result);
1369*9880d681SAndroid Build Coastguard Worker rememberInstruction(Result);
1370*9880d681SAndroid Build Coastguard Worker }
1371*9880d681SAndroid Build Coastguard Worker }
1372*9880d681SAndroid Build Coastguard Worker
1373*9880d681SAndroid Build Coastguard Worker // Re-apply any non-loop-dominating scale.
1374*9880d681SAndroid Build Coastguard Worker if (PostLoopScale) {
1375*9880d681SAndroid Build Coastguard Worker assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
1376*9880d681SAndroid Build Coastguard Worker Result = InsertNoopCastOfTo(Result, IntTy);
1377*9880d681SAndroid Build Coastguard Worker Result = Builder.CreateMul(Result,
1378*9880d681SAndroid Build Coastguard Worker expandCodeFor(PostLoopScale, IntTy));
1379*9880d681SAndroid Build Coastguard Worker rememberInstruction(Result);
1380*9880d681SAndroid Build Coastguard Worker }
1381*9880d681SAndroid Build Coastguard Worker
1382*9880d681SAndroid Build Coastguard Worker // Re-apply any non-loop-dominating offset.
1383*9880d681SAndroid Build Coastguard Worker if (PostLoopOffset) {
1384*9880d681SAndroid Build Coastguard Worker if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1385*9880d681SAndroid Build Coastguard Worker const SCEV *const OffsetArray[1] = { PostLoopOffset };
1386*9880d681SAndroid Build Coastguard Worker Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1387*9880d681SAndroid Build Coastguard Worker } else {
1388*9880d681SAndroid Build Coastguard Worker Result = InsertNoopCastOfTo(Result, IntTy);
1389*9880d681SAndroid Build Coastguard Worker Result = Builder.CreateAdd(Result,
1390*9880d681SAndroid Build Coastguard Worker expandCodeFor(PostLoopOffset, IntTy));
1391*9880d681SAndroid Build Coastguard Worker rememberInstruction(Result);
1392*9880d681SAndroid Build Coastguard Worker }
1393*9880d681SAndroid Build Coastguard Worker }
1394*9880d681SAndroid Build Coastguard Worker
1395*9880d681SAndroid Build Coastguard Worker return Result;
1396*9880d681SAndroid Build Coastguard Worker }
1397*9880d681SAndroid Build Coastguard Worker
visitAddRecExpr(const SCEVAddRecExpr * S)1398*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1399*9880d681SAndroid Build Coastguard Worker if (!CanonicalMode) return expandAddRecExprLiterally(S);
1400*9880d681SAndroid Build Coastguard Worker
1401*9880d681SAndroid Build Coastguard Worker Type *Ty = SE.getEffectiveSCEVType(S->getType());
1402*9880d681SAndroid Build Coastguard Worker const Loop *L = S->getLoop();
1403*9880d681SAndroid Build Coastguard Worker
1404*9880d681SAndroid Build Coastguard Worker // First check for an existing canonical IV in a suitable type.
1405*9880d681SAndroid Build Coastguard Worker PHINode *CanonicalIV = nullptr;
1406*9880d681SAndroid Build Coastguard Worker if (PHINode *PN = L->getCanonicalInductionVariable())
1407*9880d681SAndroid Build Coastguard Worker if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1408*9880d681SAndroid Build Coastguard Worker CanonicalIV = PN;
1409*9880d681SAndroid Build Coastguard Worker
1410*9880d681SAndroid Build Coastguard Worker // Rewrite an AddRec in terms of the canonical induction variable, if
1411*9880d681SAndroid Build Coastguard Worker // its type is more narrow.
1412*9880d681SAndroid Build Coastguard Worker if (CanonicalIV &&
1413*9880d681SAndroid Build Coastguard Worker SE.getTypeSizeInBits(CanonicalIV->getType()) >
1414*9880d681SAndroid Build Coastguard Worker SE.getTypeSizeInBits(Ty)) {
1415*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1416*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1417*9880d681SAndroid Build Coastguard Worker NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1418*9880d681SAndroid Build Coastguard Worker Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1419*9880d681SAndroid Build Coastguard Worker S->getNoWrapFlags(SCEV::FlagNW)));
1420*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator NewInsertPt =
1421*9880d681SAndroid Build Coastguard Worker findInsertPointAfter(cast<Instruction>(V), Builder.GetInsertBlock());
1422*9880d681SAndroid Build Coastguard Worker V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
1423*9880d681SAndroid Build Coastguard Worker &*NewInsertPt);
1424*9880d681SAndroid Build Coastguard Worker return V;
1425*9880d681SAndroid Build Coastguard Worker }
1426*9880d681SAndroid Build Coastguard Worker
1427*9880d681SAndroid Build Coastguard Worker // {X,+,F} --> X + {0,+,F}
1428*9880d681SAndroid Build Coastguard Worker if (!S->getStart()->isZero()) {
1429*9880d681SAndroid Build Coastguard Worker SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1430*9880d681SAndroid Build Coastguard Worker NewOps[0] = SE.getConstant(Ty, 0);
1431*9880d681SAndroid Build Coastguard Worker const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1432*9880d681SAndroid Build Coastguard Worker S->getNoWrapFlags(SCEV::FlagNW));
1433*9880d681SAndroid Build Coastguard Worker
1434*9880d681SAndroid Build Coastguard Worker // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1435*9880d681SAndroid Build Coastguard Worker // comments on expandAddToGEP for details.
1436*9880d681SAndroid Build Coastguard Worker const SCEV *Base = S->getStart();
1437*9880d681SAndroid Build Coastguard Worker const SCEV *RestArray[1] = { Rest };
1438*9880d681SAndroid Build Coastguard Worker // Dig into the expression to find the pointer base for a GEP.
1439*9880d681SAndroid Build Coastguard Worker ExposePointerBase(Base, RestArray[0], SE);
1440*9880d681SAndroid Build Coastguard Worker // If we found a pointer, expand the AddRec with a GEP.
1441*9880d681SAndroid Build Coastguard Worker if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1442*9880d681SAndroid Build Coastguard Worker // Make sure the Base isn't something exotic, such as a multiplied
1443*9880d681SAndroid Build Coastguard Worker // or divided pointer value. In those cases, the result type isn't
1444*9880d681SAndroid Build Coastguard Worker // actually a pointer type.
1445*9880d681SAndroid Build Coastguard Worker if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1446*9880d681SAndroid Build Coastguard Worker Value *StartV = expand(Base);
1447*9880d681SAndroid Build Coastguard Worker assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1448*9880d681SAndroid Build Coastguard Worker return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1449*9880d681SAndroid Build Coastguard Worker }
1450*9880d681SAndroid Build Coastguard Worker }
1451*9880d681SAndroid Build Coastguard Worker
1452*9880d681SAndroid Build Coastguard Worker // Just do a normal add. Pre-expand the operands to suppress folding.
1453*9880d681SAndroid Build Coastguard Worker //
1454*9880d681SAndroid Build Coastguard Worker // The LHS and RHS values are factored out of the expand call to make the
1455*9880d681SAndroid Build Coastguard Worker // output independent of the argument evaluation order.
1456*9880d681SAndroid Build Coastguard Worker const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1457*9880d681SAndroid Build Coastguard Worker const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1458*9880d681SAndroid Build Coastguard Worker return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1459*9880d681SAndroid Build Coastguard Worker }
1460*9880d681SAndroid Build Coastguard Worker
1461*9880d681SAndroid Build Coastguard Worker // If we don't yet have a canonical IV, create one.
1462*9880d681SAndroid Build Coastguard Worker if (!CanonicalIV) {
1463*9880d681SAndroid Build Coastguard Worker // Create and insert the PHI node for the induction variable in the
1464*9880d681SAndroid Build Coastguard Worker // specified loop.
1465*9880d681SAndroid Build Coastguard Worker BasicBlock *Header = L->getHeader();
1466*9880d681SAndroid Build Coastguard Worker pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1467*9880d681SAndroid Build Coastguard Worker CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1468*9880d681SAndroid Build Coastguard Worker &Header->front());
1469*9880d681SAndroid Build Coastguard Worker rememberInstruction(CanonicalIV);
1470*9880d681SAndroid Build Coastguard Worker
1471*9880d681SAndroid Build Coastguard Worker SmallSet<BasicBlock *, 4> PredSeen;
1472*9880d681SAndroid Build Coastguard Worker Constant *One = ConstantInt::get(Ty, 1);
1473*9880d681SAndroid Build Coastguard Worker for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1474*9880d681SAndroid Build Coastguard Worker BasicBlock *HP = *HPI;
1475*9880d681SAndroid Build Coastguard Worker if (!PredSeen.insert(HP).second) {
1476*9880d681SAndroid Build Coastguard Worker // There must be an incoming value for each predecessor, even the
1477*9880d681SAndroid Build Coastguard Worker // duplicates!
1478*9880d681SAndroid Build Coastguard Worker CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1479*9880d681SAndroid Build Coastguard Worker continue;
1480*9880d681SAndroid Build Coastguard Worker }
1481*9880d681SAndroid Build Coastguard Worker
1482*9880d681SAndroid Build Coastguard Worker if (L->contains(HP)) {
1483*9880d681SAndroid Build Coastguard Worker // Insert a unit add instruction right before the terminator
1484*9880d681SAndroid Build Coastguard Worker // corresponding to the back-edge.
1485*9880d681SAndroid Build Coastguard Worker Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1486*9880d681SAndroid Build Coastguard Worker "indvar.next",
1487*9880d681SAndroid Build Coastguard Worker HP->getTerminator());
1488*9880d681SAndroid Build Coastguard Worker Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1489*9880d681SAndroid Build Coastguard Worker rememberInstruction(Add);
1490*9880d681SAndroid Build Coastguard Worker CanonicalIV->addIncoming(Add, HP);
1491*9880d681SAndroid Build Coastguard Worker } else {
1492*9880d681SAndroid Build Coastguard Worker CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1493*9880d681SAndroid Build Coastguard Worker }
1494*9880d681SAndroid Build Coastguard Worker }
1495*9880d681SAndroid Build Coastguard Worker }
1496*9880d681SAndroid Build Coastguard Worker
1497*9880d681SAndroid Build Coastguard Worker // {0,+,1} --> Insert a canonical induction variable into the loop!
1498*9880d681SAndroid Build Coastguard Worker if (S->isAffine() && S->getOperand(1)->isOne()) {
1499*9880d681SAndroid Build Coastguard Worker assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1500*9880d681SAndroid Build Coastguard Worker "IVs with types different from the canonical IV should "
1501*9880d681SAndroid Build Coastguard Worker "already have been handled!");
1502*9880d681SAndroid Build Coastguard Worker return CanonicalIV;
1503*9880d681SAndroid Build Coastguard Worker }
1504*9880d681SAndroid Build Coastguard Worker
1505*9880d681SAndroid Build Coastguard Worker // {0,+,F} --> {0,+,1} * F
1506*9880d681SAndroid Build Coastguard Worker
1507*9880d681SAndroid Build Coastguard Worker // If this is a simple linear addrec, emit it now as a special case.
1508*9880d681SAndroid Build Coastguard Worker if (S->isAffine()) // {0,+,F} --> i*F
1509*9880d681SAndroid Build Coastguard Worker return
1510*9880d681SAndroid Build Coastguard Worker expand(SE.getTruncateOrNoop(
1511*9880d681SAndroid Build Coastguard Worker SE.getMulExpr(SE.getUnknown(CanonicalIV),
1512*9880d681SAndroid Build Coastguard Worker SE.getNoopOrAnyExtend(S->getOperand(1),
1513*9880d681SAndroid Build Coastguard Worker CanonicalIV->getType())),
1514*9880d681SAndroid Build Coastguard Worker Ty));
1515*9880d681SAndroid Build Coastguard Worker
1516*9880d681SAndroid Build Coastguard Worker // If this is a chain of recurrences, turn it into a closed form, using the
1517*9880d681SAndroid Build Coastguard Worker // folders, then expandCodeFor the closed form. This allows the folders to
1518*9880d681SAndroid Build Coastguard Worker // simplify the expression without having to build a bunch of special code
1519*9880d681SAndroid Build Coastguard Worker // into this folder.
1520*9880d681SAndroid Build Coastguard Worker const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
1521*9880d681SAndroid Build Coastguard Worker
1522*9880d681SAndroid Build Coastguard Worker // Promote S up to the canonical IV type, if the cast is foldable.
1523*9880d681SAndroid Build Coastguard Worker const SCEV *NewS = S;
1524*9880d681SAndroid Build Coastguard Worker const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1525*9880d681SAndroid Build Coastguard Worker if (isa<SCEVAddRecExpr>(Ext))
1526*9880d681SAndroid Build Coastguard Worker NewS = Ext;
1527*9880d681SAndroid Build Coastguard Worker
1528*9880d681SAndroid Build Coastguard Worker const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1529*9880d681SAndroid Build Coastguard Worker //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
1530*9880d681SAndroid Build Coastguard Worker
1531*9880d681SAndroid Build Coastguard Worker // Truncate the result down to the original type, if needed.
1532*9880d681SAndroid Build Coastguard Worker const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1533*9880d681SAndroid Build Coastguard Worker return expand(T);
1534*9880d681SAndroid Build Coastguard Worker }
1535*9880d681SAndroid Build Coastguard Worker
visitTruncateExpr(const SCEVTruncateExpr * S)1536*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1537*9880d681SAndroid Build Coastguard Worker Type *Ty = SE.getEffectiveSCEVType(S->getType());
1538*9880d681SAndroid Build Coastguard Worker Value *V = expandCodeFor(S->getOperand(),
1539*9880d681SAndroid Build Coastguard Worker SE.getEffectiveSCEVType(S->getOperand()->getType()));
1540*9880d681SAndroid Build Coastguard Worker Value *I = Builder.CreateTrunc(V, Ty);
1541*9880d681SAndroid Build Coastguard Worker rememberInstruction(I);
1542*9880d681SAndroid Build Coastguard Worker return I;
1543*9880d681SAndroid Build Coastguard Worker }
1544*9880d681SAndroid Build Coastguard Worker
visitZeroExtendExpr(const SCEVZeroExtendExpr * S)1545*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1546*9880d681SAndroid Build Coastguard Worker Type *Ty = SE.getEffectiveSCEVType(S->getType());
1547*9880d681SAndroid Build Coastguard Worker Value *V = expandCodeFor(S->getOperand(),
1548*9880d681SAndroid Build Coastguard Worker SE.getEffectiveSCEVType(S->getOperand()->getType()));
1549*9880d681SAndroid Build Coastguard Worker Value *I = Builder.CreateZExt(V, Ty);
1550*9880d681SAndroid Build Coastguard Worker rememberInstruction(I);
1551*9880d681SAndroid Build Coastguard Worker return I;
1552*9880d681SAndroid Build Coastguard Worker }
1553*9880d681SAndroid Build Coastguard Worker
visitSignExtendExpr(const SCEVSignExtendExpr * S)1554*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1555*9880d681SAndroid Build Coastguard Worker Type *Ty = SE.getEffectiveSCEVType(S->getType());
1556*9880d681SAndroid Build Coastguard Worker Value *V = expandCodeFor(S->getOperand(),
1557*9880d681SAndroid Build Coastguard Worker SE.getEffectiveSCEVType(S->getOperand()->getType()));
1558*9880d681SAndroid Build Coastguard Worker Value *I = Builder.CreateSExt(V, Ty);
1559*9880d681SAndroid Build Coastguard Worker rememberInstruction(I);
1560*9880d681SAndroid Build Coastguard Worker return I;
1561*9880d681SAndroid Build Coastguard Worker }
1562*9880d681SAndroid Build Coastguard Worker
visitSMaxExpr(const SCEVSMaxExpr * S)1563*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1564*9880d681SAndroid Build Coastguard Worker Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1565*9880d681SAndroid Build Coastguard Worker Type *Ty = LHS->getType();
1566*9880d681SAndroid Build Coastguard Worker for (int i = S->getNumOperands()-2; i >= 0; --i) {
1567*9880d681SAndroid Build Coastguard Worker // In the case of mixed integer and pointer types, do the
1568*9880d681SAndroid Build Coastguard Worker // rest of the comparisons as integer.
1569*9880d681SAndroid Build Coastguard Worker if (S->getOperand(i)->getType() != Ty) {
1570*9880d681SAndroid Build Coastguard Worker Ty = SE.getEffectiveSCEVType(Ty);
1571*9880d681SAndroid Build Coastguard Worker LHS = InsertNoopCastOfTo(LHS, Ty);
1572*9880d681SAndroid Build Coastguard Worker }
1573*9880d681SAndroid Build Coastguard Worker Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1574*9880d681SAndroid Build Coastguard Worker Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1575*9880d681SAndroid Build Coastguard Worker rememberInstruction(ICmp);
1576*9880d681SAndroid Build Coastguard Worker Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1577*9880d681SAndroid Build Coastguard Worker rememberInstruction(Sel);
1578*9880d681SAndroid Build Coastguard Worker LHS = Sel;
1579*9880d681SAndroid Build Coastguard Worker }
1580*9880d681SAndroid Build Coastguard Worker // In the case of mixed integer and pointer types, cast the
1581*9880d681SAndroid Build Coastguard Worker // final result back to the pointer type.
1582*9880d681SAndroid Build Coastguard Worker if (LHS->getType() != S->getType())
1583*9880d681SAndroid Build Coastguard Worker LHS = InsertNoopCastOfTo(LHS, S->getType());
1584*9880d681SAndroid Build Coastguard Worker return LHS;
1585*9880d681SAndroid Build Coastguard Worker }
1586*9880d681SAndroid Build Coastguard Worker
visitUMaxExpr(const SCEVUMaxExpr * S)1587*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1588*9880d681SAndroid Build Coastguard Worker Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1589*9880d681SAndroid Build Coastguard Worker Type *Ty = LHS->getType();
1590*9880d681SAndroid Build Coastguard Worker for (int i = S->getNumOperands()-2; i >= 0; --i) {
1591*9880d681SAndroid Build Coastguard Worker // In the case of mixed integer and pointer types, do the
1592*9880d681SAndroid Build Coastguard Worker // rest of the comparisons as integer.
1593*9880d681SAndroid Build Coastguard Worker if (S->getOperand(i)->getType() != Ty) {
1594*9880d681SAndroid Build Coastguard Worker Ty = SE.getEffectiveSCEVType(Ty);
1595*9880d681SAndroid Build Coastguard Worker LHS = InsertNoopCastOfTo(LHS, Ty);
1596*9880d681SAndroid Build Coastguard Worker }
1597*9880d681SAndroid Build Coastguard Worker Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1598*9880d681SAndroid Build Coastguard Worker Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1599*9880d681SAndroid Build Coastguard Worker rememberInstruction(ICmp);
1600*9880d681SAndroid Build Coastguard Worker Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1601*9880d681SAndroid Build Coastguard Worker rememberInstruction(Sel);
1602*9880d681SAndroid Build Coastguard Worker LHS = Sel;
1603*9880d681SAndroid Build Coastguard Worker }
1604*9880d681SAndroid Build Coastguard Worker // In the case of mixed integer and pointer types, cast the
1605*9880d681SAndroid Build Coastguard Worker // final result back to the pointer type.
1606*9880d681SAndroid Build Coastguard Worker if (LHS->getType() != S->getType())
1607*9880d681SAndroid Build Coastguard Worker LHS = InsertNoopCastOfTo(LHS, S->getType());
1608*9880d681SAndroid Build Coastguard Worker return LHS;
1609*9880d681SAndroid Build Coastguard Worker }
1610*9880d681SAndroid Build Coastguard Worker
expandCodeFor(const SCEV * SH,Type * Ty,Instruction * IP)1611*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1612*9880d681SAndroid Build Coastguard Worker Instruction *IP) {
1613*9880d681SAndroid Build Coastguard Worker assert(IP);
1614*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(IP);
1615*9880d681SAndroid Build Coastguard Worker return expandCodeFor(SH, Ty);
1616*9880d681SAndroid Build Coastguard Worker }
1617*9880d681SAndroid Build Coastguard Worker
expandCodeFor(const SCEV * SH,Type * Ty)1618*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
1619*9880d681SAndroid Build Coastguard Worker // Expand the code for this SCEV.
1620*9880d681SAndroid Build Coastguard Worker Value *V = expand(SH);
1621*9880d681SAndroid Build Coastguard Worker if (Ty) {
1622*9880d681SAndroid Build Coastguard Worker assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1623*9880d681SAndroid Build Coastguard Worker "non-trivial casts should be done with the SCEVs directly!");
1624*9880d681SAndroid Build Coastguard Worker V = InsertNoopCastOfTo(V, Ty);
1625*9880d681SAndroid Build Coastguard Worker }
1626*9880d681SAndroid Build Coastguard Worker return V;
1627*9880d681SAndroid Build Coastguard Worker }
1628*9880d681SAndroid Build Coastguard Worker
FindValueInExprValueMap(const SCEV * S,const Instruction * InsertPt)1629*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::FindValueInExprValueMap(const SCEV *S,
1630*9880d681SAndroid Build Coastguard Worker const Instruction *InsertPt) {
1631*9880d681SAndroid Build Coastguard Worker SetVector<Value *> *Set = SE.getSCEVValues(S);
1632*9880d681SAndroid Build Coastguard Worker // If the expansion is not in CanonicalMode, and the SCEV contains any
1633*9880d681SAndroid Build Coastguard Worker // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1634*9880d681SAndroid Build Coastguard Worker if (CanonicalMode || !SE.containsAddRecurrence(S)) {
1635*9880d681SAndroid Build Coastguard Worker // If S is scConstant, it may be worse to reuse an existing Value.
1636*9880d681SAndroid Build Coastguard Worker if (S->getSCEVType() != scConstant && Set) {
1637*9880d681SAndroid Build Coastguard Worker // Choose a Value from the set which dominates the insertPt.
1638*9880d681SAndroid Build Coastguard Worker // insertPt should be inside the Value's parent loop so as not to break
1639*9880d681SAndroid Build Coastguard Worker // the LCSSA form.
1640*9880d681SAndroid Build Coastguard Worker for (auto const &Ent : *Set) {
1641*9880d681SAndroid Build Coastguard Worker Instruction *EntInst = nullptr;
1642*9880d681SAndroid Build Coastguard Worker if (Ent && isa<Instruction>(Ent) &&
1643*9880d681SAndroid Build Coastguard Worker (EntInst = cast<Instruction>(Ent)) &&
1644*9880d681SAndroid Build Coastguard Worker S->getType() == Ent->getType() &&
1645*9880d681SAndroid Build Coastguard Worker EntInst->getFunction() == InsertPt->getFunction() &&
1646*9880d681SAndroid Build Coastguard Worker SE.DT.dominates(EntInst, InsertPt) &&
1647*9880d681SAndroid Build Coastguard Worker (SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
1648*9880d681SAndroid Build Coastguard Worker SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt))) {
1649*9880d681SAndroid Build Coastguard Worker return Ent;
1650*9880d681SAndroid Build Coastguard Worker }
1651*9880d681SAndroid Build Coastguard Worker }
1652*9880d681SAndroid Build Coastguard Worker }
1653*9880d681SAndroid Build Coastguard Worker }
1654*9880d681SAndroid Build Coastguard Worker return nullptr;
1655*9880d681SAndroid Build Coastguard Worker }
1656*9880d681SAndroid Build Coastguard Worker
1657*9880d681SAndroid Build Coastguard Worker // The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1658*9880d681SAndroid Build Coastguard Worker // or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1659*9880d681SAndroid Build Coastguard Worker // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1660*9880d681SAndroid Build Coastguard Worker // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1661*9880d681SAndroid Build Coastguard Worker // the expansion will try to reuse Value from ExprValueMap, and only when it
1662*9880d681SAndroid Build Coastguard Worker // fails, expand the SCEV literally.
expand(const SCEV * S)1663*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::expand(const SCEV *S) {
1664*9880d681SAndroid Build Coastguard Worker // Compute an insertion point for this SCEV object. Hoist the instructions
1665*9880d681SAndroid Build Coastguard Worker // as far out in the loop nest as possible.
1666*9880d681SAndroid Build Coastguard Worker Instruction *InsertPt = &*Builder.GetInsertPoint();
1667*9880d681SAndroid Build Coastguard Worker for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1668*9880d681SAndroid Build Coastguard Worker L = L->getParentLoop())
1669*9880d681SAndroid Build Coastguard Worker if (SE.isLoopInvariant(S, L)) {
1670*9880d681SAndroid Build Coastguard Worker if (!L) break;
1671*9880d681SAndroid Build Coastguard Worker if (BasicBlock *Preheader = L->getLoopPreheader())
1672*9880d681SAndroid Build Coastguard Worker InsertPt = Preheader->getTerminator();
1673*9880d681SAndroid Build Coastguard Worker else {
1674*9880d681SAndroid Build Coastguard Worker // LSR sets the insertion point for AddRec start/step values to the
1675*9880d681SAndroid Build Coastguard Worker // block start to simplify value reuse, even though it's an invalid
1676*9880d681SAndroid Build Coastguard Worker // position. SCEVExpander must correct for this in all cases.
1677*9880d681SAndroid Build Coastguard Worker InsertPt = &*L->getHeader()->getFirstInsertionPt();
1678*9880d681SAndroid Build Coastguard Worker }
1679*9880d681SAndroid Build Coastguard Worker } else {
1680*9880d681SAndroid Build Coastguard Worker // If the SCEV is computable at this level, insert it into the header
1681*9880d681SAndroid Build Coastguard Worker // after the PHIs (and after any other instructions that we've inserted
1682*9880d681SAndroid Build Coastguard Worker // there) so that it is guaranteed to dominate any user inside the loop.
1683*9880d681SAndroid Build Coastguard Worker if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1684*9880d681SAndroid Build Coastguard Worker InsertPt = &*L->getHeader()->getFirstInsertionPt();
1685*9880d681SAndroid Build Coastguard Worker while (InsertPt->getIterator() != Builder.GetInsertPoint() &&
1686*9880d681SAndroid Build Coastguard Worker (isInsertedInstruction(InsertPt) ||
1687*9880d681SAndroid Build Coastguard Worker isa<DbgInfoIntrinsic>(InsertPt))) {
1688*9880d681SAndroid Build Coastguard Worker InsertPt = &*std::next(InsertPt->getIterator());
1689*9880d681SAndroid Build Coastguard Worker }
1690*9880d681SAndroid Build Coastguard Worker break;
1691*9880d681SAndroid Build Coastguard Worker }
1692*9880d681SAndroid Build Coastguard Worker
1693*9880d681SAndroid Build Coastguard Worker // Check to see if we already expanded this here.
1694*9880d681SAndroid Build Coastguard Worker auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
1695*9880d681SAndroid Build Coastguard Worker if (I != InsertedExpressions.end())
1696*9880d681SAndroid Build Coastguard Worker return I->second;
1697*9880d681SAndroid Build Coastguard Worker
1698*9880d681SAndroid Build Coastguard Worker SCEVInsertPointGuard Guard(Builder, this);
1699*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(InsertPt);
1700*9880d681SAndroid Build Coastguard Worker
1701*9880d681SAndroid Build Coastguard Worker // Expand the expression into instructions.
1702*9880d681SAndroid Build Coastguard Worker Value *V = FindValueInExprValueMap(S, InsertPt);
1703*9880d681SAndroid Build Coastguard Worker
1704*9880d681SAndroid Build Coastguard Worker if (!V)
1705*9880d681SAndroid Build Coastguard Worker V = visit(S);
1706*9880d681SAndroid Build Coastguard Worker
1707*9880d681SAndroid Build Coastguard Worker // Remember the expanded value for this SCEV at this location.
1708*9880d681SAndroid Build Coastguard Worker //
1709*9880d681SAndroid Build Coastguard Worker // This is independent of PostIncLoops. The mapped value simply materializes
1710*9880d681SAndroid Build Coastguard Worker // the expression at this insertion point. If the mapped value happened to be
1711*9880d681SAndroid Build Coastguard Worker // a postinc expansion, it could be reused by a non-postinc user, but only if
1712*9880d681SAndroid Build Coastguard Worker // its insertion point was already at the head of the loop.
1713*9880d681SAndroid Build Coastguard Worker InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1714*9880d681SAndroid Build Coastguard Worker return V;
1715*9880d681SAndroid Build Coastguard Worker }
1716*9880d681SAndroid Build Coastguard Worker
rememberInstruction(Value * I)1717*9880d681SAndroid Build Coastguard Worker void SCEVExpander::rememberInstruction(Value *I) {
1718*9880d681SAndroid Build Coastguard Worker if (!PostIncLoops.empty())
1719*9880d681SAndroid Build Coastguard Worker InsertedPostIncValues.insert(I);
1720*9880d681SAndroid Build Coastguard Worker else
1721*9880d681SAndroid Build Coastguard Worker InsertedValues.insert(I);
1722*9880d681SAndroid Build Coastguard Worker }
1723*9880d681SAndroid Build Coastguard Worker
1724*9880d681SAndroid Build Coastguard Worker /// getOrInsertCanonicalInductionVariable - This method returns the
1725*9880d681SAndroid Build Coastguard Worker /// canonical induction variable of the specified type for the specified
1726*9880d681SAndroid Build Coastguard Worker /// loop (inserting one if there is none). A canonical induction variable
1727*9880d681SAndroid Build Coastguard Worker /// starts at zero and steps by one on each iteration.
1728*9880d681SAndroid Build Coastguard Worker PHINode *
getOrInsertCanonicalInductionVariable(const Loop * L,Type * Ty)1729*9880d681SAndroid Build Coastguard Worker SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1730*9880d681SAndroid Build Coastguard Worker Type *Ty) {
1731*9880d681SAndroid Build Coastguard Worker assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1732*9880d681SAndroid Build Coastguard Worker
1733*9880d681SAndroid Build Coastguard Worker // Build a SCEV for {0,+,1}<L>.
1734*9880d681SAndroid Build Coastguard Worker // Conservatively use FlagAnyWrap for now.
1735*9880d681SAndroid Build Coastguard Worker const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1736*9880d681SAndroid Build Coastguard Worker SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1737*9880d681SAndroid Build Coastguard Worker
1738*9880d681SAndroid Build Coastguard Worker // Emit code for it.
1739*9880d681SAndroid Build Coastguard Worker SCEVInsertPointGuard Guard(Builder, this);
1740*9880d681SAndroid Build Coastguard Worker PHINode *V =
1741*9880d681SAndroid Build Coastguard Worker cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front()));
1742*9880d681SAndroid Build Coastguard Worker
1743*9880d681SAndroid Build Coastguard Worker return V;
1744*9880d681SAndroid Build Coastguard Worker }
1745*9880d681SAndroid Build Coastguard Worker
1746*9880d681SAndroid Build Coastguard Worker /// replaceCongruentIVs - Check for congruent phis in this loop header and
1747*9880d681SAndroid Build Coastguard Worker /// replace them with their most canonical representative. Return the number of
1748*9880d681SAndroid Build Coastguard Worker /// phis eliminated.
1749*9880d681SAndroid Build Coastguard Worker ///
1750*9880d681SAndroid Build Coastguard Worker /// This does not depend on any SCEVExpander state but should be used in
1751*9880d681SAndroid Build Coastguard Worker /// the same context that SCEVExpander is used.
replaceCongruentIVs(Loop * L,const DominatorTree * DT,SmallVectorImpl<WeakVH> & DeadInsts,const TargetTransformInfo * TTI)1752*9880d681SAndroid Build Coastguard Worker unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1753*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<WeakVH> &DeadInsts,
1754*9880d681SAndroid Build Coastguard Worker const TargetTransformInfo *TTI) {
1755*9880d681SAndroid Build Coastguard Worker // Find integer phis in order of increasing width.
1756*9880d681SAndroid Build Coastguard Worker SmallVector<PHINode*, 8> Phis;
1757*9880d681SAndroid Build Coastguard Worker for (auto &I : *L->getHeader()) {
1758*9880d681SAndroid Build Coastguard Worker if (auto *PN = dyn_cast<PHINode>(&I))
1759*9880d681SAndroid Build Coastguard Worker Phis.push_back(PN);
1760*9880d681SAndroid Build Coastguard Worker else
1761*9880d681SAndroid Build Coastguard Worker break;
1762*9880d681SAndroid Build Coastguard Worker }
1763*9880d681SAndroid Build Coastguard Worker
1764*9880d681SAndroid Build Coastguard Worker if (TTI)
1765*9880d681SAndroid Build Coastguard Worker std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
1766*9880d681SAndroid Build Coastguard Worker // Put pointers at the back and make sure pointer < pointer = false.
1767*9880d681SAndroid Build Coastguard Worker if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1768*9880d681SAndroid Build Coastguard Worker return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1769*9880d681SAndroid Build Coastguard Worker return RHS->getType()->getPrimitiveSizeInBits() <
1770*9880d681SAndroid Build Coastguard Worker LHS->getType()->getPrimitiveSizeInBits();
1771*9880d681SAndroid Build Coastguard Worker });
1772*9880d681SAndroid Build Coastguard Worker
1773*9880d681SAndroid Build Coastguard Worker unsigned NumElim = 0;
1774*9880d681SAndroid Build Coastguard Worker DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1775*9880d681SAndroid Build Coastguard Worker // Process phis from wide to narrow. Map wide phis to their truncation
1776*9880d681SAndroid Build Coastguard Worker // so narrow phis can reuse them.
1777*9880d681SAndroid Build Coastguard Worker for (PHINode *Phi : Phis) {
1778*9880d681SAndroid Build Coastguard Worker auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1779*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyInstruction(PN, DL, &SE.TLI, &SE.DT, &SE.AC))
1780*9880d681SAndroid Build Coastguard Worker return V;
1781*9880d681SAndroid Build Coastguard Worker if (!SE.isSCEVable(PN->getType()))
1782*9880d681SAndroid Build Coastguard Worker return nullptr;
1783*9880d681SAndroid Build Coastguard Worker auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1784*9880d681SAndroid Build Coastguard Worker if (!Const)
1785*9880d681SAndroid Build Coastguard Worker return nullptr;
1786*9880d681SAndroid Build Coastguard Worker return Const->getValue();
1787*9880d681SAndroid Build Coastguard Worker };
1788*9880d681SAndroid Build Coastguard Worker
1789*9880d681SAndroid Build Coastguard Worker // Fold constant phis. They may be congruent to other constant phis and
1790*9880d681SAndroid Build Coastguard Worker // would confuse the logic below that expects proper IVs.
1791*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyPHINode(Phi)) {
1792*9880d681SAndroid Build Coastguard Worker if (V->getType() != Phi->getType())
1793*9880d681SAndroid Build Coastguard Worker continue;
1794*9880d681SAndroid Build Coastguard Worker Phi->replaceAllUsesWith(V);
1795*9880d681SAndroid Build Coastguard Worker DeadInsts.emplace_back(Phi);
1796*9880d681SAndroid Build Coastguard Worker ++NumElim;
1797*9880d681SAndroid Build Coastguard Worker DEBUG_WITH_TYPE(DebugType, dbgs()
1798*9880d681SAndroid Build Coastguard Worker << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1799*9880d681SAndroid Build Coastguard Worker continue;
1800*9880d681SAndroid Build Coastguard Worker }
1801*9880d681SAndroid Build Coastguard Worker
1802*9880d681SAndroid Build Coastguard Worker if (!SE.isSCEVable(Phi->getType()))
1803*9880d681SAndroid Build Coastguard Worker continue;
1804*9880d681SAndroid Build Coastguard Worker
1805*9880d681SAndroid Build Coastguard Worker PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1806*9880d681SAndroid Build Coastguard Worker if (!OrigPhiRef) {
1807*9880d681SAndroid Build Coastguard Worker OrigPhiRef = Phi;
1808*9880d681SAndroid Build Coastguard Worker if (Phi->getType()->isIntegerTy() && TTI &&
1809*9880d681SAndroid Build Coastguard Worker TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1810*9880d681SAndroid Build Coastguard Worker // This phi can be freely truncated to the narrowest phi type. Map the
1811*9880d681SAndroid Build Coastguard Worker // truncated expression to it so it will be reused for narrow types.
1812*9880d681SAndroid Build Coastguard Worker const SCEV *TruncExpr =
1813*9880d681SAndroid Build Coastguard Worker SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1814*9880d681SAndroid Build Coastguard Worker ExprToIVMap[TruncExpr] = Phi;
1815*9880d681SAndroid Build Coastguard Worker }
1816*9880d681SAndroid Build Coastguard Worker continue;
1817*9880d681SAndroid Build Coastguard Worker }
1818*9880d681SAndroid Build Coastguard Worker
1819*9880d681SAndroid Build Coastguard Worker // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1820*9880d681SAndroid Build Coastguard Worker // sense.
1821*9880d681SAndroid Build Coastguard Worker if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1822*9880d681SAndroid Build Coastguard Worker continue;
1823*9880d681SAndroid Build Coastguard Worker
1824*9880d681SAndroid Build Coastguard Worker if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1825*9880d681SAndroid Build Coastguard Worker Instruction *OrigInc = dyn_cast<Instruction>(
1826*9880d681SAndroid Build Coastguard Worker OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1827*9880d681SAndroid Build Coastguard Worker Instruction *IsomorphicInc =
1828*9880d681SAndroid Build Coastguard Worker dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1829*9880d681SAndroid Build Coastguard Worker
1830*9880d681SAndroid Build Coastguard Worker if (OrigInc && IsomorphicInc) {
1831*9880d681SAndroid Build Coastguard Worker // If this phi has the same width but is more canonical, replace the
1832*9880d681SAndroid Build Coastguard Worker // original with it. As part of the "more canonical" determination,
1833*9880d681SAndroid Build Coastguard Worker // respect a prior decision to use an IV chain.
1834*9880d681SAndroid Build Coastguard Worker if (OrigPhiRef->getType() == Phi->getType() &&
1835*9880d681SAndroid Build Coastguard Worker !(ChainedPhis.count(Phi) ||
1836*9880d681SAndroid Build Coastguard Worker isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
1837*9880d681SAndroid Build Coastguard Worker (ChainedPhis.count(Phi) ||
1838*9880d681SAndroid Build Coastguard Worker isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1839*9880d681SAndroid Build Coastguard Worker std::swap(OrigPhiRef, Phi);
1840*9880d681SAndroid Build Coastguard Worker std::swap(OrigInc, IsomorphicInc);
1841*9880d681SAndroid Build Coastguard Worker }
1842*9880d681SAndroid Build Coastguard Worker // Replacing the congruent phi is sufficient because acyclic
1843*9880d681SAndroid Build Coastguard Worker // redundancy elimination, CSE/GVN, should handle the
1844*9880d681SAndroid Build Coastguard Worker // rest. However, once SCEV proves that a phi is congruent,
1845*9880d681SAndroid Build Coastguard Worker // it's often the head of an IV user cycle that is isomorphic
1846*9880d681SAndroid Build Coastguard Worker // with the original phi. It's worth eagerly cleaning up the
1847*9880d681SAndroid Build Coastguard Worker // common case of a single IV increment so that DeleteDeadPHIs
1848*9880d681SAndroid Build Coastguard Worker // can remove cycles that had postinc uses.
1849*9880d681SAndroid Build Coastguard Worker const SCEV *TruncExpr =
1850*9880d681SAndroid Build Coastguard Worker SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
1851*9880d681SAndroid Build Coastguard Worker if (OrigInc != IsomorphicInc &&
1852*9880d681SAndroid Build Coastguard Worker TruncExpr == SE.getSCEV(IsomorphicInc) &&
1853*9880d681SAndroid Build Coastguard Worker SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
1854*9880d681SAndroid Build Coastguard Worker hoistIVInc(OrigInc, IsomorphicInc)) {
1855*9880d681SAndroid Build Coastguard Worker DEBUG_WITH_TYPE(DebugType,
1856*9880d681SAndroid Build Coastguard Worker dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1857*9880d681SAndroid Build Coastguard Worker << *IsomorphicInc << '\n');
1858*9880d681SAndroid Build Coastguard Worker Value *NewInc = OrigInc;
1859*9880d681SAndroid Build Coastguard Worker if (OrigInc->getType() != IsomorphicInc->getType()) {
1860*9880d681SAndroid Build Coastguard Worker Instruction *IP = nullptr;
1861*9880d681SAndroid Build Coastguard Worker if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1862*9880d681SAndroid Build Coastguard Worker IP = &*PN->getParent()->getFirstInsertionPt();
1863*9880d681SAndroid Build Coastguard Worker else
1864*9880d681SAndroid Build Coastguard Worker IP = OrigInc->getNextNode();
1865*9880d681SAndroid Build Coastguard Worker
1866*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(IP);
1867*9880d681SAndroid Build Coastguard Worker Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1868*9880d681SAndroid Build Coastguard Worker NewInc = Builder.CreateTruncOrBitCast(
1869*9880d681SAndroid Build Coastguard Worker OrigInc, IsomorphicInc->getType(), IVName);
1870*9880d681SAndroid Build Coastguard Worker }
1871*9880d681SAndroid Build Coastguard Worker IsomorphicInc->replaceAllUsesWith(NewInc);
1872*9880d681SAndroid Build Coastguard Worker DeadInsts.emplace_back(IsomorphicInc);
1873*9880d681SAndroid Build Coastguard Worker }
1874*9880d681SAndroid Build Coastguard Worker }
1875*9880d681SAndroid Build Coastguard Worker }
1876*9880d681SAndroid Build Coastguard Worker DEBUG_WITH_TYPE(DebugType, dbgs() << "INDVARS: Eliminated congruent iv: "
1877*9880d681SAndroid Build Coastguard Worker << *Phi << '\n');
1878*9880d681SAndroid Build Coastguard Worker ++NumElim;
1879*9880d681SAndroid Build Coastguard Worker Value *NewIV = OrigPhiRef;
1880*9880d681SAndroid Build Coastguard Worker if (OrigPhiRef->getType() != Phi->getType()) {
1881*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
1882*9880d681SAndroid Build Coastguard Worker Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1883*9880d681SAndroid Build Coastguard Worker NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1884*9880d681SAndroid Build Coastguard Worker }
1885*9880d681SAndroid Build Coastguard Worker Phi->replaceAllUsesWith(NewIV);
1886*9880d681SAndroid Build Coastguard Worker DeadInsts.emplace_back(Phi);
1887*9880d681SAndroid Build Coastguard Worker }
1888*9880d681SAndroid Build Coastguard Worker return NumElim;
1889*9880d681SAndroid Build Coastguard Worker }
1890*9880d681SAndroid Build Coastguard Worker
findExistingExpansion(const SCEV * S,const Instruction * At,Loop * L)1891*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::findExistingExpansion(const SCEV *S,
1892*9880d681SAndroid Build Coastguard Worker const Instruction *At, Loop *L) {
1893*9880d681SAndroid Build Coastguard Worker using namespace llvm::PatternMatch;
1894*9880d681SAndroid Build Coastguard Worker
1895*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 4> ExitingBlocks;
1896*9880d681SAndroid Build Coastguard Worker L->getExitingBlocks(ExitingBlocks);
1897*9880d681SAndroid Build Coastguard Worker
1898*9880d681SAndroid Build Coastguard Worker // Look for suitable value in simple conditions at the loop exits.
1899*9880d681SAndroid Build Coastguard Worker for (BasicBlock *BB : ExitingBlocks) {
1900*9880d681SAndroid Build Coastguard Worker ICmpInst::Predicate Pred;
1901*9880d681SAndroid Build Coastguard Worker Instruction *LHS, *RHS;
1902*9880d681SAndroid Build Coastguard Worker BasicBlock *TrueBB, *FalseBB;
1903*9880d681SAndroid Build Coastguard Worker
1904*9880d681SAndroid Build Coastguard Worker if (!match(BB->getTerminator(),
1905*9880d681SAndroid Build Coastguard Worker m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1906*9880d681SAndroid Build Coastguard Worker TrueBB, FalseBB)))
1907*9880d681SAndroid Build Coastguard Worker continue;
1908*9880d681SAndroid Build Coastguard Worker
1909*9880d681SAndroid Build Coastguard Worker if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1910*9880d681SAndroid Build Coastguard Worker return LHS;
1911*9880d681SAndroid Build Coastguard Worker
1912*9880d681SAndroid Build Coastguard Worker if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
1913*9880d681SAndroid Build Coastguard Worker return RHS;
1914*9880d681SAndroid Build Coastguard Worker }
1915*9880d681SAndroid Build Coastguard Worker
1916*9880d681SAndroid Build Coastguard Worker // Use expand's logic which is used for reusing a previous Value in
1917*9880d681SAndroid Build Coastguard Worker // ExprValueMap.
1918*9880d681SAndroid Build Coastguard Worker if (Value *Val = FindValueInExprValueMap(S, At))
1919*9880d681SAndroid Build Coastguard Worker return Val;
1920*9880d681SAndroid Build Coastguard Worker
1921*9880d681SAndroid Build Coastguard Worker // There is potential to make this significantly smarter, but this simple
1922*9880d681SAndroid Build Coastguard Worker // heuristic already gets some interesting cases.
1923*9880d681SAndroid Build Coastguard Worker
1924*9880d681SAndroid Build Coastguard Worker // Can not find suitable value.
1925*9880d681SAndroid Build Coastguard Worker return nullptr;
1926*9880d681SAndroid Build Coastguard Worker }
1927*9880d681SAndroid Build Coastguard Worker
isHighCostExpansionHelper(const SCEV * S,Loop * L,const Instruction * At,SmallPtrSetImpl<const SCEV * > & Processed)1928*9880d681SAndroid Build Coastguard Worker bool SCEVExpander::isHighCostExpansionHelper(
1929*9880d681SAndroid Build Coastguard Worker const SCEV *S, Loop *L, const Instruction *At,
1930*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<const SCEV *> &Processed) {
1931*9880d681SAndroid Build Coastguard Worker
1932*9880d681SAndroid Build Coastguard Worker // If we can find an existing value for this scev avaliable at the point "At"
1933*9880d681SAndroid Build Coastguard Worker // then consider the expression cheap.
1934*9880d681SAndroid Build Coastguard Worker if (At && findExistingExpansion(S, At, L) != nullptr)
1935*9880d681SAndroid Build Coastguard Worker return false;
1936*9880d681SAndroid Build Coastguard Worker
1937*9880d681SAndroid Build Coastguard Worker // Zero/One operand expressions
1938*9880d681SAndroid Build Coastguard Worker switch (S->getSCEVType()) {
1939*9880d681SAndroid Build Coastguard Worker case scUnknown:
1940*9880d681SAndroid Build Coastguard Worker case scConstant:
1941*9880d681SAndroid Build Coastguard Worker return false;
1942*9880d681SAndroid Build Coastguard Worker case scTruncate:
1943*9880d681SAndroid Build Coastguard Worker return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
1944*9880d681SAndroid Build Coastguard Worker L, At, Processed);
1945*9880d681SAndroid Build Coastguard Worker case scZeroExtend:
1946*9880d681SAndroid Build Coastguard Worker return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
1947*9880d681SAndroid Build Coastguard Worker L, At, Processed);
1948*9880d681SAndroid Build Coastguard Worker case scSignExtend:
1949*9880d681SAndroid Build Coastguard Worker return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
1950*9880d681SAndroid Build Coastguard Worker L, At, Processed);
1951*9880d681SAndroid Build Coastguard Worker }
1952*9880d681SAndroid Build Coastguard Worker
1953*9880d681SAndroid Build Coastguard Worker if (!Processed.insert(S).second)
1954*9880d681SAndroid Build Coastguard Worker return false;
1955*9880d681SAndroid Build Coastguard Worker
1956*9880d681SAndroid Build Coastguard Worker if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
1957*9880d681SAndroid Build Coastguard Worker // If the divisor is a power of two and the SCEV type fits in a native
1958*9880d681SAndroid Build Coastguard Worker // integer, consider the division cheap irrespective of whether it occurs in
1959*9880d681SAndroid Build Coastguard Worker // the user code since it can be lowered into a right shift.
1960*9880d681SAndroid Build Coastguard Worker if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
1961*9880d681SAndroid Build Coastguard Worker if (SC->getAPInt().isPowerOf2()) {
1962*9880d681SAndroid Build Coastguard Worker const DataLayout &DL =
1963*9880d681SAndroid Build Coastguard Worker L->getHeader()->getParent()->getParent()->getDataLayout();
1964*9880d681SAndroid Build Coastguard Worker unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
1965*9880d681SAndroid Build Coastguard Worker return DL.isIllegalInteger(Width);
1966*9880d681SAndroid Build Coastguard Worker }
1967*9880d681SAndroid Build Coastguard Worker
1968*9880d681SAndroid Build Coastguard Worker // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
1969*9880d681SAndroid Build Coastguard Worker // HowManyLessThans produced to compute a precise expression, rather than a
1970*9880d681SAndroid Build Coastguard Worker // UDiv from the user's code. If we can't find a UDiv in the code with some
1971*9880d681SAndroid Build Coastguard Worker // simple searching, assume the former consider UDivExpr expensive to
1972*9880d681SAndroid Build Coastguard Worker // compute.
1973*9880d681SAndroid Build Coastguard Worker BasicBlock *ExitingBB = L->getExitingBlock();
1974*9880d681SAndroid Build Coastguard Worker if (!ExitingBB)
1975*9880d681SAndroid Build Coastguard Worker return true;
1976*9880d681SAndroid Build Coastguard Worker
1977*9880d681SAndroid Build Coastguard Worker // At the beginning of this function we already tried to find existing value
1978*9880d681SAndroid Build Coastguard Worker // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern
1979*9880d681SAndroid Build Coastguard Worker // involving division. This is just a simple search heuristic.
1980*9880d681SAndroid Build Coastguard Worker if (!At)
1981*9880d681SAndroid Build Coastguard Worker At = &ExitingBB->back();
1982*9880d681SAndroid Build Coastguard Worker if (!findExistingExpansion(
1983*9880d681SAndroid Build Coastguard Worker SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L))
1984*9880d681SAndroid Build Coastguard Worker return true;
1985*9880d681SAndroid Build Coastguard Worker }
1986*9880d681SAndroid Build Coastguard Worker
1987*9880d681SAndroid Build Coastguard Worker // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1988*9880d681SAndroid Build Coastguard Worker // the exit condition.
1989*9880d681SAndroid Build Coastguard Worker if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1990*9880d681SAndroid Build Coastguard Worker return true;
1991*9880d681SAndroid Build Coastguard Worker
1992*9880d681SAndroid Build Coastguard Worker // Recurse past nary expressions, which commonly occur in the
1993*9880d681SAndroid Build Coastguard Worker // BackedgeTakenCount. They may already exist in program code, and if not,
1994*9880d681SAndroid Build Coastguard Worker // they are not too expensive rematerialize.
1995*9880d681SAndroid Build Coastguard Worker if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
1996*9880d681SAndroid Build Coastguard Worker for (auto *Op : NAry->operands())
1997*9880d681SAndroid Build Coastguard Worker if (isHighCostExpansionHelper(Op, L, At, Processed))
1998*9880d681SAndroid Build Coastguard Worker return true;
1999*9880d681SAndroid Build Coastguard Worker }
2000*9880d681SAndroid Build Coastguard Worker
2001*9880d681SAndroid Build Coastguard Worker // If we haven't recognized an expensive SCEV pattern, assume it's an
2002*9880d681SAndroid Build Coastguard Worker // expression produced by program code.
2003*9880d681SAndroid Build Coastguard Worker return false;
2004*9880d681SAndroid Build Coastguard Worker }
2005*9880d681SAndroid Build Coastguard Worker
expandCodeForPredicate(const SCEVPredicate * Pred,Instruction * IP)2006*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
2007*9880d681SAndroid Build Coastguard Worker Instruction *IP) {
2008*9880d681SAndroid Build Coastguard Worker assert(IP);
2009*9880d681SAndroid Build Coastguard Worker switch (Pred->getKind()) {
2010*9880d681SAndroid Build Coastguard Worker case SCEVPredicate::P_Union:
2011*9880d681SAndroid Build Coastguard Worker return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2012*9880d681SAndroid Build Coastguard Worker case SCEVPredicate::P_Equal:
2013*9880d681SAndroid Build Coastguard Worker return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
2014*9880d681SAndroid Build Coastguard Worker case SCEVPredicate::P_Wrap: {
2015*9880d681SAndroid Build Coastguard Worker auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2016*9880d681SAndroid Build Coastguard Worker return expandWrapPredicate(AddRecPred, IP);
2017*9880d681SAndroid Build Coastguard Worker }
2018*9880d681SAndroid Build Coastguard Worker }
2019*9880d681SAndroid Build Coastguard Worker llvm_unreachable("Unknown SCEV predicate type");
2020*9880d681SAndroid Build Coastguard Worker }
2021*9880d681SAndroid Build Coastguard Worker
expandEqualPredicate(const SCEVEqualPredicate * Pred,Instruction * IP)2022*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::expandEqualPredicate(const SCEVEqualPredicate *Pred,
2023*9880d681SAndroid Build Coastguard Worker Instruction *IP) {
2024*9880d681SAndroid Build Coastguard Worker Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP);
2025*9880d681SAndroid Build Coastguard Worker Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP);
2026*9880d681SAndroid Build Coastguard Worker
2027*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(IP);
2028*9880d681SAndroid Build Coastguard Worker auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
2029*9880d681SAndroid Build Coastguard Worker return I;
2030*9880d681SAndroid Build Coastguard Worker }
2031*9880d681SAndroid Build Coastguard Worker
generateOverflowCheck(const SCEVAddRecExpr * AR,Instruction * Loc,bool Signed)2032*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
2033*9880d681SAndroid Build Coastguard Worker Instruction *Loc, bool Signed) {
2034*9880d681SAndroid Build Coastguard Worker assert(AR->isAffine() && "Cannot generate RT check for "
2035*9880d681SAndroid Build Coastguard Worker "non-affine expression");
2036*9880d681SAndroid Build Coastguard Worker
2037*9880d681SAndroid Build Coastguard Worker SCEVUnionPredicate Pred;
2038*9880d681SAndroid Build Coastguard Worker const SCEV *ExitCount =
2039*9880d681SAndroid Build Coastguard Worker SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
2040*9880d681SAndroid Build Coastguard Worker
2041*9880d681SAndroid Build Coastguard Worker assert(ExitCount != SE.getCouldNotCompute() && "Invalid loop count");
2042*9880d681SAndroid Build Coastguard Worker
2043*9880d681SAndroid Build Coastguard Worker const SCEV *Step = AR->getStepRecurrence(SE);
2044*9880d681SAndroid Build Coastguard Worker const SCEV *Start = AR->getStart();
2045*9880d681SAndroid Build Coastguard Worker
2046*9880d681SAndroid Build Coastguard Worker unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2047*9880d681SAndroid Build Coastguard Worker unsigned DstBits = SE.getTypeSizeInBits(AR->getType());
2048*9880d681SAndroid Build Coastguard Worker
2049*9880d681SAndroid Build Coastguard Worker // The expression {Start,+,Step} has nusw/nssw if
2050*9880d681SAndroid Build Coastguard Worker // Step < 0, Start - |Step| * Backedge <= Start
2051*9880d681SAndroid Build Coastguard Worker // Step >= 0, Start + |Step| * Backedge > Start
2052*9880d681SAndroid Build Coastguard Worker // and |Step| * Backedge doesn't unsigned overflow.
2053*9880d681SAndroid Build Coastguard Worker
2054*9880d681SAndroid Build Coastguard Worker IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits);
2055*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(Loc);
2056*9880d681SAndroid Build Coastguard Worker Value *TripCountVal = expandCodeFor(ExitCount, CountTy, Loc);
2057*9880d681SAndroid Build Coastguard Worker
2058*9880d681SAndroid Build Coastguard Worker IntegerType *Ty =
2059*9880d681SAndroid Build Coastguard Worker IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(AR->getType()));
2060*9880d681SAndroid Build Coastguard Worker
2061*9880d681SAndroid Build Coastguard Worker Value *StepValue = expandCodeFor(Step, Ty, Loc);
2062*9880d681SAndroid Build Coastguard Worker Value *NegStepValue = expandCodeFor(SE.getNegativeSCEV(Step), Ty, Loc);
2063*9880d681SAndroid Build Coastguard Worker Value *StartValue = expandCodeFor(Start, Ty, Loc);
2064*9880d681SAndroid Build Coastguard Worker
2065*9880d681SAndroid Build Coastguard Worker ConstantInt *Zero =
2066*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Loc->getContext(), APInt::getNullValue(DstBits));
2067*9880d681SAndroid Build Coastguard Worker
2068*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(Loc);
2069*9880d681SAndroid Build Coastguard Worker // Compute |Step|
2070*9880d681SAndroid Build Coastguard Worker Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2071*9880d681SAndroid Build Coastguard Worker Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
2072*9880d681SAndroid Build Coastguard Worker
2073*9880d681SAndroid Build Coastguard Worker // Get the backedge taken count and truncate or extended to the AR type.
2074*9880d681SAndroid Build Coastguard Worker Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2075*9880d681SAndroid Build Coastguard Worker auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
2076*9880d681SAndroid Build Coastguard Worker Intrinsic::umul_with_overflow, Ty);
2077*9880d681SAndroid Build Coastguard Worker
2078*9880d681SAndroid Build Coastguard Worker // Compute |Step| * Backedge
2079*9880d681SAndroid Build Coastguard Worker CallInst *Mul = Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2080*9880d681SAndroid Build Coastguard Worker Value *MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2081*9880d681SAndroid Build Coastguard Worker Value *OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2082*9880d681SAndroid Build Coastguard Worker
2083*9880d681SAndroid Build Coastguard Worker // Compute:
2084*9880d681SAndroid Build Coastguard Worker // Start + |Step| * Backedge < Start
2085*9880d681SAndroid Build Coastguard Worker // Start - |Step| * Backedge > Start
2086*9880d681SAndroid Build Coastguard Worker Value *Add = Builder.CreateAdd(StartValue, MulV);
2087*9880d681SAndroid Build Coastguard Worker Value *Sub = Builder.CreateSub(StartValue, MulV);
2088*9880d681SAndroid Build Coastguard Worker
2089*9880d681SAndroid Build Coastguard Worker Value *EndCompareGT = Builder.CreateICmp(
2090*9880d681SAndroid Build Coastguard Worker Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
2091*9880d681SAndroid Build Coastguard Worker
2092*9880d681SAndroid Build Coastguard Worker Value *EndCompareLT = Builder.CreateICmp(
2093*9880d681SAndroid Build Coastguard Worker Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
2094*9880d681SAndroid Build Coastguard Worker
2095*9880d681SAndroid Build Coastguard Worker // Select the answer based on the sign of Step.
2096*9880d681SAndroid Build Coastguard Worker Value *EndCheck =
2097*9880d681SAndroid Build Coastguard Worker Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2098*9880d681SAndroid Build Coastguard Worker
2099*9880d681SAndroid Build Coastguard Worker // If the backedge taken count type is larger than the AR type,
2100*9880d681SAndroid Build Coastguard Worker // check that we don't drop any bits by truncating it. If we are
2101*9880d681SAndroid Build Coastguard Worker // droping bits, then we have overflow (unless the step is zero).
2102*9880d681SAndroid Build Coastguard Worker if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
2103*9880d681SAndroid Build Coastguard Worker auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2104*9880d681SAndroid Build Coastguard Worker auto *BackedgeCheck =
2105*9880d681SAndroid Build Coastguard Worker Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2106*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Loc->getContext(), MaxVal));
2107*9880d681SAndroid Build Coastguard Worker BackedgeCheck = Builder.CreateAnd(
2108*9880d681SAndroid Build Coastguard Worker BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2109*9880d681SAndroid Build Coastguard Worker
2110*9880d681SAndroid Build Coastguard Worker EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2111*9880d681SAndroid Build Coastguard Worker }
2112*9880d681SAndroid Build Coastguard Worker
2113*9880d681SAndroid Build Coastguard Worker EndCheck = Builder.CreateOr(EndCheck, OfMul);
2114*9880d681SAndroid Build Coastguard Worker return EndCheck;
2115*9880d681SAndroid Build Coastguard Worker }
2116*9880d681SAndroid Build Coastguard Worker
expandWrapPredicate(const SCEVWrapPredicate * Pred,Instruction * IP)2117*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
2118*9880d681SAndroid Build Coastguard Worker Instruction *IP) {
2119*9880d681SAndroid Build Coastguard Worker const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2120*9880d681SAndroid Build Coastguard Worker Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2121*9880d681SAndroid Build Coastguard Worker
2122*9880d681SAndroid Build Coastguard Worker // Add a check for NUSW
2123*9880d681SAndroid Build Coastguard Worker if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
2124*9880d681SAndroid Build Coastguard Worker NUSWCheck = generateOverflowCheck(A, IP, false);
2125*9880d681SAndroid Build Coastguard Worker
2126*9880d681SAndroid Build Coastguard Worker // Add a check for NSSW
2127*9880d681SAndroid Build Coastguard Worker if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
2128*9880d681SAndroid Build Coastguard Worker NSSWCheck = generateOverflowCheck(A, IP, true);
2129*9880d681SAndroid Build Coastguard Worker
2130*9880d681SAndroid Build Coastguard Worker if (NUSWCheck && NSSWCheck)
2131*9880d681SAndroid Build Coastguard Worker return Builder.CreateOr(NUSWCheck, NSSWCheck);
2132*9880d681SAndroid Build Coastguard Worker
2133*9880d681SAndroid Build Coastguard Worker if (NUSWCheck)
2134*9880d681SAndroid Build Coastguard Worker return NUSWCheck;
2135*9880d681SAndroid Build Coastguard Worker
2136*9880d681SAndroid Build Coastguard Worker if (NSSWCheck)
2137*9880d681SAndroid Build Coastguard Worker return NSSWCheck;
2138*9880d681SAndroid Build Coastguard Worker
2139*9880d681SAndroid Build Coastguard Worker return ConstantInt::getFalse(IP->getContext());
2140*9880d681SAndroid Build Coastguard Worker }
2141*9880d681SAndroid Build Coastguard Worker
expandUnionPredicate(const SCEVUnionPredicate * Union,Instruction * IP)2142*9880d681SAndroid Build Coastguard Worker Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
2143*9880d681SAndroid Build Coastguard Worker Instruction *IP) {
2144*9880d681SAndroid Build Coastguard Worker auto *BoolType = IntegerType::get(IP->getContext(), 1);
2145*9880d681SAndroid Build Coastguard Worker Value *Check = ConstantInt::getNullValue(BoolType);
2146*9880d681SAndroid Build Coastguard Worker
2147*9880d681SAndroid Build Coastguard Worker // Loop over all checks in this set.
2148*9880d681SAndroid Build Coastguard Worker for (auto Pred : Union->getPredicates()) {
2149*9880d681SAndroid Build Coastguard Worker auto *NextCheck = expandCodeForPredicate(Pred, IP);
2150*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(IP);
2151*9880d681SAndroid Build Coastguard Worker Check = Builder.CreateOr(Check, NextCheck);
2152*9880d681SAndroid Build Coastguard Worker }
2153*9880d681SAndroid Build Coastguard Worker
2154*9880d681SAndroid Build Coastguard Worker return Check;
2155*9880d681SAndroid Build Coastguard Worker }
2156*9880d681SAndroid Build Coastguard Worker
2157*9880d681SAndroid Build Coastguard Worker namespace {
2158*9880d681SAndroid Build Coastguard Worker // Search for a SCEV subexpression that is not safe to expand. Any expression
2159*9880d681SAndroid Build Coastguard Worker // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2160*9880d681SAndroid Build Coastguard Worker // UDiv expressions. We don't know if the UDiv is derived from an IR divide
2161*9880d681SAndroid Build Coastguard Worker // instruction, but the important thing is that we prove the denominator is
2162*9880d681SAndroid Build Coastguard Worker // nonzero before expansion.
2163*9880d681SAndroid Build Coastguard Worker //
2164*9880d681SAndroid Build Coastguard Worker // IVUsers already checks that IV-derived expressions are safe. So this check is
2165*9880d681SAndroid Build Coastguard Worker // only needed when the expression includes some subexpression that is not IV
2166*9880d681SAndroid Build Coastguard Worker // derived.
2167*9880d681SAndroid Build Coastguard Worker //
2168*9880d681SAndroid Build Coastguard Worker // Currently, we only allow division by a nonzero constant here. If this is
2169*9880d681SAndroid Build Coastguard Worker // inadequate, we could easily allow division by SCEVUnknown by using
2170*9880d681SAndroid Build Coastguard Worker // ValueTracking to check isKnownNonZero().
2171*9880d681SAndroid Build Coastguard Worker //
2172*9880d681SAndroid Build Coastguard Worker // We cannot generally expand recurrences unless the step dominates the loop
2173*9880d681SAndroid Build Coastguard Worker // header. The expander handles the special case of affine recurrences by
2174*9880d681SAndroid Build Coastguard Worker // scaling the recurrence outside the loop, but this technique isn't generally
2175*9880d681SAndroid Build Coastguard Worker // applicable. Expanding a nested recurrence outside a loop requires computing
2176*9880d681SAndroid Build Coastguard Worker // binomial coefficients. This could be done, but the recurrence has to be in a
2177*9880d681SAndroid Build Coastguard Worker // perfectly reduced form, which can't be guaranteed.
2178*9880d681SAndroid Build Coastguard Worker struct SCEVFindUnsafe {
2179*9880d681SAndroid Build Coastguard Worker ScalarEvolution &SE;
2180*9880d681SAndroid Build Coastguard Worker bool IsUnsafe;
2181*9880d681SAndroid Build Coastguard Worker
SCEVFindUnsafe__anondcda4fad0511::SCEVFindUnsafe2182*9880d681SAndroid Build Coastguard Worker SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
2183*9880d681SAndroid Build Coastguard Worker
follow__anondcda4fad0511::SCEVFindUnsafe2184*9880d681SAndroid Build Coastguard Worker bool follow(const SCEV *S) {
2185*9880d681SAndroid Build Coastguard Worker if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2186*9880d681SAndroid Build Coastguard Worker const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
2187*9880d681SAndroid Build Coastguard Worker if (!SC || SC->getValue()->isZero()) {
2188*9880d681SAndroid Build Coastguard Worker IsUnsafe = true;
2189*9880d681SAndroid Build Coastguard Worker return false;
2190*9880d681SAndroid Build Coastguard Worker }
2191*9880d681SAndroid Build Coastguard Worker }
2192*9880d681SAndroid Build Coastguard Worker if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2193*9880d681SAndroid Build Coastguard Worker const SCEV *Step = AR->getStepRecurrence(SE);
2194*9880d681SAndroid Build Coastguard Worker if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
2195*9880d681SAndroid Build Coastguard Worker IsUnsafe = true;
2196*9880d681SAndroid Build Coastguard Worker return false;
2197*9880d681SAndroid Build Coastguard Worker }
2198*9880d681SAndroid Build Coastguard Worker }
2199*9880d681SAndroid Build Coastguard Worker return true;
2200*9880d681SAndroid Build Coastguard Worker }
isDone__anondcda4fad0511::SCEVFindUnsafe2201*9880d681SAndroid Build Coastguard Worker bool isDone() const { return IsUnsafe; }
2202*9880d681SAndroid Build Coastguard Worker };
2203*9880d681SAndroid Build Coastguard Worker }
2204*9880d681SAndroid Build Coastguard Worker
2205*9880d681SAndroid Build Coastguard Worker namespace llvm {
isSafeToExpand(const SCEV * S,ScalarEvolution & SE)2206*9880d681SAndroid Build Coastguard Worker bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
2207*9880d681SAndroid Build Coastguard Worker SCEVFindUnsafe Search(SE);
2208*9880d681SAndroid Build Coastguard Worker visitAll(S, Search);
2209*9880d681SAndroid Build Coastguard Worker return !Search.IsUnsafe;
2210*9880d681SAndroid Build Coastguard Worker }
2211*9880d681SAndroid Build Coastguard Worker }
2212