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"
18 #include "llvm/Target/TargetData.h"
21 /// InsertCastOfTo - Insert a cast of V to the specified type, doing what
22 /// we can to share the casts.
23 Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V,
25 // Short-circuit unnecessary bitcasts.
26 if (opcode == Instruction::BitCast && V->getType() == Ty)
29 // FIXME: keep track of the cast instruction.
30 if (Constant *C = dyn_cast<Constant>(V))
31 return ConstantExpr::getCast(opcode, C, Ty);
33 if (Argument *A = dyn_cast<Argument>(V)) {
34 // Check to see if there is already a cast!
35 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
37 if ((*UI)->getType() == Ty)
38 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
39 if (CI->getOpcode() == opcode) {
40 // If the cast isn't the first instruction of the function, move it.
41 if (BasicBlock::iterator(CI) !=
42 A->getParent()->getEntryBlock().begin()) {
43 CI->moveBefore(A->getParent()->getEntryBlock().begin());
48 return CastInst::Create(opcode, V, Ty, V->getName(),
49 A->getParent()->getEntryBlock().begin());
52 Instruction *I = cast<Instruction>(V);
54 // Check to see if there is already a cast. If there is, use it.
55 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
57 if ((*UI)->getType() == Ty)
58 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
59 if (CI->getOpcode() == opcode) {
60 BasicBlock::iterator It = I; ++It;
61 if (isa<InvokeInst>(I))
62 It = cast<InvokeInst>(I)->getNormalDest()->begin();
63 while (isa<PHINode>(It)) ++It;
64 if (It != BasicBlock::iterator(CI)) {
65 // Splice the cast immediately after the operand in question.
71 BasicBlock::iterator IP = I; ++IP;
72 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
73 IP = II->getNormalDest()->begin();
74 while (isa<PHINode>(IP)) ++IP;
75 return CastInst::Create(opcode, V, Ty, V->getName(), IP);
78 /// InsertBinop - Insert the specified binary operator, doing a small amount
79 /// of work to avoid inserting an obviously redundant operation.
80 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
81 Value *RHS, Instruction *InsertPt) {
82 // Fold a binop with constant operands.
83 if (Constant *CLHS = dyn_cast<Constant>(LHS))
84 if (Constant *CRHS = dyn_cast<Constant>(RHS))
85 return ConstantExpr::get(Opcode, CLHS, CRHS);
87 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
88 unsigned ScanLimit = 6;
89 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
90 if (InsertPt != BlockBegin) {
91 // Scanning starts from the last instruction before InsertPt.
92 BasicBlock::iterator IP = InsertPt;
94 for (; ScanLimit; --IP, --ScanLimit) {
95 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(IP))
96 if (BinOp->getOpcode() == Opcode && BinOp->getOperand(0) == LHS &&
97 BinOp->getOperand(1) == RHS)
99 if (IP == BlockBegin) break;
103 // If we haven't found this binop, insert it.
104 return BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
107 Value *SCEVExpander::visitAddExpr(SCEVAddExpr *S) {
108 const Type *Ty = S->getType();
109 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
110 Value *V = expand(S->getOperand(S->getNumOperands()-1));
111 V = InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
113 // Emit a bunch of add instructions
114 for (int i = S->getNumOperands()-2; i >= 0; --i) {
115 Value *W = expand(S->getOperand(i));
116 W = InsertCastOfTo(CastInst::getCastOpcode(W, false, Ty, false), W, Ty);
117 V = InsertBinop(Instruction::Add, V, W, InsertPt);
122 Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
123 const Type *Ty = S->getType();
124 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
125 int FirstOp = 0; // Set if we should emit a subtract.
126 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
127 if (SC->getValue()->isAllOnesValue())
130 int i = S->getNumOperands()-2;
131 Value *V = expand(S->getOperand(i+1));
132 V = InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
134 // Emit a bunch of multiply instructions
135 for (; i >= FirstOp; --i) {
136 Value *W = expand(S->getOperand(i));
137 W = InsertCastOfTo(CastInst::getCastOpcode(W, false, Ty, false), W, Ty);
138 V = InsertBinop(Instruction::Mul, V, W, InsertPt);
141 // -1 * ... ---> 0 - ...
143 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
147 Value *SCEVExpander::visitUDivExpr(SCEVUDivExpr *S) {
148 const Type *Ty = S->getType();
149 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
151 Value *LHS = expand(S->getLHS());
152 LHS = InsertCastOfTo(CastInst::getCastOpcode(LHS, false, Ty, false), LHS, Ty);
153 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
154 const APInt &RHS = SC->getValue()->getValue();
155 if (RHS.isPowerOf2())
156 return InsertBinop(Instruction::LShr, LHS,
157 ConstantInt::get(Ty, RHS.logBase2()),
161 Value *RHS = expand(S->getRHS());
162 RHS = InsertCastOfTo(CastInst::getCastOpcode(RHS, false, Ty, false), RHS, Ty);
163 return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
166 Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
167 const Type *Ty = S->getType();
168 const Loop *L = S->getLoop();
169 // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
170 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
171 "Cannot expand fp recurrences yet!");
173 // {X,+,F} --> X + {0,+,F}
174 if (!S->getStart()->isZero()) {
175 Value *Start = expand(S->getStart());
176 if (isa<PointerType>(Start->getType()))
177 Start = InsertCastOfTo(Instruction::PtrToInt, Start, TD.getIntPtrType());
178 std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
179 NewOps[0] = SE.getIntegerSCEV(0, Ty);
180 Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
181 if (isa<PointerType>(Rest->getType()))
182 Rest = InsertCastOfTo(Instruction::PtrToInt, Rest, TD.getIntPtrType());
184 // FIXME: look for an existing add to use.
185 return InsertBinop(Instruction::Add, Rest, Start, InsertPt);
188 // {0,+,1} --> Insert a canonical induction variable into the loop!
190 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
191 // Create and insert the PHI node for the induction variable in the
193 BasicBlock *Header = L->getHeader();
194 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
195 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
197 pred_iterator HPI = pred_begin(Header);
198 assert(HPI != pred_end(Header) && "Loop with zero preds???");
199 if (!L->contains(*HPI)) ++HPI;
200 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
201 "No backedge in loop?");
203 // Insert a unit add instruction right before the terminator corresponding
205 Constant *One = ConstantInt::get(Ty, 1);
206 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
207 (*HPI)->getTerminator());
209 pred_iterator PI = pred_begin(Header);
210 if (*PI == L->getLoopPreheader())
212 PN->addIncoming(Add, *PI);
216 // Get the canonical induction variable I for this loop.
217 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
219 // If this is a simple linear addrec, emit it now as a special case.
220 if (S->isAffine()) { // {0,+,F} --> i*F
221 Value *F = expand(S->getOperand(1));
223 // IF the step is by one, just return the inserted IV.
224 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
225 if (CI->getValue() == 1)
228 // If the insert point is directly inside of the loop, emit the multiply at
229 // the insert point. Otherwise, L is a loop that is a parent of the insert
230 // point loop. If we can, move the multiply to the outer most loop that it
232 Instruction *MulInsertPt = InsertPt;
233 Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
234 if (InsertPtLoop != L && InsertPtLoop &&
235 L->contains(InsertPtLoop->getHeader())) {
237 // If we cannot hoist the multiply out of this loop, don't.
238 if (!InsertPtLoop->isLoopInvariant(F)) break;
240 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
242 // If this loop hasn't got a preheader, we aren't able to hoist the
247 // Otherwise, move the insert point to the preheader.
248 MulInsertPt = InsertPtLoopPH->getTerminator();
249 InsertPtLoop = InsertPtLoop->getParentLoop();
250 } while (InsertPtLoop != L);
253 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
256 // If this is a chain of recurrences, turn it into a closed form, using the
257 // folders, then expandCodeFor the closed form. This allows the folders to
258 // simplify the expression without having to build a bunch of special code
260 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
262 SCEVHandle V = S->evaluateAtIteration(IH, SE);
263 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
268 Value *SCEVExpander::visitTruncateExpr(SCEVTruncateExpr *S) {
269 Value *V = expand(S->getOperand());
270 if (isa<PointerType>(V->getType()))
271 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
272 return CastInst::CreateTruncOrBitCast(V, S->getType(), "tmp.", InsertPt);
275 Value *SCEVExpander::visitZeroExtendExpr(SCEVZeroExtendExpr *S) {
276 Value *V = expand(S->getOperand());
277 if (isa<PointerType>(V->getType()))
278 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
279 return CastInst::CreateZExtOrBitCast(V, S->getType(), "tmp.", InsertPt);
282 Value *SCEVExpander::visitSignExtendExpr(SCEVSignExtendExpr *S) {
283 Value *V = expand(S->getOperand());
284 if (isa<PointerType>(V->getType()))
285 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
286 return CastInst::CreateSExtOrBitCast(V, S->getType(), "tmp.", InsertPt);
289 Value *SCEVExpander::visitSMaxExpr(SCEVSMaxExpr *S) {
290 Value *LHS = expand(S->getOperand(0));
291 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
292 Value *RHS = expand(S->getOperand(i));
293 Value *ICmp = new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
294 LHS = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
299 Value *SCEVExpander::visitUMaxExpr(SCEVUMaxExpr *S) {
300 Value *LHS = expand(S->getOperand(0));
301 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
302 Value *RHS = expand(S->getOperand(i));
303 Value *ICmp = new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
304 LHS = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
309 Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty,
311 // Expand the code for this SCEV.
312 assert(TD.getTypeSizeInBits(Ty) == TD.getTypeSizeInBits(SH->getType()) &&
313 "non-trivial casts should be done with the SCEVs directly!");
315 Value *V = expand(SH);
316 return InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
319 Value *SCEVExpander::expand(SCEV *S) {
320 // Check to see if we already expanded this.
321 std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
322 if (I != InsertedExpressions.end())
326 InsertedExpressions[S] = V;