1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
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 transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into simpler forms suitable for subsequent
12 // analysis and transformation.
14 // This transformation makes the following changes to each loop with an
15 // identifiable induction variable:
16 // 1. All loops are transformed to have a SINGLE canonical induction variable
17 // which starts at zero and steps by one.
18 // 2. The canonical induction variable is guaranteed to be the first PHI node
19 // in the loop header block.
20 // 3. The canonical induction variable is guaranteed to be in a wide enough
21 // type so that IV expressions need not be (directly) zero-extended or
23 // 4. Any pointer arithmetic recurrences are raised to use array subscripts.
25 // If the trip count of a loop is computable, this pass also makes the following
27 // 1. The exit condition for the loop is canonicalized to compare the
28 // induction value against the exit value. This turns loops like:
29 // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30 // 2. Any use outside of the loop of an expression derived from the indvar
31 // is changed to compute the derived value outside of the loop, eliminating
32 // the dependence on the exit value of the induction variable. If the only
33 // purpose of the loop is to compute the exit value of some derived
34 // expression, this transformation will make the loop dead.
36 // This transformation should be followed by strength reduction after all of the
37 // desired loop transformations have been performed.
39 //===----------------------------------------------------------------------===//
41 #define DEBUG_TYPE "indvars"
42 #include "llvm/Transforms/Scalar.h"
43 #include "llvm/BasicBlock.h"
44 #include "llvm/Constants.h"
45 #include "llvm/Instructions.h"
46 #include "llvm/Type.h"
47 #include "llvm/Analysis/Dominators.h"
48 #include "llvm/Analysis/IVUsers.h"
49 #include "llvm/Analysis/ScalarEvolutionExpander.h"
50 #include "llvm/Analysis/LoopInfo.h"
51 #include "llvm/Analysis/LoopPass.h"
52 #include "llvm/Support/CFG.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
57 #include "llvm/Support/CommandLine.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/Statistic.h"
60 #include "llvm/ADT/STLExtras.h"
63 STATISTIC(NumRemoved , "Number of aux indvars removed");
64 STATISTIC(NumInserted, "Number of canonical indvars added");
65 STATISTIC(NumReplaced, "Number of exit values replaced");
66 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
69 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
77 static char ID; // Pass identification, replacement for typeid
78 IndVarSimplify() : LoopPass(&ID) {}
80 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
82 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83 AU.addRequired<DominatorTree>();
84 AU.addRequired<ScalarEvolution>();
85 AU.addRequiredID(LCSSAID);
86 AU.addRequiredID(LoopSimplifyID);
87 AU.addRequired<LoopInfo>();
88 AU.addRequired<IVUsers>();
89 AU.addPreserved<ScalarEvolution>();
90 AU.addPreservedID(LoopSimplifyID);
91 AU.addPreserved<IVUsers>();
92 AU.addPreservedID(LCSSAID);
98 void RewriteNonIntegerIVs(Loop *L);
100 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV* BackedgeTakenCount,
102 BasicBlock *ExitingBlock,
104 SCEVExpander &Rewriter);
105 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount,
106 SCEVExpander &Rewriter);
108 void RewriteIVExpressions(Loop *L, const Type *LargestType,
109 SCEVExpander &Rewriter);
111 void SinkUnusedInvariants(Loop *L);
113 void HandleFloatingPointIV(Loop *L, PHINode *PH);
117 char IndVarSimplify::ID = 0;
118 static RegisterPass<IndVarSimplify>
119 X("indvars", "Canonicalize Induction Variables");
121 Pass *llvm::createIndVarSimplifyPass() {
122 return new IndVarSimplify();
125 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
126 /// loop to be a canonical != comparison against the incremented loop induction
127 /// variable. This pass is able to rewrite the exit tests of any loop where the
128 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
129 /// is actually a much broader range than just linear tests.
130 ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
131 const SCEV* BackedgeTakenCount,
133 BasicBlock *ExitingBlock,
135 SCEVExpander &Rewriter) {
136 // If the exiting block is not the same as the backedge block, we must compare
137 // against the preincremented value, otherwise we prefer to compare against
138 // the post-incremented value.
140 const SCEV* RHS = BackedgeTakenCount;
141 if (ExitingBlock == L->getLoopLatch()) {
142 // Add one to the "backedge-taken" count to get the trip count.
143 // If this addition may overflow, we have to be more pessimistic and
144 // cast the induction variable before doing the add.
145 const SCEV* Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
147 SE->getAddExpr(BackedgeTakenCount,
148 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
149 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
150 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
151 // No overflow. Cast the sum.
152 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
154 // Potential overflow. Cast before doing the add.
155 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
157 RHS = SE->getAddExpr(RHS,
158 SE->getIntegerSCEV(1, IndVar->getType()));
161 // The BackedgeTaken expression contains the number of times that the
162 // backedge branches to the loop header. This is one less than the
163 // number of times the loop executes, so use the incremented indvar.
164 CmpIndVar = L->getCanonicalInductionVariableIncrement();
166 // We have to use the preincremented value...
167 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
172 // Expand the code for the iteration count.
173 assert(RHS->isLoopInvariant(L) &&
174 "Computed iteration count is not loop invariant!");
175 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
177 // Insert a new icmp_ne or icmp_eq instruction before the branch.
178 ICmpInst::Predicate Opcode;
179 if (L->contains(BI->getSuccessor(0)))
180 Opcode = ICmpInst::ICMP_NE;
182 Opcode = ICmpInst::ICMP_EQ;
184 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
185 << " LHS:" << *CmpIndVar // includes a newline
187 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
188 << " RHS:\t" << *RHS << "\n";
190 ICmpInst *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
192 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
193 // It's tempting to use replaceAllUsesWith here to fully replace the old
194 // comparison, but that's not immediately safe, since users of the old
195 // comparison may not be dominated by the new comparison. Instead, just
196 // update the branch to use the new comparison; in the common case this
197 // will make old comparison dead.
198 BI->setCondition(Cond);
199 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
206 /// RewriteLoopExitValues - Check to see if this loop has a computable
207 /// loop-invariant execution count. If so, this means that we can compute the
208 /// final value of any expressions that are recurrent in the loop, and
209 /// substitute the exit values from the loop into any instructions outside of
210 /// the loop that use the final values of the current expressions.
212 /// This is mostly redundant with the regular IndVarSimplify activities that
213 /// happen later, except that it's more powerful in some cases, because it's
214 /// able to brute-force evaluate arbitrary instructions as long as they have
215 /// constant operands at the beginning of the loop.
216 void IndVarSimplify::RewriteLoopExitValues(Loop *L,
217 const SCEV *BackedgeTakenCount,
218 SCEVExpander &Rewriter) {
219 // Verify the input to the pass in already in LCSSA form.
220 assert(L->isLCSSAForm());
222 SmallVector<BasicBlock*, 8> ExitBlocks;
223 L->getUniqueExitBlocks(ExitBlocks);
225 // Find all values that are computed inside the loop, but used outside of it.
226 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
227 // the exit blocks of the loop to find them.
228 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
229 BasicBlock *ExitBB = ExitBlocks[i];
231 // If there are no PHI nodes in this exit block, then no values defined
232 // inside the loop are used on this path, skip it.
233 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
236 unsigned NumPreds = PN->getNumIncomingValues();
238 // Iterate over all of the PHI nodes.
239 BasicBlock::iterator BBI = ExitBB->begin();
240 while ((PN = dyn_cast<PHINode>(BBI++))) {
242 continue; // dead use, don't replace it
243 // Iterate over all of the values in all the PHI nodes.
244 for (unsigned i = 0; i != NumPreds; ++i) {
245 // If the value being merged in is not integer or is not defined
246 // in the loop, skip it.
247 Value *InVal = PN->getIncomingValue(i);
248 if (!isa<Instruction>(InVal) ||
249 // SCEV only supports integer expressions for now.
250 (!isa<IntegerType>(InVal->getType()) &&
251 !isa<PointerType>(InVal->getType())))
254 // If this pred is for a subloop, not L itself, skip it.
255 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
256 continue; // The Block is in a subloop, skip it.
258 // Check that InVal is defined in the loop.
259 Instruction *Inst = cast<Instruction>(InVal);
260 if (!L->contains(Inst->getParent()))
263 // Okay, this instruction has a user outside of the current loop
264 // and varies predictably *inside* the loop. Evaluate the value it
265 // contains when the loop exits, if possible.
266 const SCEV* ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
267 if (!ExitValue->isLoopInvariant(L))
273 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
275 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
276 << " LoopVal = " << *Inst << "\n";
278 PN->setIncomingValue(i, ExitVal);
280 // If this instruction is dead now, delete it.
281 RecursivelyDeleteTriviallyDeadInstructions(Inst);
283 // If we're inserting code into the exit block rather than the
284 // preheader, we can (and have to) remove the PHI entirely.
285 // This is safe, because the NewVal won't be variant
286 // in the loop, so we don't need an LCSSA phi node anymore.
287 if (ExitBlocks.size() == 1) {
288 PN->replaceAllUsesWith(ExitVal);
289 RecursivelyDeleteTriviallyDeadInstructions(PN);
293 if (ExitBlocks.size() != 1) {
294 // Clone the PHI and delete the original one. This lets IVUsers and
295 // any other maps purge the original user from their records.
296 PHINode *NewPN = PN->clone();
298 NewPN->insertBefore(PN);
299 PN->replaceAllUsesWith(NewPN);
300 PN->eraseFromParent();
306 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
307 // First step. Check to see if there are any floating-point recurrences.
308 // If there are, change them into integer recurrences, permitting analysis by
309 // the SCEV routines.
311 BasicBlock *Header = L->getHeader();
313 SmallVector<WeakVH, 8> PHIs;
314 for (BasicBlock::iterator I = Header->begin();
315 PHINode *PN = dyn_cast<PHINode>(I); ++I)
318 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
319 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
320 HandleFloatingPointIV(L, PN);
322 // If the loop previously had floating-point IV, ScalarEvolution
323 // may not have been able to compute a trip count. Now that we've done some
324 // re-writing, the trip count may be computable.
326 SE->forgetLoopBackedgeTakenCount(L);
329 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
330 IU = &getAnalysis<IVUsers>();
331 LI = &getAnalysis<LoopInfo>();
332 SE = &getAnalysis<ScalarEvolution>();
333 DT = &getAnalysis<DominatorTree>();
336 // If there are any floating-point recurrences, attempt to
337 // transform them to use integer recurrences.
338 RewriteNonIntegerIVs(L);
340 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
341 const SCEV* BackedgeTakenCount = SE->getBackedgeTakenCount(L);
343 // Create a rewriter object which we'll use to transform the code with.
344 SCEVExpander Rewriter(*SE);
346 // Check to see if this loop has a computable loop-invariant execution count.
347 // If so, this means that we can compute the final value of any expressions
348 // that are recurrent in the loop, and substitute the exit values from the
349 // loop into any instructions outside of the loop that use the final values of
350 // the current expressions.
352 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
353 RewriteLoopExitValues(L, BackedgeTakenCount, Rewriter);
355 // Compute the type of the largest recurrence expression, and decide whether
356 // a canonical induction variable should be inserted.
357 const Type *LargestType = 0;
358 bool NeedCannIV = false;
359 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
360 LargestType = BackedgeTakenCount->getType();
361 LargestType = SE->getEffectiveSCEVType(LargestType);
362 // If we have a known trip count and a single exit block, we'll be
363 // rewriting the loop exit test condition below, which requires a
364 // canonical induction variable.
368 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
369 const SCEV* Stride = IU->StrideOrder[i];
370 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
372 SE->getTypeSizeInBits(Ty) >
373 SE->getTypeSizeInBits(LargestType))
376 std::map<const SCEV*, IVUsersOfOneStride *>::iterator SI =
377 IU->IVUsesByStride.find(IU->StrideOrder[i]);
378 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
380 if (!SI->second->Users.empty())
384 // Now that we know the largest of of the induction variable expressions
385 // in this loop, insert a canonical induction variable of the largest size.
388 // Check to see if the loop already has a canonical-looking induction
389 // variable. If one is present and it's wider than the planned canonical
390 // induction variable, temporarily remove it, so that the Rewriter
391 // doesn't attempt to reuse it.
392 PHINode *OldCannIV = L->getCanonicalInductionVariable();
394 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
395 SE->getTypeSizeInBits(LargestType))
396 OldCannIV->removeFromParent();
401 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
405 DOUT << "INDVARS: New CanIV: " << *IndVar;
407 // Now that the official induction variable is established, reinsert
408 // the old canonical-looking variable after it so that the IR remains
409 // consistent. It will be deleted as part of the dead-PHI deletion at
410 // the end of the pass.
412 OldCannIV->insertAfter(cast<Instruction>(IndVar));
415 // If we have a trip count expression, rewrite the loop's exit condition
416 // using it. We can currently only handle loops with a single exit.
417 ICmpInst *NewICmp = 0;
418 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
420 "LinearFunctionTestReplace requires a canonical induction variable");
421 // Can't rewrite non-branch yet.
422 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
423 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
424 ExitingBlock, BI, Rewriter);
427 // Rewrite IV-derived expressions. Clears the rewriter cache.
428 RewriteIVExpressions(L, LargestType, Rewriter);
430 // The Rewriter may not be used from this point on.
432 // Loop-invariant instructions in the preheader that aren't used in the
433 // loop may be sunk below the loop to reduce register pressure.
434 SinkUnusedInvariants(L);
436 // For completeness, inform IVUsers of the IV use in the newly-created
437 // loop exit test instruction.
439 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
441 // Clean up dead instructions.
442 DeleteDeadPHIs(L->getHeader());
443 // Check a post-condition.
444 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
448 void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
449 SCEVExpander &Rewriter) {
450 SmallVector<WeakVH, 16> DeadInsts;
452 // Rewrite all induction variable expressions in terms of the canonical
453 // induction variable.
455 // If there were induction variables of other sizes or offsets, manually
456 // add the offsets to the primary induction variable and cast, avoiding
457 // the need for the code evaluation methods to insert induction variables
458 // of different sizes.
459 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
460 const SCEV* Stride = IU->StrideOrder[i];
462 std::map<const SCEV*, IVUsersOfOneStride *>::iterator SI =
463 IU->IVUsesByStride.find(IU->StrideOrder[i]);
464 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
465 ilist<IVStrideUse> &List = SI->second->Users;
466 for (ilist<IVStrideUse>::iterator UI = List.begin(),
467 E = List.end(); UI != E; ++UI) {
468 Value *Op = UI->getOperandValToReplace();
469 const Type *UseTy = Op->getType();
470 Instruction *User = UI->getUser();
472 // Compute the final addrec to expand into code.
473 const SCEV* AR = IU->getReplacementExpr(*UI);
475 // FIXME: It is an extremely bad idea to indvar substitute anything more
476 // complex than affine induction variables. Doing so will put expensive
477 // polynomial evaluations inside of the loop, and the str reduction pass
478 // currently can only reduce affine polynomials. For now just disable
479 // indvar subst on anything more complex than an affine addrec, unless
480 // it can be expanded to a trivial value.
481 if (!AR->isLoopInvariant(L) && !Stride->isLoopInvariant(L))
484 // Determine the insertion point for this user. By default, insert
485 // immediately before the user. The SCEVExpander class will automatically
486 // hoist loop invariants out of the loop. For PHI nodes, there may be
487 // multiple uses, so compute the nearest common dominator for the
489 Instruction *InsertPt = User;
490 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
491 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
492 if (PHI->getIncomingValue(i) == Op) {
493 if (InsertPt == User)
494 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
497 DT->findNearestCommonDominator(InsertPt->getParent(),
498 PHI->getIncomingBlock(i))
502 // Now expand it into actual Instructions and patch it into place.
503 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
505 // Patch the new value into place.
507 NewVal->takeName(Op);
508 User->replaceUsesOfWith(Op, NewVal);
509 UI->setOperandValToReplace(NewVal);
510 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *Op
511 << " into = " << *NewVal << "\n";
515 // The old value may be dead now.
516 DeadInsts.push_back(Op);
520 // Clear the rewriter cache, because values that are in the rewriter's cache
521 // can be deleted in the loop below, causing the AssertingVH in the cache to
524 // Now that we're done iterating through lists, clean up any instructions
525 // which are now dead.
526 while (!DeadInsts.empty()) {
527 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
529 RecursivelyDeleteTriviallyDeadInstructions(Inst);
533 /// If there's a single exit block, sink any loop-invariant values that
534 /// were defined in the preheader but not used inside the loop into the
535 /// exit block to reduce register pressure in the loop.
536 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
537 BasicBlock *ExitBlock = L->getExitBlock();
538 if (!ExitBlock) return;
540 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
541 BasicBlock *Preheader = L->getLoopPreheader();
542 BasicBlock::iterator I = Preheader->getTerminator();
543 while (I != Preheader->begin()) {
545 // New instructions were inserted at the end of the preheader.
550 // Determine if there is a use in or before the loop (direct or
552 bool UsedInLoop = false;
553 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
555 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
556 if (PHINode *P = dyn_cast<PHINode>(UI)) {
558 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
559 UseBB = P->getIncomingBlock(i);
561 if (UseBB == Preheader || L->contains(UseBB)) {
566 // If there is, the def must remain in the preheader.
569 // Otherwise, sink it to the exit block.
570 Instruction *ToMove = I;
572 if (I != Preheader->begin())
576 ToMove->moveBefore(InsertPt);
583 /// Return true if it is OK to use SIToFPInst for an inducation variable
584 /// with given inital and exit values.
585 static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
586 uint64_t intIV, uint64_t intEV) {
588 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
591 // If the iteration range can be handled by SIToFPInst then use it.
592 APInt Max = APInt::getSignedMaxValue(32);
593 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
599 /// convertToInt - Convert APF to an integer, if possible.
600 static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
602 bool isExact = false;
603 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
605 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
606 APFloat::rmTowardZero, &isExact)
615 /// HandleFloatingPointIV - If the loop has floating induction variable
616 /// then insert corresponding integer induction variable if possible.
618 /// for(double i = 0; i < 10000; ++i)
620 /// is converted into
621 /// for(int i = 0; i < 10000; ++i)
624 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
626 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
627 unsigned BackEdge = IncomingEdge^1;
629 // Check incoming value.
630 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
631 if (!InitValue) return;
632 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
633 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
636 // Check IV increment. Reject this PH if increement operation is not
637 // an add or increment value can not be represented by an integer.
638 BinaryOperator *Incr =
639 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
641 if (Incr->getOpcode() != Instruction::FAdd) return;
642 ConstantFP *IncrValue = NULL;
643 unsigned IncrVIndex = 1;
644 if (Incr->getOperand(1) == PH)
646 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
647 if (!IncrValue) return;
648 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
649 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
652 // Check Incr uses. One user is PH and the other users is exit condition used
653 // by the conditional terminator.
654 Value::use_iterator IncrUse = Incr->use_begin();
655 Instruction *U1 = cast<Instruction>(IncrUse++);
656 if (IncrUse == Incr->use_end()) return;
657 Instruction *U2 = cast<Instruction>(IncrUse++);
658 if (IncrUse != Incr->use_end()) return;
660 // Find exit condition.
661 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
663 EC = dyn_cast<FCmpInst>(U2);
666 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
667 if (!BI->isConditional()) return;
668 if (BI->getCondition() != EC) return;
671 // Find exit value. If exit value can not be represented as an interger then
672 // do not handle this floating point PH.
673 ConstantFP *EV = NULL;
674 unsigned EVIndex = 1;
675 if (EC->getOperand(1) == Incr)
677 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
679 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
680 if (!convertToInt(EV->getValueAPF(), &intEV))
683 // Find new predicate for integer comparison.
684 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
685 switch (EC->getPredicate()) {
686 case CmpInst::FCMP_OEQ:
687 case CmpInst::FCMP_UEQ:
688 NewPred = CmpInst::ICMP_EQ;
690 case CmpInst::FCMP_OGT:
691 case CmpInst::FCMP_UGT:
692 NewPred = CmpInst::ICMP_UGT;
694 case CmpInst::FCMP_OGE:
695 case CmpInst::FCMP_UGE:
696 NewPred = CmpInst::ICMP_UGE;
698 case CmpInst::FCMP_OLT:
699 case CmpInst::FCMP_ULT:
700 NewPred = CmpInst::ICMP_ULT;
702 case CmpInst::FCMP_OLE:
703 case CmpInst::FCMP_ULE:
704 NewPred = CmpInst::ICMP_ULE;
709 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
711 // Insert new integer induction variable.
712 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
713 PH->getName()+".int", PH);
714 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
715 PH->getIncomingBlock(IncomingEdge));
717 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
718 ConstantInt::get(Type::Int32Ty,
720 Incr->getName()+".int", Incr);
721 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
723 // The back edge is edge 1 of newPHI, whatever it may have been in the
725 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
726 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
727 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
728 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
729 EC->getParent()->getTerminator());
731 // In the following deltions, PH may become dead and may be deleted.
732 // Use a WeakVH to observe whether this happens.
735 // Delete old, floating point, exit comparision instruction.
737 EC->replaceAllUsesWith(NewEC);
738 RecursivelyDeleteTriviallyDeadInstructions(EC);
740 // Delete old, floating point, increment instruction.
741 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
742 RecursivelyDeleteTriviallyDeadInstructions(Incr);
744 // Replace floating induction variable, if it isn't already deleted.
745 // Give SIToFPInst preference over UIToFPInst because it is faster on
746 // platforms that are widely used.
747 if (WeakPH && !PH->use_empty()) {
748 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
749 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
750 PH->getParent()->getFirstNonPHI());
751 PH->replaceAllUsesWith(Conv);
753 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
754 PH->getParent()->getFirstNonPHI());
755 PH->replaceAllUsesWith(Conv);
757 RecursivelyDeleteTriviallyDeadInstructions(PH);
760 // Add a new IVUsers entry for the newly-created integer PHI.
761 IU->AddUsersIfInteresting(NewPHI);