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 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
30 if ((opcode == Instruction::PtrToInt || opcode == Instruction::IntToPtr) &&
31 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
32 if (CastInst *CI = dyn_cast<CastInst>(V))
33 if ((CI->getOpcode() == Instruction::PtrToInt ||
34 CI->getOpcode() == Instruction::IntToPtr) &&
35 SE.getTypeSizeInBits(CI->getType()) ==
36 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
37 return CI->getOperand(0);
38 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
39 if ((CE->getOpcode() == Instruction::PtrToInt ||
40 CE->getOpcode() == Instruction::IntToPtr) &&
41 SE.getTypeSizeInBits(CE->getType()) ==
42 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
43 return CE->getOperand(0);
46 // FIXME: keep track of the cast instruction.
47 if (Constant *C = dyn_cast<Constant>(V))
48 return ConstantExpr::getCast(opcode, C, Ty);
50 if (Argument *A = dyn_cast<Argument>(V)) {
51 // Check to see if there is already a cast!
52 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
54 if ((*UI)->getType() == Ty)
55 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
56 if (CI->getOpcode() == opcode) {
57 // If the cast isn't the first instruction of the function, move it.
58 if (BasicBlock::iterator(CI) !=
59 A->getParent()->getEntryBlock().begin()) {
60 // If the CastInst is the insert point, change the insert point.
61 if (CI == InsertPt) ++InsertPt;
62 // Splice the cast at the beginning of the entry block.
63 CI->moveBefore(A->getParent()->getEntryBlock().begin());
68 Instruction *I = CastInst::Create(opcode, V, Ty, V->getName(),
69 A->getParent()->getEntryBlock().begin());
70 InsertedValues.insert(I);
74 Instruction *I = cast<Instruction>(V);
76 // Check to see if there is already a cast. If there is, use it.
77 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
79 if ((*UI)->getType() == Ty)
80 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
81 if (CI->getOpcode() == opcode) {
82 BasicBlock::iterator It = I; ++It;
83 if (isa<InvokeInst>(I))
84 It = cast<InvokeInst>(I)->getNormalDest()->begin();
85 while (isa<PHINode>(It)) ++It;
86 if (It != BasicBlock::iterator(CI)) {
87 // If the CastInst is the insert point, change the insert point.
88 if (CI == InsertPt) ++InsertPt;
89 // Splice the cast immediately after the operand in question.
95 BasicBlock::iterator IP = I; ++IP;
96 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
97 IP = II->getNormalDest()->begin();
98 while (isa<PHINode>(IP)) ++IP;
99 Instruction *CI = CastInst::Create(opcode, V, Ty, V->getName(), IP);
100 InsertedValues.insert(CI);
104 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
105 /// which must be possible with a noop cast.
106 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
107 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
108 assert((Op == Instruction::BitCast ||
109 Op == Instruction::PtrToInt ||
110 Op == Instruction::IntToPtr) &&
111 "InsertNoopCastOfTo cannot perform non-noop casts!");
112 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
113 "InsertNoopCastOfTo cannot change sizes!");
114 return InsertCastOfTo(Op, V, Ty);
117 /// InsertBinop - Insert the specified binary operator, doing a small amount
118 /// of work to avoid inserting an obviously redundant operation.
119 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
120 Value *RHS, BasicBlock::iterator InsertPt) {
121 // Fold a binop with constant operands.
122 if (Constant *CLHS = dyn_cast<Constant>(LHS))
123 if (Constant *CRHS = dyn_cast<Constant>(RHS))
124 return ConstantExpr::get(Opcode, CLHS, CRHS);
126 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
127 unsigned ScanLimit = 6;
128 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
129 if (InsertPt != BlockBegin) {
130 // Scanning starts from the last instruction before InsertPt.
131 BasicBlock::iterator IP = InsertPt;
133 for (; ScanLimit; --IP, --ScanLimit) {
134 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
135 IP->getOperand(1) == RHS)
137 if (IP == BlockBegin) break;
141 // If we haven't found this binop, insert it.
142 Instruction *BO = BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
143 InsertedValues.insert(BO);
147 /// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
148 /// instead of using ptrtoint+arithmetic+inttoptr.
149 Value *SCEVExpander::expandAddToGEP(const SCEVAddExpr *S,
150 const PointerType *PTy,
153 const Type *ElTy = PTy->getElementType();
154 SmallVector<Value *, 4> GepIndices;
155 std::vector<SCEVHandle> Ops = S->getOperands();
156 bool AnyNonZeroIndices = false;
159 // Decend down the pointer's type and attempt to convert the other
160 // operands into GEP indices, at each level. The first index in a GEP
161 // indexes into the array implied by the pointer operand; the rest of
162 // the indices index into the element or field type selected by the
165 APInt ElSize = APInt(SE.getTypeSizeInBits(Ty),
166 ElTy->isSized() ? SE.TD->getTypeAllocSize(ElTy) : 0);
167 std::vector<SCEVHandle> NewOps;
168 std::vector<SCEVHandle> ScaledOps;
169 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
171 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i]))
172 if (!C->getValue()->getValue().srem(ElSize)) {
174 ConstantInt::get(C->getValue()->getValue().sdiv(ElSize));
175 SCEVHandle Div = SE.getConstant(CI);
176 ScaledOps.push_back(Div);
179 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i]))
180 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
181 if (C->getValue()->getValue() == ElSize) {
182 for (unsigned j = 1, f = M->getNumOperands(); j != f; ++j)
183 ScaledOps.push_back(M->getOperand(j));
186 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i]))
187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getValue()))
188 if (BO->getOpcode() == Instruction::Mul)
189 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
190 if (CI->getValue() == ElSize) {
191 ScaledOps.push_back(SE.getUnknown(BO->getOperand(0)));
195 ScaledOps.push_back(Ops[i]);
199 NewOps.push_back(Ops[i]);
202 AnyNonZeroIndices |= !ScaledOps.empty();
203 Value *Scaled = ScaledOps.empty() ?
204 Constant::getNullValue(Ty) :
205 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
206 GepIndices.push_back(Scaled);
208 // Collect struct field index operands.
210 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
211 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
212 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
213 const StructLayout &SL = *SE.TD->getStructLayout(STy);
214 uint64_t FullOffset = C->getValue()->getZExtValue();
215 if (FullOffset < SL.getSizeInBytes()) {
216 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
217 GepIndices.push_back(ConstantInt::get(Type::Int32Ty, ElIdx));
218 ElTy = STy->getTypeAtIndex(ElIdx);
220 SE.getConstant(ConstantInt::get(Ty,
222 SL.getElementOffset(ElIdx)));
223 AnyNonZeroIndices = true;
230 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
231 ElTy = ATy->getElementType();
237 // If none of the operands were convertable to proper GEP indices, cast
238 // the base to i8* and do an ugly getelementptr with that. It's still
239 // better than ptrtoint+arithmetic+inttoptr at least.
240 if (!AnyNonZeroIndices) {
241 V = InsertNoopCastOfTo(V,
242 Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
243 Value *Idx = expand(SE.getAddExpr(Ops));
244 Idx = InsertNoopCastOfTo(Idx, Ty);
246 // Fold a GEP with constant operands.
247 if (Constant *CLHS = dyn_cast<Constant>(V))
248 if (Constant *CRHS = dyn_cast<Constant>(Idx))
249 return ConstantExpr::get(Instruction::GetElementPtr, CLHS, CRHS);
251 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
252 unsigned ScanLimit = 6;
253 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
254 if (InsertPt != BlockBegin) {
255 // Scanning starts from the last instruction before InsertPt.
256 BasicBlock::iterator IP = InsertPt;
258 for (; ScanLimit; --IP, --ScanLimit) {
259 if (IP->getOpcode() == Instruction::GetElementPtr &&
260 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
262 if (IP == BlockBegin) break;
266 Value *GEP = GetElementPtrInst::Create(V, Idx, "scevgep", InsertPt);
267 InsertedValues.insert(GEP);
271 // Insert a pretty getelementptr.
272 Value *GEP = GetElementPtrInst::Create(V,
275 "scevgep", InsertPt);
276 Ops.push_back(SE.getUnknown(GEP));
277 InsertedValues.insert(GEP);
278 return expand(SE.getAddExpr(Ops));
281 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
282 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
283 Value *V = expand(S->getOperand(S->getNumOperands()-1));
285 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. This helps
286 // BasicAliasAnalysis analyze the result. However, it suffers from the
287 // underlying bug described in PR2831. Addition in LLVM currently always
288 // has two's complement wrapping guaranteed. However, the semantics for
289 // getelementptr overflow are ambiguous. In the common case though, this
290 // expansion gets used when a GEP in the original code has been converted
291 // into integer arithmetic, in which case the resulting code will be no
292 // more undefined than it was originally.
294 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
295 return expandAddToGEP(S, PTy, Ty, V);
297 V = InsertNoopCastOfTo(V, Ty);
299 // Emit a bunch of add instructions
300 for (int i = S->getNumOperands()-2; i >= 0; --i) {
301 Value *W = expand(S->getOperand(i));
302 W = InsertNoopCastOfTo(W, Ty);
303 V = InsertBinop(Instruction::Add, V, W, InsertPt);
308 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
309 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
310 int FirstOp = 0; // Set if we should emit a subtract.
311 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
312 if (SC->getValue()->isAllOnesValue())
315 int i = S->getNumOperands()-2;
316 Value *V = expand(S->getOperand(i+1));
317 V = InsertNoopCastOfTo(V, Ty);
319 // Emit a bunch of multiply instructions
320 for (; i >= FirstOp; --i) {
321 Value *W = expand(S->getOperand(i));
322 W = InsertNoopCastOfTo(W, Ty);
323 V = InsertBinop(Instruction::Mul, V, W, InsertPt);
326 // -1 * ... ---> 0 - ...
328 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
332 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
333 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
335 Value *LHS = expand(S->getLHS());
336 LHS = InsertNoopCastOfTo(LHS, Ty);
337 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
338 const APInt &RHS = SC->getValue()->getValue();
339 if (RHS.isPowerOf2())
340 return InsertBinop(Instruction::LShr, LHS,
341 ConstantInt::get(Ty, RHS.logBase2()),
345 Value *RHS = expand(S->getRHS());
346 RHS = InsertNoopCastOfTo(RHS, Ty);
347 return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
350 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
351 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
352 const Loop *L = S->getLoop();
354 // {X,+,F} --> X + {0,+,F}
355 if (!S->getStart()->isZero()) {
356 std::vector<SCEVHandle> NewOps(S->getOperands());
357 NewOps[0] = SE.getIntegerSCEV(0, Ty);
358 Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
359 return expand(SE.getAddExpr(S->getStart(), SE.getUnknown(Rest)));
362 // {0,+,1} --> Insert a canonical induction variable into the loop!
364 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
365 // Create and insert the PHI node for the induction variable in the
367 BasicBlock *Header = L->getHeader();
368 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
369 InsertedValues.insert(PN);
370 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
372 pred_iterator HPI = pred_begin(Header);
373 assert(HPI != pred_end(Header) && "Loop with zero preds???");
374 if (!L->contains(*HPI)) ++HPI;
375 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
376 "No backedge in loop?");
378 // Insert a unit add instruction right before the terminator corresponding
380 Constant *One = ConstantInt::get(Ty, 1);
381 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
382 (*HPI)->getTerminator());
383 InsertedValues.insert(Add);
385 pred_iterator PI = pred_begin(Header);
386 if (*PI == L->getLoopPreheader())
388 PN->addIncoming(Add, *PI);
392 // Get the canonical induction variable I for this loop.
393 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
395 // If this is a simple linear addrec, emit it now as a special case.
396 if (S->isAffine()) { // {0,+,F} --> i*F
397 Value *F = expand(S->getOperand(1));
398 F = InsertNoopCastOfTo(F, Ty);
400 // IF the step is by one, just return the inserted IV.
401 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
402 if (CI->getValue() == 1)
405 // If the insert point is directly inside of the loop, emit the multiply at
406 // the insert point. Otherwise, L is a loop that is a parent of the insert
407 // point loop. If we can, move the multiply to the outer most loop that it
409 BasicBlock::iterator MulInsertPt = getInsertionPoint();
410 Loop *InsertPtLoop = SE.LI->getLoopFor(MulInsertPt->getParent());
411 if (InsertPtLoop != L && InsertPtLoop &&
412 L->contains(InsertPtLoop->getHeader())) {
414 // If we cannot hoist the multiply out of this loop, don't.
415 if (!InsertPtLoop->isLoopInvariant(F)) break;
417 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
419 // If this loop hasn't got a preheader, we aren't able to hoist the
424 // Otherwise, move the insert point to the preheader.
425 MulInsertPt = InsertPtLoopPH->getTerminator();
426 InsertPtLoop = InsertPtLoop->getParentLoop();
427 } while (InsertPtLoop != L);
430 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
433 // If this is a chain of recurrences, turn it into a closed form, using the
434 // folders, then expandCodeFor the closed form. This allows the folders to
435 // simplify the expression without having to build a bunch of special code
437 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
439 SCEVHandle V = S->evaluateAtIteration(IH, SE);
440 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
445 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
446 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
447 Value *V = expand(S->getOperand());
448 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
449 Instruction *I = new TruncInst(V, Ty, "tmp.", InsertPt);
450 InsertedValues.insert(I);
454 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
455 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
456 Value *V = expand(S->getOperand());
457 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
458 Instruction *I = new ZExtInst(V, Ty, "tmp.", InsertPt);
459 InsertedValues.insert(I);
463 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
464 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
465 Value *V = expand(S->getOperand());
466 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
467 Instruction *I = new SExtInst(V, Ty, "tmp.", InsertPt);
468 InsertedValues.insert(I);
472 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
473 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
474 Value *LHS = expand(S->getOperand(0));
475 LHS = InsertNoopCastOfTo(LHS, Ty);
476 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
477 Value *RHS = expand(S->getOperand(i));
478 RHS = InsertNoopCastOfTo(RHS, Ty);
480 new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
481 InsertedValues.insert(ICmp);
482 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
483 InsertedValues.insert(Sel);
489 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
490 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
491 Value *LHS = expand(S->getOperand(0));
492 LHS = InsertNoopCastOfTo(LHS, Ty);
493 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
494 Value *RHS = expand(S->getOperand(i));
495 RHS = InsertNoopCastOfTo(RHS, Ty);
497 new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
498 InsertedValues.insert(ICmp);
499 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
500 InsertedValues.insert(Sel);
506 Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty) {
507 // Expand the code for this SCEV.
508 Value *V = expand(SH);
510 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
511 "non-trivial casts should be done with the SCEVs directly!");
512 V = InsertNoopCastOfTo(V, Ty);
517 Value *SCEVExpander::expand(const SCEV *S) {
518 // Check to see if we already expanded this.
519 std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
520 if (I != InsertedExpressions.end())
524 InsertedExpressions[S] = V;