1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the scalar evolution expander,
11 // which is used to generate the code corresponding to a given scalar evolution
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Analysis/ScalarEvolutionExpander.h"
17 #include "llvm/Analysis/LoopInfo.h"
20 /// InsertCastOfTo - Insert a cast of V to the specified type, doing what
21 /// we can to share the casts.
22 Value
*SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode
, Value
*V
,
24 // Short-circuit unnecessary bitcasts.
25 if (opcode
== Instruction::BitCast
&& V
->getType() == Ty
)
28 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
29 if ((opcode
== Instruction::PtrToInt
|| opcode
== Instruction::IntToPtr
) &&
30 SE
.getTypeSizeInBits(Ty
) == SE
.getTypeSizeInBits(V
->getType()))
31 if (CastInst
*CI
= dyn_cast
<CastInst
>(V
))
32 if ((CI
->getOpcode() == Instruction::PtrToInt
||
33 CI
->getOpcode() == Instruction::IntToPtr
) &&
34 SE
.getTypeSizeInBits(CI
->getType()) ==
35 SE
.getTypeSizeInBits(CI
->getOperand(0)->getType()))
36 return CI
->getOperand(0);
38 // FIXME: keep track of the cast instruction.
39 if (Constant
*C
= dyn_cast
<Constant
>(V
))
40 return ConstantExpr::getCast(opcode
, C
, Ty
);
42 if (Argument
*A
= dyn_cast
<Argument
>(V
)) {
43 // Check to see if there is already a cast!
44 for (Value::use_iterator UI
= A
->use_begin(), E
= A
->use_end();
46 if ((*UI
)->getType() == Ty
)
47 if (CastInst
*CI
= dyn_cast
<CastInst
>(cast
<Instruction
>(*UI
)))
48 if (CI
->getOpcode() == opcode
) {
49 // If the cast isn't the first instruction of the function, move it.
50 if (BasicBlock::iterator(CI
) !=
51 A
->getParent()->getEntryBlock().begin()) {
52 // If the CastInst is the insert point, change the insert point.
53 if (CI
== InsertPt
) ++InsertPt
;
54 // Splice the cast at the beginning of the entry block.
55 CI
->moveBefore(A
->getParent()->getEntryBlock().begin());
60 return CastInst::Create(opcode
, V
, Ty
, V
->getName(),
61 A
->getParent()->getEntryBlock().begin());
64 Instruction
*I
= cast
<Instruction
>(V
);
66 // Check to see if there is already a cast. If there is, use it.
67 for (Value::use_iterator UI
= I
->use_begin(), E
= I
->use_end();
69 if ((*UI
)->getType() == Ty
)
70 if (CastInst
*CI
= dyn_cast
<CastInst
>(cast
<Instruction
>(*UI
)))
71 if (CI
->getOpcode() == opcode
) {
72 BasicBlock::iterator It
= I
; ++It
;
73 if (isa
<InvokeInst
>(I
))
74 It
= cast
<InvokeInst
>(I
)->getNormalDest()->begin();
75 while (isa
<PHINode
>(It
)) ++It
;
76 if (It
!= BasicBlock::iterator(CI
)) {
77 // If the CastInst is the insert point, change the insert point.
78 if (CI
== InsertPt
) ++InsertPt
;
79 // Splice the cast immediately after the operand in question.
85 BasicBlock::iterator IP
= I
; ++IP
;
86 if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(I
))
87 IP
= II
->getNormalDest()->begin();
88 while (isa
<PHINode
>(IP
)) ++IP
;
89 return CastInst::Create(opcode
, V
, Ty
, V
->getName(), IP
);
92 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
93 /// which must be possible with a noop cast.
94 Value
*SCEVExpander::InsertNoopCastOfTo(Value
*V
, const Type
*Ty
) {
95 Instruction::CastOps Op
= CastInst::getCastOpcode(V
, false, Ty
, false);
96 assert((Op
== Instruction::BitCast
||
97 Op
== Instruction::PtrToInt
||
98 Op
== Instruction::IntToPtr
) &&
99 "InsertNoopCastOfTo cannot perform non-noop casts!");
100 assert(SE
.getTypeSizeInBits(V
->getType()) == SE
.getTypeSizeInBits(Ty
) &&
101 "InsertNoopCastOfTo cannot change sizes!");
102 return InsertCastOfTo(Op
, V
, Ty
);
105 /// InsertBinop - Insert the specified binary operator, doing a small amount
106 /// of work to avoid inserting an obviously redundant operation.
107 Value
*SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode
, Value
*LHS
,
108 Value
*RHS
, BasicBlock::iterator InsertPt
) {
109 // Fold a binop with constant operands.
110 if (Constant
*CLHS
= dyn_cast
<Constant
>(LHS
))
111 if (Constant
*CRHS
= dyn_cast
<Constant
>(RHS
))
112 return ConstantExpr::get(Opcode
, CLHS
, CRHS
);
114 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
115 unsigned ScanLimit
= 6;
116 BasicBlock::iterator BlockBegin
= InsertPt
->getParent()->begin();
117 if (InsertPt
!= BlockBegin
) {
118 // Scanning starts from the last instruction before InsertPt.
119 BasicBlock::iterator IP
= InsertPt
;
121 for (; ScanLimit
; --IP
, --ScanLimit
) {
122 if (BinaryOperator
*BinOp
= dyn_cast
<BinaryOperator
>(IP
))
123 if (BinOp
->getOpcode() == Opcode
&& BinOp
->getOperand(0) == LHS
&&
124 BinOp
->getOperand(1) == RHS
)
126 if (IP
== BlockBegin
) break;
130 // If we haven't found this binop, insert it.
131 return BinaryOperator::Create(Opcode
, LHS
, RHS
, "tmp", InsertPt
);
134 Value
*SCEVExpander::visitAddExpr(const SCEVAddExpr
*S
) {
135 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
136 Value
*V
= expand(S
->getOperand(S
->getNumOperands()-1));
137 V
= InsertNoopCastOfTo(V
, Ty
);
139 // Emit a bunch of add instructions
140 for (int i
= S
->getNumOperands()-2; i
>= 0; --i
) {
141 Value
*W
= expand(S
->getOperand(i
));
142 W
= InsertNoopCastOfTo(W
, Ty
);
143 V
= InsertBinop(Instruction::Add
, V
, W
, InsertPt
);
148 Value
*SCEVExpander::visitMulExpr(const SCEVMulExpr
*S
) {
149 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
150 int FirstOp
= 0; // Set if we should emit a subtract.
151 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(S
->getOperand(0)))
152 if (SC
->getValue()->isAllOnesValue())
155 int i
= S
->getNumOperands()-2;
156 Value
*V
= expand(S
->getOperand(i
+1));
157 V
= InsertNoopCastOfTo(V
, Ty
);
159 // Emit a bunch of multiply instructions
160 for (; i
>= FirstOp
; --i
) {
161 Value
*W
= expand(S
->getOperand(i
));
162 W
= InsertNoopCastOfTo(W
, Ty
);
163 V
= InsertBinop(Instruction::Mul
, V
, W
, InsertPt
);
166 // -1 * ... ---> 0 - ...
168 V
= InsertBinop(Instruction::Sub
, Constant::getNullValue(Ty
), V
, InsertPt
);
172 Value
*SCEVExpander::visitUDivExpr(const SCEVUDivExpr
*S
) {
173 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
175 Value
*LHS
= expand(S
->getLHS());
176 LHS
= InsertNoopCastOfTo(LHS
, Ty
);
177 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(S
->getRHS())) {
178 const APInt
&RHS
= SC
->getValue()->getValue();
179 if (RHS
.isPowerOf2())
180 return InsertBinop(Instruction::LShr
, LHS
,
181 ConstantInt::get(Ty
, RHS
.logBase2()),
185 Value
*RHS
= expand(S
->getRHS());
186 RHS
= InsertNoopCastOfTo(RHS
, Ty
);
187 return InsertBinop(Instruction::UDiv
, LHS
, RHS
, InsertPt
);
190 Value
*SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr
*S
) {
191 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
192 const Loop
*L
= S
->getLoop();
194 // {X,+,F} --> X + {0,+,F}
195 if (!S
->getStart()->isZero()) {
196 Value
*Start
= expand(S
->getStart());
197 Start
= InsertNoopCastOfTo(Start
, Ty
);
198 std::vector
<SCEVHandle
> NewOps(S
->op_begin(), S
->op_end());
199 NewOps
[0] = SE
.getIntegerSCEV(0, Ty
);
200 Value
*Rest
= expand(SE
.getAddRecExpr(NewOps
, L
));
201 Rest
= InsertNoopCastOfTo(Rest
, Ty
);
203 // FIXME: look for an existing add to use.
204 return InsertBinop(Instruction::Add
, Rest
, Start
, InsertPt
);
207 // {0,+,1} --> Insert a canonical induction variable into the loop!
209 S
->getOperand(1) == SE
.getIntegerSCEV(1, Ty
)) {
210 // Create and insert the PHI node for the induction variable in the
212 BasicBlock
*Header
= L
->getHeader();
213 PHINode
*PN
= PHINode::Create(Ty
, "indvar", Header
->begin());
214 PN
->addIncoming(Constant::getNullValue(Ty
), L
->getLoopPreheader());
216 pred_iterator HPI
= pred_begin(Header
);
217 assert(HPI
!= pred_end(Header
) && "Loop with zero preds???");
218 if (!L
->contains(*HPI
)) ++HPI
;
219 assert(HPI
!= pred_end(Header
) && L
->contains(*HPI
) &&
220 "No backedge in loop?");
222 // Insert a unit add instruction right before the terminator corresponding
224 Constant
*One
= ConstantInt::get(Ty
, 1);
225 Instruction
*Add
= BinaryOperator::CreateAdd(PN
, One
, "indvar.next",
226 (*HPI
)->getTerminator());
228 pred_iterator PI
= pred_begin(Header
);
229 if (*PI
== L
->getLoopPreheader())
231 PN
->addIncoming(Add
, *PI
);
235 // Get the canonical induction variable I for this loop.
236 Value
*I
= getOrInsertCanonicalInductionVariable(L
, Ty
);
238 // If this is a simple linear addrec, emit it now as a special case.
239 if (S
->isAffine()) { // {0,+,F} --> i*F
240 Value
*F
= expand(S
->getOperand(1));
241 F
= InsertNoopCastOfTo(F
, Ty
);
243 // IF the step is by one, just return the inserted IV.
244 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(F
))
245 if (CI
->getValue() == 1)
248 // If the insert point is directly inside of the loop, emit the multiply at
249 // the insert point. Otherwise, L is a loop that is a parent of the insert
250 // point loop. If we can, move the multiply to the outer most loop that it
252 BasicBlock::iterator MulInsertPt
= getInsertionPoint();
253 Loop
*InsertPtLoop
= LI
.getLoopFor(MulInsertPt
->getParent());
254 if (InsertPtLoop
!= L
&& InsertPtLoop
&&
255 L
->contains(InsertPtLoop
->getHeader())) {
257 // If we cannot hoist the multiply out of this loop, don't.
258 if (!InsertPtLoop
->isLoopInvariant(F
)) break;
260 BasicBlock
*InsertPtLoopPH
= InsertPtLoop
->getLoopPreheader();
262 // If this loop hasn't got a preheader, we aren't able to hoist the
267 // Otherwise, move the insert point to the preheader.
268 MulInsertPt
= InsertPtLoopPH
->getTerminator();
269 InsertPtLoop
= InsertPtLoop
->getParentLoop();
270 } while (InsertPtLoop
!= L
);
273 return InsertBinop(Instruction::Mul
, I
, F
, MulInsertPt
);
276 // If this is a chain of recurrences, turn it into a closed form, using the
277 // folders, then expandCodeFor the closed form. This allows the folders to
278 // simplify the expression without having to build a bunch of special code
280 SCEVHandle IH
= SE
.getUnknown(I
); // Get I as a "symbolic" SCEV.
282 SCEVHandle V
= S
->evaluateAtIteration(IH
, SE
);
283 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
288 Value
*SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr
*S
) {
289 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
290 Value
*V
= expand(S
->getOperand());
291 V
= InsertNoopCastOfTo(V
, SE
.getEffectiveSCEVType(V
->getType()));
292 return new TruncInst(V
, Ty
, "tmp.", InsertPt
);
295 Value
*SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr
*S
) {
296 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
297 Value
*V
= expand(S
->getOperand());
298 V
= InsertNoopCastOfTo(V
, SE
.getEffectiveSCEVType(V
->getType()));
299 return new ZExtInst(V
, Ty
, "tmp.", InsertPt
);
302 Value
*SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr
*S
) {
303 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
304 Value
*V
= expand(S
->getOperand());
305 V
= InsertNoopCastOfTo(V
, SE
.getEffectiveSCEVType(V
->getType()));
306 return new SExtInst(V
, Ty
, "tmp.", InsertPt
);
309 Value
*SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr
*S
) {
310 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
311 Value
*LHS
= expand(S
->getOperand(0));
312 LHS
= InsertNoopCastOfTo(LHS
, Ty
);
313 for (unsigned i
= 1; i
< S
->getNumOperands(); ++i
) {
314 Value
*RHS
= expand(S
->getOperand(i
));
315 RHS
= InsertNoopCastOfTo(RHS
, Ty
);
316 Value
*ICmp
= new ICmpInst(ICmpInst::ICMP_SGT
, LHS
, RHS
, "tmp", InsertPt
);
317 LHS
= SelectInst::Create(ICmp
, LHS
, RHS
, "smax", InsertPt
);
322 Value
*SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr
*S
) {
323 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
324 Value
*LHS
= expand(S
->getOperand(0));
325 LHS
= InsertNoopCastOfTo(LHS
, Ty
);
326 for (unsigned i
= 1; i
< S
->getNumOperands(); ++i
) {
327 Value
*RHS
= expand(S
->getOperand(i
));
328 RHS
= InsertNoopCastOfTo(RHS
, Ty
);
329 Value
*ICmp
= new ICmpInst(ICmpInst::ICMP_UGT
, LHS
, RHS
, "tmp", InsertPt
);
330 LHS
= SelectInst::Create(ICmp
, LHS
, RHS
, "umax", InsertPt
);
335 Value
*SCEVExpander::expandCodeFor(SCEVHandle SH
, const Type
*Ty
) {
336 // Expand the code for this SCEV.
337 assert(SE
.getTypeSizeInBits(Ty
) == SE
.getTypeSizeInBits(SH
->getType()) &&
338 "non-trivial casts should be done with the SCEVs directly!");
339 Value
*V
= expand(SH
);
340 return InsertNoopCastOfTo(V
, Ty
);
343 Value
*SCEVExpander::expand(const SCEV
*S
) {
344 // Check to see if we already expanded this.
345 std::map
<SCEVHandle
, Value
*>::iterator I
= InsertedExpressions
.find(S
);
346 if (I
!= InsertedExpressions
.end())
350 InsertedExpressions
[S
] = V
;