Silence -Wunused-variable in release builds.
[llvm/stm8.git] / lib / Transforms / Scalar / IndVarSimplify.cpp
blob31dbd42f2c03deee9fbff3377c77e9763820f11c
1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
22 // sign-extended.
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
26 // changes:
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/IntrinsicInst.h"
47 #include "llvm/LLVMContext.h"
48 #include "llvm/Type.h"
49 #include "llvm/Analysis/Dominators.h"
50 #include "llvm/Analysis/IVUsers.h"
51 #include "llvm/Analysis/ScalarEvolutionExpander.h"
52 #include "llvm/Analysis/LoopInfo.h"
53 #include "llvm/Analysis/LoopPass.h"
54 #include "llvm/Support/CFG.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Utils/Local.h"
59 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
60 #include "llvm/Target/TargetData.h"
61 #include "llvm/ADT/DenseMap.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/ADT/Statistic.h"
64 #include "llvm/ADT/STLExtras.h"
65 using namespace llvm;
67 STATISTIC(NumRemoved , "Number of aux indvars removed");
68 STATISTIC(NumWidened , "Number of indvars widened");
69 STATISTIC(NumInserted , "Number of canonical indvars added");
70 STATISTIC(NumReplaced , "Number of exit values replaced");
71 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
72 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
73 STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
74 STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
75 STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
76 STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
78 static cl::opt<bool> DisableIVRewrite(
79 "disable-iv-rewrite", cl::Hidden,
80 cl::desc("Disable canonical induction variable rewriting"));
82 namespace {
83 class IndVarSimplify : public LoopPass {
84 typedef DenseMap< const SCEV *, AssertingVH<PHINode> > ExprToIVMapTy;
86 IVUsers *IU;
87 LoopInfo *LI;
88 ScalarEvolution *SE;
89 DominatorTree *DT;
90 TargetData *TD;
92 ExprToIVMapTy ExprToIVMap;
93 SmallVector<WeakVH, 16> DeadInsts;
94 bool Changed;
95 public:
97 static char ID; // Pass identification, replacement for typeid
98 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
99 Changed(false) {
100 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
103 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
105 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
106 AU.addRequired<DominatorTree>();
107 AU.addRequired<LoopInfo>();
108 AU.addRequired<ScalarEvolution>();
109 AU.addRequiredID(LoopSimplifyID);
110 AU.addRequiredID(LCSSAID);
111 if (!DisableIVRewrite)
112 AU.addRequired<IVUsers>();
113 AU.addPreserved<ScalarEvolution>();
114 AU.addPreservedID(LoopSimplifyID);
115 AU.addPreservedID(LCSSAID);
116 if (!DisableIVRewrite)
117 AU.addPreserved<IVUsers>();
118 AU.setPreservesCFG();
121 private:
122 virtual void releaseMemory() {
123 ExprToIVMap.clear();
124 DeadInsts.clear();
127 bool isValidRewrite(Value *FromVal, Value *ToVal);
129 void SimplifyIVUsers(SCEVExpander &Rewriter);
130 void SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter);
132 bool EliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
133 void EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
134 void EliminateIVRemainder(BinaryOperator *Rem,
135 Value *IVOperand,
136 bool IsSigned);
137 bool isSimpleIVUser(Instruction *I, const Loop *L);
138 void RewriteNonIntegerIVs(Loop *L);
140 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
141 PHINode *IndVar,
142 SCEVExpander &Rewriter);
144 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
146 void SimplifyCongruentIVs(Loop *L);
148 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
150 void SinkUnusedInvariants(Loop *L);
152 void HandleFloatingPointIV(Loop *L, PHINode *PH);
156 char IndVarSimplify::ID = 0;
157 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
158 "Induction Variable Simplification", false, false)
159 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
160 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
161 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
162 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
163 INITIALIZE_PASS_DEPENDENCY(LCSSA)
164 INITIALIZE_PASS_DEPENDENCY(IVUsers)
165 INITIALIZE_PASS_END(IndVarSimplify, "indvars",
166 "Induction Variable Simplification", false, false)
168 Pass *llvm::createIndVarSimplifyPass() {
169 return new IndVarSimplify();
172 /// isValidRewrite - Return true if the SCEV expansion generated by the
173 /// rewriter can replace the original value. SCEV guarantees that it
174 /// produces the same value, but the way it is produced may be illegal IR.
175 /// Ideally, this function will only be called for verification.
176 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
177 // If an SCEV expression subsumed multiple pointers, its expansion could
178 // reassociate the GEP changing the base pointer. This is illegal because the
179 // final address produced by a GEP chain must be inbounds relative to its
180 // underlying object. Otherwise basic alias analysis, among other things,
181 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
182 // producing an expression involving multiple pointers. Until then, we must
183 // bail out here.
185 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
186 // because it understands lcssa phis while SCEV does not.
187 Value *FromPtr = FromVal;
188 Value *ToPtr = ToVal;
189 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
190 FromPtr = GEP->getPointerOperand();
192 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
193 ToPtr = GEP->getPointerOperand();
195 if (FromPtr != FromVal || ToPtr != ToVal) {
196 // Quickly check the common case
197 if (FromPtr == ToPtr)
198 return true;
200 // SCEV may have rewritten an expression that produces the GEP's pointer
201 // operand. That's ok as long as the pointer operand has the same base
202 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
203 // base of a recurrence. This handles the case in which SCEV expansion
204 // converts a pointer type recurrence into a nonrecurrent pointer base
205 // indexed by an integer recurrence.
206 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
207 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
208 if (FromBase == ToBase)
209 return true;
211 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
212 << *FromBase << " != " << *ToBase << "\n");
214 return false;
216 return true;
219 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
220 /// count expression can be safely and cheaply expanded into an instruction
221 /// sequence that can be used by LinearFunctionTestReplace.
222 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
223 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
224 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
225 BackedgeTakenCount->isZero())
226 return false;
228 if (!L->getExitingBlock())
229 return false;
231 // Can't rewrite non-branch yet.
232 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
233 if (!BI)
234 return false;
236 // Special case: If the backedge-taken count is a UDiv, it's very likely a
237 // UDiv that ScalarEvolution produced in order to compute a precise
238 // expression, rather than a UDiv from the user's code. If we can't find a
239 // UDiv in the code with some simple searching, assume the former and forego
240 // rewriting the loop.
241 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
242 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
243 if (!OrigCond) return false;
244 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
245 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
246 if (R != BackedgeTakenCount) {
247 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
248 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
249 if (L != BackedgeTakenCount)
250 return false;
253 return true;
256 /// getBackedgeIVType - Get the widest type used by the loop test after peeking
257 /// through Truncs.
259 /// TODO: Unnecessary once LinearFunctionTestReplace is removed.
260 static const Type *getBackedgeIVType(Loop *L) {
261 if (!L->getExitingBlock())
262 return 0;
264 // Can't rewrite non-branch yet.
265 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
266 if (!BI)
267 return 0;
269 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
270 if (!Cond)
271 return 0;
273 const Type *Ty = 0;
274 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
275 OI != OE; ++OI) {
276 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
277 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
278 if (!Trunc)
279 continue;
281 return Trunc->getSrcTy();
283 return Ty;
286 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
287 /// loop to be a canonical != comparison against the incremented loop induction
288 /// variable. This pass is able to rewrite the exit tests of any loop where the
289 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
290 /// is actually a much broader range than just linear tests.
291 ICmpInst *IndVarSimplify::
292 LinearFunctionTestReplace(Loop *L,
293 const SCEV *BackedgeTakenCount,
294 PHINode *IndVar,
295 SCEVExpander &Rewriter) {
296 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
297 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
299 // If the exiting block is not the same as the backedge block, we must compare
300 // against the preincremented value, otherwise we prefer to compare against
301 // the post-incremented value.
302 Value *CmpIndVar;
303 const SCEV *RHS = BackedgeTakenCount;
304 if (L->getExitingBlock() == L->getLoopLatch()) {
305 // Add one to the "backedge-taken" count to get the trip count.
306 // If this addition may overflow, we have to be more pessimistic and
307 // cast the induction variable before doing the add.
308 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
309 const SCEV *N =
310 SE->getAddExpr(BackedgeTakenCount,
311 SE->getConstant(BackedgeTakenCount->getType(), 1));
312 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
313 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
314 // No overflow. Cast the sum.
315 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
316 } else {
317 // Potential overflow. Cast before doing the add.
318 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
319 IndVar->getType());
320 RHS = SE->getAddExpr(RHS,
321 SE->getConstant(IndVar->getType(), 1));
324 // The BackedgeTaken expression contains the number of times that the
325 // backedge branches to the loop header. This is one less than the
326 // number of times the loop executes, so use the incremented indvar.
327 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
328 } else {
329 // We have to use the preincremented value...
330 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
331 IndVar->getType());
332 CmpIndVar = IndVar;
335 // Expand the code for the iteration count.
336 assert(SE->isLoopInvariant(RHS, L) &&
337 "Computed iteration count is not loop invariant!");
338 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
340 // Insert a new icmp_ne or icmp_eq instruction before the branch.
341 ICmpInst::Predicate Opcode;
342 if (L->contains(BI->getSuccessor(0)))
343 Opcode = ICmpInst::ICMP_NE;
344 else
345 Opcode = ICmpInst::ICMP_EQ;
347 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
348 << " LHS:" << *CmpIndVar << '\n'
349 << " op:\t"
350 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
351 << " RHS:\t" << *RHS << "\n");
353 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
354 Cond->setDebugLoc(BI->getDebugLoc());
355 Value *OrigCond = BI->getCondition();
356 // It's tempting to use replaceAllUsesWith here to fully replace the old
357 // comparison, but that's not immediately safe, since users of the old
358 // comparison may not be dominated by the new comparison. Instead, just
359 // update the branch to use the new comparison; in the common case this
360 // will make old comparison dead.
361 BI->setCondition(Cond);
362 DeadInsts.push_back(OrigCond);
364 ++NumLFTR;
365 Changed = true;
366 return Cond;
369 /// RewriteLoopExitValues - Check to see if this loop has a computable
370 /// loop-invariant execution count. If so, this means that we can compute the
371 /// final value of any expressions that are recurrent in the loop, and
372 /// substitute the exit values from the loop into any instructions outside of
373 /// the loop that use the final values of the current expressions.
375 /// This is mostly redundant with the regular IndVarSimplify activities that
376 /// happen later, except that it's more powerful in some cases, because it's
377 /// able to brute-force evaluate arbitrary instructions as long as they have
378 /// constant operands at the beginning of the loop.
379 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
380 // Verify the input to the pass in already in LCSSA form.
381 assert(L->isLCSSAForm(*DT));
383 SmallVector<BasicBlock*, 8> ExitBlocks;
384 L->getUniqueExitBlocks(ExitBlocks);
386 // Find all values that are computed inside the loop, but used outside of it.
387 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
388 // the exit blocks of the loop to find them.
389 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
390 BasicBlock *ExitBB = ExitBlocks[i];
392 // If there are no PHI nodes in this exit block, then no values defined
393 // inside the loop are used on this path, skip it.
394 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
395 if (!PN) continue;
397 unsigned NumPreds = PN->getNumIncomingValues();
399 // Iterate over all of the PHI nodes.
400 BasicBlock::iterator BBI = ExitBB->begin();
401 while ((PN = dyn_cast<PHINode>(BBI++))) {
402 if (PN->use_empty())
403 continue; // dead use, don't replace it
405 // SCEV only supports integer expressions for now.
406 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
407 continue;
409 // It's necessary to tell ScalarEvolution about this explicitly so that
410 // it can walk the def-use list and forget all SCEVs, as it may not be
411 // watching the PHI itself. Once the new exit value is in place, there
412 // may not be a def-use connection between the loop and every instruction
413 // which got a SCEVAddRecExpr for that loop.
414 SE->forgetValue(PN);
416 // Iterate over all of the values in all the PHI nodes.
417 for (unsigned i = 0; i != NumPreds; ++i) {
418 // If the value being merged in is not integer or is not defined
419 // in the loop, skip it.
420 Value *InVal = PN->getIncomingValue(i);
421 if (!isa<Instruction>(InVal))
422 continue;
424 // If this pred is for a subloop, not L itself, skip it.
425 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
426 continue; // The Block is in a subloop, skip it.
428 // Check that InVal is defined in the loop.
429 Instruction *Inst = cast<Instruction>(InVal);
430 if (!L->contains(Inst))
431 continue;
433 // Okay, this instruction has a user outside of the current loop
434 // and varies predictably *inside* the loop. Evaluate the value it
435 // contains when the loop exits, if possible.
436 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
437 if (!SE->isLoopInvariant(ExitValue, L))
438 continue;
440 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
442 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
443 << " LoopVal = " << *Inst << "\n");
445 if (!isValidRewrite(Inst, ExitVal)) {
446 DeadInsts.push_back(ExitVal);
447 continue;
449 Changed = true;
450 ++NumReplaced;
452 PN->setIncomingValue(i, ExitVal);
454 // If this instruction is dead now, delete it.
455 RecursivelyDeleteTriviallyDeadInstructions(Inst);
457 if (NumPreds == 1) {
458 // Completely replace a single-pred PHI. This is safe, because the
459 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
460 // node anymore.
461 PN->replaceAllUsesWith(ExitVal);
462 RecursivelyDeleteTriviallyDeadInstructions(PN);
465 if (NumPreds != 1) {
466 // Clone the PHI and delete the original one. This lets IVUsers and
467 // any other maps purge the original user from their records.
468 PHINode *NewPN = cast<PHINode>(PN->clone());
469 NewPN->takeName(PN);
470 NewPN->insertBefore(PN);
471 PN->replaceAllUsesWith(NewPN);
472 PN->eraseFromParent();
477 // The insertion point instruction may have been deleted; clear it out
478 // so that the rewriter doesn't trip over it later.
479 Rewriter.clearInsertPoint();
482 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
483 // First step. Check to see if there are any floating-point recurrences.
484 // If there are, change them into integer recurrences, permitting analysis by
485 // the SCEV routines.
487 BasicBlock *Header = L->getHeader();
489 SmallVector<WeakVH, 8> PHIs;
490 for (BasicBlock::iterator I = Header->begin();
491 PHINode *PN = dyn_cast<PHINode>(I); ++I)
492 PHIs.push_back(PN);
494 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
495 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
496 HandleFloatingPointIV(L, PN);
498 // If the loop previously had floating-point IV, ScalarEvolution
499 // may not have been able to compute a trip count. Now that we've done some
500 // re-writing, the trip count may be computable.
501 if (Changed)
502 SE->forgetLoop(L);
505 /// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this
506 /// loop. IVUsers is treated as a worklist. Each successive simplification may
507 /// push more users which may themselves be candidates for simplification.
509 /// This is the old approach to IV simplification to be replaced by
510 /// SimplifyIVUsersNoRewrite.
512 void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) {
513 // Each round of simplification involves a round of eliminating operations
514 // followed by a round of widening IVs. A single IVUsers worklist is used
515 // across all rounds. The inner loop advances the user. If widening exposes
516 // more uses, then another pass through the outer loop is triggered.
517 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) {
518 Instruction *UseInst = I->getUser();
519 Value *IVOperand = I->getOperandValToReplace();
521 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
522 EliminateIVComparison(ICmp, IVOperand);
523 continue;
525 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
526 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
527 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
528 EliminateIVRemainder(Rem, IVOperand, IsSigned);
529 continue;
535 namespace {
536 // Collect information about induction variables that are used by sign/zero
537 // extend operations. This information is recorded by CollectExtend and
538 // provides the input to WidenIV.
539 struct WideIVInfo {
540 const Type *WidestNativeType; // Widest integer type created [sz]ext
541 bool IsSigned; // Was an sext user seen before a zext?
543 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
547 /// CollectExtend - Update information about the induction variable that is
548 /// extended by this sign or zero extend operation. This is used to determine
549 /// the final width of the IV before actually widening it.
550 static void CollectExtend(CastInst *Cast, bool IsSigned, WideIVInfo &WI,
551 ScalarEvolution *SE, const TargetData *TD) {
552 const Type *Ty = Cast->getType();
553 uint64_t Width = SE->getTypeSizeInBits(Ty);
554 if (TD && !TD->isLegalInteger(Width))
555 return;
557 if (!WI.WidestNativeType) {
558 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
559 WI.IsSigned = IsSigned;
560 return;
563 // We extend the IV to satisfy the sign of its first user, arbitrarily.
564 if (WI.IsSigned != IsSigned)
565 return;
567 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
568 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
571 namespace {
572 /// WidenIV - The goal of this transform is to remove sign and zero extends
573 /// without creating any new induction variables. To do this, it creates a new
574 /// phi of the wider type and redirects all users, either removing extends or
575 /// inserting truncs whenever we stop propagating the type.
577 class WidenIV {
578 // Parameters
579 PHINode *OrigPhi;
580 const Type *WideType;
581 bool IsSigned;
583 // Context
584 LoopInfo *LI;
585 Loop *L;
586 ScalarEvolution *SE;
587 DominatorTree *DT;
589 // Result
590 PHINode *WidePhi;
591 Instruction *WideInc;
592 const SCEV *WideIncExpr;
593 SmallVectorImpl<WeakVH> &DeadInsts;
595 SmallPtrSet<Instruction*,16> Widened;
596 SmallVector<std::pair<Use *, Instruction *>, 8> NarrowIVUsers;
598 public:
599 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
600 ScalarEvolution *SEv, DominatorTree *DTree,
601 SmallVectorImpl<WeakVH> &DI) :
602 OrigPhi(PN),
603 WideType(WI.WidestNativeType),
604 IsSigned(WI.IsSigned),
605 LI(LInfo),
606 L(LI->getLoopFor(OrigPhi->getParent())),
607 SE(SEv),
608 DT(DTree),
609 WidePhi(0),
610 WideInc(0),
611 WideIncExpr(0),
612 DeadInsts(DI) {
613 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
616 PHINode *CreateWideIV(SCEVExpander &Rewriter);
618 protected:
619 Instruction *CloneIVUser(Instruction *NarrowUse,
620 Instruction *NarrowDef,
621 Instruction *WideDef);
623 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
625 Instruction *WidenIVUse(Use &NarrowDefUse, Instruction *NarrowDef,
626 Instruction *WideDef);
628 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
630 } // anonymous namespace
632 static Value *getExtend( Value *NarrowOper, const Type *WideType,
633 bool IsSigned, IRBuilder<> &Builder) {
634 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
635 Builder.CreateZExt(NarrowOper, WideType);
638 /// CloneIVUser - Instantiate a wide operation to replace a narrow
639 /// operation. This only needs to handle operations that can evaluation to
640 /// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
641 Instruction *WidenIV::CloneIVUser(Instruction *NarrowUse,
642 Instruction *NarrowDef,
643 Instruction *WideDef) {
644 unsigned Opcode = NarrowUse->getOpcode();
645 switch (Opcode) {
646 default:
647 return 0;
648 case Instruction::Add:
649 case Instruction::Mul:
650 case Instruction::UDiv:
651 case Instruction::Sub:
652 case Instruction::And:
653 case Instruction::Or:
654 case Instruction::Xor:
655 case Instruction::Shl:
656 case Instruction::LShr:
657 case Instruction::AShr:
658 DEBUG(dbgs() << "Cloning IVUser: " << *NarrowUse << "\n");
660 IRBuilder<> Builder(NarrowUse);
662 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
663 // anything about the narrow operand yet so must insert a [sz]ext. It is
664 // probably loop invariant and will be folded or hoisted. If it actually
665 // comes from a widened IV, it should be removed during a future call to
666 // WidenIVUse.
667 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) ? WideDef :
668 getExtend(NarrowUse->getOperand(0), WideType, IsSigned, Builder);
669 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) ? WideDef :
670 getExtend(NarrowUse->getOperand(1), WideType, IsSigned, Builder);
672 BinaryOperator *NarrowBO = cast<BinaryOperator>(NarrowUse);
673 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
674 LHS, RHS,
675 NarrowBO->getName());
676 Builder.Insert(WideBO);
677 if (const OverflowingBinaryOperator *OBO =
678 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
679 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
680 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
682 return WideBO;
684 llvm_unreachable(0);
687 /// HoistStep - Attempt to hoist an IV increment above a potential use.
689 /// To successfully hoist, two criteria must be met:
690 /// - IncV operands dominate InsertPos and
691 /// - InsertPos dominates IncV
693 /// Meeting the second condition means that we don't need to check all of IncV's
694 /// existing uses (it's moving up in the domtree).
696 /// This does not yet recursively hoist the operands, although that would
697 /// not be difficult.
698 static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
699 const DominatorTree *DT)
701 if (DT->dominates(IncV, InsertPos))
702 return true;
704 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
705 return false;
707 if (IncV->mayHaveSideEffects())
708 return false;
710 // Attempt to hoist IncV
711 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
712 OI != OE; ++OI) {
713 Instruction *OInst = dyn_cast<Instruction>(OI);
714 if (OInst && !DT->dominates(OInst, InsertPos))
715 return false;
717 IncV->moveBefore(InsertPos);
718 return true;
721 // GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
722 // perspective after widening it's type? In other words, can the extend be
723 // safely hoisted out of the loop with SCEV reducing the value to a recurrence
724 // on the same loop. If so, return the sign or zero extended
725 // recurrence. Otherwise return NULL.
726 const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
727 if (!SE->isSCEVable(NarrowUse->getType()))
728 return 0;
730 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
731 if (SE->getTypeSizeInBits(NarrowExpr->getType())
732 >= SE->getTypeSizeInBits(WideType)) {
733 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
734 // index. So don't follow this use.
735 return 0;
738 const SCEV *WideExpr = IsSigned ?
739 SE->getSignExtendExpr(NarrowExpr, WideType) :
740 SE->getZeroExtendExpr(NarrowExpr, WideType);
741 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
742 if (!AddRec || AddRec->getLoop() != L)
743 return 0;
745 return AddRec;
748 /// WidenIVUse - Determine whether an individual user of the narrow IV can be
749 /// widened. If so, return the wide clone of the user.
750 Instruction *WidenIV::WidenIVUse(Use &NarrowDefUse, Instruction *NarrowDef,
751 Instruction *WideDef) {
752 Instruction *NarrowUse = cast<Instruction>(NarrowDefUse.getUser());
754 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
755 if (isa<PHINode>(NarrowUse) && LI->getLoopFor(NarrowUse->getParent()) != L)
756 return 0;
758 // Our raison d'etre! Eliminate sign and zero extension.
759 if (IsSigned ? isa<SExtInst>(NarrowUse) : isa<ZExtInst>(NarrowUse)) {
760 Value *NewDef = WideDef;
761 if (NarrowUse->getType() != WideType) {
762 unsigned CastWidth = SE->getTypeSizeInBits(NarrowUse->getType());
763 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
764 if (CastWidth < IVWidth) {
765 // The cast isn't as wide as the IV, so insert a Trunc.
766 IRBuilder<> Builder(NarrowDefUse);
767 NewDef = Builder.CreateTrunc(WideDef, NarrowUse->getType());
769 else {
770 // A wider extend was hidden behind a narrower one. This may induce
771 // another round of IV widening in which the intermediate IV becomes
772 // dead. It should be very rare.
773 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
774 << " not wide enough to subsume " << *NarrowUse << "\n");
775 NarrowUse->replaceUsesOfWith(NarrowDef, WideDef);
776 NewDef = NarrowUse;
779 if (NewDef != NarrowUse) {
780 DEBUG(dbgs() << "INDVARS: eliminating " << *NarrowUse
781 << " replaced by " << *WideDef << "\n");
782 ++NumElimExt;
783 NarrowUse->replaceAllUsesWith(NewDef);
784 DeadInsts.push_back(NarrowUse);
786 // Now that the extend is gone, we want to expose it's uses for potential
787 // further simplification. We don't need to directly inform SimplifyIVUsers
788 // of the new users, because their parent IV will be processed later as a
789 // new loop phi. If we preserved IVUsers analysis, we would also want to
790 // push the uses of WideDef here.
792 // No further widening is needed. The deceased [sz]ext had done it for us.
793 return 0;
796 // Does this user itself evaluate to a recurrence after widening?
797 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(NarrowUse);
798 if (!WideAddRec) {
799 // This user does not evaluate to a recurence after widening, so don't
800 // follow it. Instead insert a Trunc to kill off the original use,
801 // eventually isolating the original narrow IV so it can be removed.
802 IRBuilder<> Builder(NarrowDefUse);
803 Value *Trunc = Builder.CreateTrunc(WideDef, NarrowDef->getType());
804 NarrowUse->replaceUsesOfWith(NarrowDef, Trunc);
805 return 0;
807 // We assume that block terminators are not SCEVable. We wouldn't want to
808 // insert a Trunc after a terminator if there happens to be a critical edge.
809 assert(NarrowUse != NarrowUse->getParent()->getTerminator() &&
810 "SCEV is not expected to evaluate a block terminator");
812 // Reuse the IV increment that SCEVExpander created as long as it dominates
813 // NarrowUse.
814 Instruction *WideUse = 0;
815 if (WideAddRec == WideIncExpr && HoistStep(WideInc, NarrowUse, DT)) {
816 WideUse = WideInc;
818 else {
819 WideUse = CloneIVUser(NarrowUse, NarrowDef, WideDef);
820 if (!WideUse)
821 return 0;
823 // Evaluation of WideAddRec ensured that the narrow expression could be
824 // extended outside the loop without overflow. This suggests that the wide use
825 // evaluates to the same expression as the extended narrow use, but doesn't
826 // absolutely guarantee it. Hence the following failsafe check. In rare cases
827 // where it fails, we simply throw away the newly created wide use.
828 if (WideAddRec != SE->getSCEV(WideUse)) {
829 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
830 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
831 DeadInsts.push_back(WideUse);
832 return 0;
835 // Returning WideUse pushes it on the worklist.
836 return WideUse;
839 /// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
841 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
842 for (Value::use_iterator UI = NarrowDef->use_begin(),
843 UE = NarrowDef->use_end(); UI != UE; ++UI) {
844 Use &U = UI.getUse();
846 // Handle data flow merges and bizarre phi cycles.
847 if (!Widened.insert(cast<Instruction>(U.getUser())))
848 continue;
850 NarrowIVUsers.push_back(std::make_pair(&UI.getUse(), WideDef));
854 /// CreateWideIV - Process a single induction variable. First use the
855 /// SCEVExpander to create a wide induction variable that evaluates to the same
856 /// recurrence as the original narrow IV. Then use a worklist to forward
857 /// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
858 /// interesting IV users, the narrow IV will be isolated for removal by
859 /// DeleteDeadPHIs.
861 /// It would be simpler to delete uses as they are processed, but we must avoid
862 /// invalidating SCEV expressions.
864 PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
865 // Is this phi an induction variable?
866 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
867 if (!AddRec)
868 return NULL;
870 // Widen the induction variable expression.
871 const SCEV *WideIVExpr = IsSigned ?
872 SE->getSignExtendExpr(AddRec, WideType) :
873 SE->getZeroExtendExpr(AddRec, WideType);
875 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
876 "Expect the new IV expression to preserve its type");
878 // Can the IV be extended outside the loop without overflow?
879 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
880 if (!AddRec || AddRec->getLoop() != L)
881 return NULL;
883 // An AddRec must have loop-invariant operands. Since this AddRec is
884 // materialized by a loop header phi, the expression cannot have any post-loop
885 // operands, so they must dominate the loop header.
886 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
887 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
888 && "Loop header phi recurrence inputs do not dominate the loop");
890 // The rewriter provides a value for the desired IV expression. This may
891 // either find an existing phi or materialize a new one. Either way, we
892 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
893 // of the phi-SCC dominates the loop entry.
894 Instruction *InsertPt = L->getHeader()->begin();
895 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
897 // Remembering the WideIV increment generated by SCEVExpander allows
898 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
899 // employ a general reuse mechanism because the call above is the only call to
900 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
901 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
902 WideInc =
903 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
904 WideIncExpr = SE->getSCEV(WideInc);
907 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
908 ++NumWidened;
910 // Traverse the def-use chain using a worklist starting at the original IV.
911 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
913 Widened.insert(OrigPhi);
914 pushNarrowIVUsers(OrigPhi, WidePhi);
916 while (!NarrowIVUsers.empty()) {
917 Use *UsePtr;
918 Instruction *WideDef;
919 tie(UsePtr, WideDef) = NarrowIVUsers.pop_back_val();
920 Use &NarrowDefUse = *UsePtr;
922 // Process a def-use edge. This may replace the use, so don't hold a
923 // use_iterator across it.
924 Instruction *NarrowDef = cast<Instruction>(NarrowDefUse.get());
925 Instruction *WideUse = WidenIVUse(NarrowDefUse, NarrowDef, WideDef);
927 // Follow all def-use edges from the previous narrow use.
928 if (WideUse)
929 pushNarrowIVUsers(cast<Instruction>(NarrowDefUse.getUser()), WideUse);
931 // WidenIVUse may have removed the def-use edge.
932 if (NarrowDef->use_empty())
933 DeadInsts.push_back(NarrowDef);
935 return WidePhi;
938 void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
939 unsigned IVOperIdx = 0;
940 ICmpInst::Predicate Pred = ICmp->getPredicate();
941 if (IVOperand != ICmp->getOperand(0)) {
942 // Swapped
943 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
944 IVOperIdx = 1;
945 Pred = ICmpInst::getSwappedPredicate(Pred);
948 // Get the SCEVs for the ICmp operands.
949 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
950 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
952 // Simplify unnecessary loops away.
953 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
954 S = SE->getSCEVAtScope(S, ICmpLoop);
955 X = SE->getSCEVAtScope(X, ICmpLoop);
957 // If the condition is always true or always false, replace it with
958 // a constant value.
959 if (SE->isKnownPredicate(Pred, S, X))
960 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
961 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
962 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
963 else
964 return;
966 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
967 ++NumElimCmp;
968 Changed = true;
969 DeadInsts.push_back(ICmp);
972 void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
973 Value *IVOperand,
974 bool IsSigned) {
975 // We're only interested in the case where we know something about
976 // the numerator.
977 if (IVOperand != Rem->getOperand(0))
978 return;
980 // Get the SCEVs for the ICmp operands.
981 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
982 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
984 // Simplify unnecessary loops away.
985 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
986 S = SE->getSCEVAtScope(S, ICmpLoop);
987 X = SE->getSCEVAtScope(X, ICmpLoop);
989 // i % n --> i if i is in [0,n).
990 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
991 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
992 S, X))
993 Rem->replaceAllUsesWith(Rem->getOperand(0));
994 else {
995 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
996 const SCEV *LessOne =
997 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
998 if (IsSigned && !SE->isKnownNonNegative(LessOne))
999 return;
1001 if (!SE->isKnownPredicate(IsSigned ?
1002 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1003 LessOne, X))
1004 return;
1006 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
1007 Rem->getOperand(0), Rem->getOperand(1),
1008 "tmp");
1009 SelectInst *Sel =
1010 SelectInst::Create(ICmp,
1011 ConstantInt::get(Rem->getType(), 0),
1012 Rem->getOperand(0), "tmp", Rem);
1013 Rem->replaceAllUsesWith(Sel);
1016 // Inform IVUsers about the new users.
1017 if (IU) {
1018 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
1019 IU->AddUsersIfInteresting(I);
1021 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
1022 ++NumElimRem;
1023 Changed = true;
1024 DeadInsts.push_back(Rem);
1027 /// EliminateIVUser - Eliminate an operation that consumes a simple IV and has
1028 /// no observable side-effect given the range of IV values.
1029 bool IndVarSimplify::EliminateIVUser(Instruction *UseInst,
1030 Instruction *IVOperand) {
1031 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
1032 EliminateIVComparison(ICmp, IVOperand);
1033 return true;
1035 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
1036 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
1037 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
1038 EliminateIVRemainder(Rem, IVOperand, IsSigned);
1039 return true;
1043 // Eliminate any operation that SCEV can prove is an identity function.
1044 if (!SE->isSCEVable(UseInst->getType()) ||
1045 (UseInst->getType() != IVOperand->getType()) ||
1046 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
1047 return false;
1049 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
1051 UseInst->replaceAllUsesWith(IVOperand);
1052 ++NumElimIdentity;
1053 Changed = true;
1054 DeadInsts.push_back(UseInst);
1055 return true;
1058 /// pushIVUsers - Add all uses of Def to the current IV's worklist.
1060 static void pushIVUsers(
1061 Instruction *Def,
1062 SmallPtrSet<Instruction*,16> &Simplified,
1063 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
1065 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
1066 UI != E; ++UI) {
1067 Instruction *User = cast<Instruction>(*UI);
1069 // Avoid infinite or exponential worklist processing.
1070 // Also ensure unique worklist users.
1071 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
1072 // self edges first.
1073 if (User != Def && Simplified.insert(User))
1074 SimpleIVUsers.push_back(std::make_pair(User, Def));
1078 /// isSimpleIVUser - Return true if this instruction generates a simple SCEV
1079 /// expression in terms of that IV.
1081 /// This is similar to IVUsers' isInsteresting() but processes each instruction
1082 /// non-recursively when the operand is already known to be a simpleIVUser.
1084 bool IndVarSimplify::isSimpleIVUser(Instruction *I, const Loop *L) {
1085 if (!SE->isSCEVable(I->getType()))
1086 return false;
1088 // Get the symbolic expression for this instruction.
1089 const SCEV *S = SE->getSCEV(I);
1091 // We assume that terminators are not SCEVable.
1092 assert((!S || I != I->getParent()->getTerminator()) &&
1093 "can't fold terminators");
1095 // Only consider affine recurrences.
1096 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
1097 if (AR && AR->getLoop() == L)
1098 return true;
1100 return false;
1103 /// SimplifyIVUsersNoRewrite - Iteratively perform simplification on a worklist
1104 /// of IV users. Each successive simplification may push more users which may
1105 /// themselves be candidates for simplification.
1107 /// The "NoRewrite" algorithm does not require IVUsers analysis. Instead, it
1108 /// simplifies instructions in-place during analysis. Rather than rewriting
1109 /// induction variables bottom-up from their users, it transforms a chain of
1110 /// IVUsers top-down, updating the IR only when it encouters a clear
1111 /// optimization opportunitiy. A SCEVExpander "Rewriter" instance is still
1112 /// needed, but only used to generate a new IV (phi) of wider type for sign/zero
1113 /// extend elimination.
1115 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
1117 void IndVarSimplify::SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter) {
1118 std::map<PHINode *, WideIVInfo> WideIVMap;
1120 SmallVector<PHINode*, 8> LoopPhis;
1121 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1122 LoopPhis.push_back(cast<PHINode>(I));
1124 // Each round of simplification iterates through the SimplifyIVUsers worklist
1125 // for all current phis, then determines whether any IVs can be
1126 // widened. Widening adds new phis to LoopPhis, inducing another round of
1127 // simplification on the wide IVs.
1128 while (!LoopPhis.empty()) {
1129 // Evaluate as many IV expressions as possible before widening any IVs. This
1130 // forces SCEV to set no-wrap flags before evaluating sign/zero
1131 // extension. The first time SCEV attempts to normalize sign/zero extension,
1132 // the result becomes final. So for the most predictable results, we delay
1133 // evaluation of sign/zero extend evaluation until needed, and avoid running
1134 // other SCEV based analysis prior to SimplifyIVUsersNoRewrite.
1135 do {
1136 PHINode *CurrIV = LoopPhis.pop_back_val();
1138 // Information about sign/zero extensions of CurrIV.
1139 WideIVInfo WI;
1141 // Instructions processed by SimplifyIVUsers for CurrIV.
1142 SmallPtrSet<Instruction*,16> Simplified;
1144 // Use-def pairs if IV users waiting to be processed for CurrIV.
1145 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
1147 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
1148 // called multiple times for the same LoopPhi. This is the proper thing to
1149 // do for loop header phis that use each other.
1150 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
1152 while (!SimpleIVUsers.empty()) {
1153 Instruction *UseInst, *Operand;
1154 tie(UseInst, Operand) = SimpleIVUsers.pop_back_val();
1155 // Bypass back edges to avoid extra work.
1156 if (UseInst == CurrIV) continue;
1158 if (EliminateIVUser(UseInst, Operand)) {
1159 pushIVUsers(Operand, Simplified, SimpleIVUsers);
1160 continue;
1162 if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) {
1163 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
1164 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
1165 CollectExtend(Cast, IsSigned, WI, SE, TD);
1167 continue;
1169 if (isSimpleIVUser(UseInst, L)) {
1170 pushIVUsers(UseInst, Simplified, SimpleIVUsers);
1173 if (WI.WidestNativeType) {
1174 WideIVMap[CurrIV] = WI;
1176 } while(!LoopPhis.empty());
1178 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(),
1179 E = WideIVMap.end(); I != E; ++I) {
1180 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts);
1181 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1182 Changed = true;
1183 LoopPhis.push_back(WidePhi);
1186 WideIVMap.clear();
1190 /// SimplifyCongruentIVs - Check for congruent phis in this loop header and
1191 /// populate ExprToIVMap for use later.
1193 void IndVarSimplify::SimplifyCongruentIVs(Loop *L) {
1194 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1195 PHINode *Phi = cast<PHINode>(I);
1196 const SCEV *S = SE->getSCEV(Phi);
1197 ExprToIVMapTy::const_iterator Pos;
1198 bool Inserted;
1199 tie(Pos, Inserted) = ExprToIVMap.insert(std::make_pair(S, Phi));
1200 if (Inserted)
1201 continue;
1202 PHINode *OrigPhi = Pos->second;
1203 // Replacing the congruent phi is sufficient because acyclic redundancy
1204 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1205 // that a phi is congruent, it's almost certain to be the head of an IV
1206 // user cycle that is isomorphic with the original phi. So it's worth
1207 // eagerly cleaning up the common case of a single IV increment.
1208 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1209 Instruction *OrigInc =
1210 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1211 Instruction *IsomorphicInc =
1212 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1213 if (OrigInc != IsomorphicInc &&
1214 SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) &&
1215 HoistStep(OrigInc, IsomorphicInc, DT)) {
1216 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1217 << *IsomorphicInc << '\n');
1218 IsomorphicInc->replaceAllUsesWith(OrigInc);
1219 DeadInsts.push_back(IsomorphicInc);
1222 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1223 ++NumElimIV;
1224 Phi->replaceAllUsesWith(OrigPhi);
1225 DeadInsts.push_back(Phi);
1229 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
1230 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1231 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1232 // canonicalization can be a pessimization without LSR to "clean up"
1233 // afterwards.
1234 // - We depend on having a preheader; in particular,
1235 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1236 // and we're in trouble if we can't find the induction variable even when
1237 // we've manually inserted one.
1238 if (!L->isLoopSimplifyForm())
1239 return false;
1241 if (!DisableIVRewrite)
1242 IU = &getAnalysis<IVUsers>();
1243 LI = &getAnalysis<LoopInfo>();
1244 SE = &getAnalysis<ScalarEvolution>();
1245 DT = &getAnalysis<DominatorTree>();
1246 TD = getAnalysisIfAvailable<TargetData>();
1248 ExprToIVMap.clear();
1249 DeadInsts.clear();
1250 Changed = false;
1252 // If there are any floating-point recurrences, attempt to
1253 // transform them to use integer recurrences.
1254 RewriteNonIntegerIVs(L);
1256 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1258 // Create a rewriter object which we'll use to transform the code with.
1259 SCEVExpander Rewriter(*SE, "indvars");
1261 // Eliminate redundant IV users.
1263 // Simplification works best when run before other consumers of SCEV. We
1264 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
1265 // other expressions involving loop IVs have been evaluated. This helps SCEV
1266 // set no-wrap flags before normalizing sign/zero extension.
1267 if (DisableIVRewrite) {
1268 Rewriter.disableCanonicalMode();
1269 SimplifyIVUsersNoRewrite(L, Rewriter);
1272 // Check to see if this loop has a computable loop-invariant execution count.
1273 // If so, this means that we can compute the final value of any expressions
1274 // that are recurrent in the loop, and substitute the exit values from the
1275 // loop into any instructions outside of the loop that use the final values of
1276 // the current expressions.
1278 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1279 RewriteLoopExitValues(L, Rewriter);
1281 // Eliminate redundant IV users.
1282 if (!DisableIVRewrite)
1283 SimplifyIVUsers(Rewriter);
1285 // Eliminate redundant IV cycles and populate ExprToIVMap.
1286 // TODO: use ExprToIVMap to allow LFTR without canonical IVs
1287 if (DisableIVRewrite)
1288 SimplifyCongruentIVs(L);
1290 // Compute the type of the largest recurrence expression, and decide whether
1291 // a canonical induction variable should be inserted.
1292 const Type *LargestType = 0;
1293 bool NeedCannIV = false;
1294 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
1295 if (ExpandBECount) {
1296 // If we have a known trip count and a single exit block, we'll be
1297 // rewriting the loop exit test condition below, which requires a
1298 // canonical induction variable.
1299 NeedCannIV = true;
1300 const Type *Ty = BackedgeTakenCount->getType();
1301 if (DisableIVRewrite) {
1302 // In this mode, SimplifyIVUsers may have already widened the IV used by
1303 // the backedge test and inserted a Trunc on the compare's operand. Get
1304 // the wider type to avoid creating a redundant narrow IV only used by the
1305 // loop test.
1306 LargestType = getBackedgeIVType(L);
1308 if (!LargestType ||
1309 SE->getTypeSizeInBits(Ty) >
1310 SE->getTypeSizeInBits(LargestType))
1311 LargestType = SE->getEffectiveSCEVType(Ty);
1313 if (!DisableIVRewrite) {
1314 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
1315 NeedCannIV = true;
1316 const Type *Ty =
1317 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
1318 if (!LargestType ||
1319 SE->getTypeSizeInBits(Ty) >
1320 SE->getTypeSizeInBits(LargestType))
1321 LargestType = Ty;
1325 // Now that we know the largest of the induction variable expressions
1326 // in this loop, insert a canonical induction variable of the largest size.
1327 PHINode *IndVar = 0;
1328 if (NeedCannIV) {
1329 // Check to see if the loop already has any canonical-looking induction
1330 // variables. If any are present and wider than the planned canonical
1331 // induction variable, temporarily remove them, so that the Rewriter
1332 // doesn't attempt to reuse them.
1333 SmallVector<PHINode *, 2> OldCannIVs;
1334 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
1335 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
1336 SE->getTypeSizeInBits(LargestType))
1337 OldCannIV->removeFromParent();
1338 else
1339 break;
1340 OldCannIVs.push_back(OldCannIV);
1343 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
1345 ++NumInserted;
1346 Changed = true;
1347 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
1349 // Now that the official induction variable is established, reinsert
1350 // any old canonical-looking variables after it so that the IR remains
1351 // consistent. They will be deleted as part of the dead-PHI deletion at
1352 // the end of the pass.
1353 while (!OldCannIVs.empty()) {
1354 PHINode *OldCannIV = OldCannIVs.pop_back_val();
1355 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
1359 // If we have a trip count expression, rewrite the loop's exit condition
1360 // using it. We can currently only handle loops with a single exit.
1361 ICmpInst *NewICmp = 0;
1362 if (ExpandBECount) {
1363 assert(canExpandBackedgeTakenCount(L, SE) &&
1364 "canonical IV disrupted BackedgeTaken expansion");
1365 assert(NeedCannIV &&
1366 "LinearFunctionTestReplace requires a canonical induction variable");
1367 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
1368 Rewriter);
1370 // Rewrite IV-derived expressions.
1371 if (!DisableIVRewrite)
1372 RewriteIVExpressions(L, Rewriter);
1374 // Clear the rewriter cache, because values that are in the rewriter's cache
1375 // can be deleted in the loop below, causing the AssertingVH in the cache to
1376 // trigger.
1377 Rewriter.clear();
1378 ExprToIVMap.clear();
1380 // Now that we're done iterating through lists, clean up any instructions
1381 // which are now dead.
1382 while (!DeadInsts.empty())
1383 if (Instruction *Inst =
1384 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1385 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1387 // The Rewriter may not be used from this point on.
1389 // Loop-invariant instructions in the preheader that aren't used in the
1390 // loop may be sunk below the loop to reduce register pressure.
1391 SinkUnusedInvariants(L);
1393 // For completeness, inform IVUsers of the IV use in the newly-created
1394 // loop exit test instruction.
1395 if (NewICmp && IU)
1396 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
1398 // Clean up dead instructions.
1399 Changed |= DeleteDeadPHIs(L->getHeader());
1400 // Check a post-condition.
1401 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
1402 return Changed;
1405 // FIXME: It is an extremely bad idea to indvar substitute anything more
1406 // complex than affine induction variables. Doing so will put expensive
1407 // polynomial evaluations inside of the loop, and the str reduction pass
1408 // currently can only reduce affine polynomials. For now just disable
1409 // indvar subst on anything more complex than an affine addrec, unless
1410 // it can be expanded to a trivial value.
1411 static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
1412 // Loop-invariant values are safe.
1413 if (SE->isLoopInvariant(S, L)) return true;
1415 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
1416 // to transform them into efficient code.
1417 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
1418 return AR->isAffine();
1420 // An add is safe it all its operands are safe.
1421 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
1422 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
1423 E = Commutative->op_end(); I != E; ++I)
1424 if (!isSafe(*I, L, SE)) return false;
1425 return true;
1428 // A cast is safe if its operand is.
1429 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
1430 return isSafe(C->getOperand(), L, SE);
1432 // A udiv is safe if its operands are.
1433 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
1434 return isSafe(UD->getLHS(), L, SE) &&
1435 isSafe(UD->getRHS(), L, SE);
1437 // SCEVUnknown is always safe.
1438 if (isa<SCEVUnknown>(S))
1439 return true;
1441 // Nothing else is safe.
1442 return false;
1445 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
1446 // Rewrite all induction variable expressions in terms of the canonical
1447 // induction variable.
1449 // If there were induction variables of other sizes or offsets, manually
1450 // add the offsets to the primary induction variable and cast, avoiding
1451 // the need for the code evaluation methods to insert induction variables
1452 // of different sizes.
1453 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
1454 Value *Op = UI->getOperandValToReplace();
1455 const Type *UseTy = Op->getType();
1456 Instruction *User = UI->getUser();
1458 // Compute the final addrec to expand into code.
1459 const SCEV *AR = IU->getReplacementExpr(*UI);
1461 // Evaluate the expression out of the loop, if possible.
1462 if (!L->contains(UI->getUser())) {
1463 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
1464 if (SE->isLoopInvariant(ExitVal, L))
1465 AR = ExitVal;
1468 // FIXME: It is an extremely bad idea to indvar substitute anything more
1469 // complex than affine induction variables. Doing so will put expensive
1470 // polynomial evaluations inside of the loop, and the str reduction pass
1471 // currently can only reduce affine polynomials. For now just disable
1472 // indvar subst on anything more complex than an affine addrec, unless
1473 // it can be expanded to a trivial value.
1474 if (!isSafe(AR, L, SE))
1475 continue;
1477 // Determine the insertion point for this user. By default, insert
1478 // immediately before the user. The SCEVExpander class will automatically
1479 // hoist loop invariants out of the loop. For PHI nodes, there may be
1480 // multiple uses, so compute the nearest common dominator for the
1481 // incoming blocks.
1482 Instruction *InsertPt = User;
1483 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
1484 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
1485 if (PHI->getIncomingValue(i) == Op) {
1486 if (InsertPt == User)
1487 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
1488 else
1489 InsertPt =
1490 DT->findNearestCommonDominator(InsertPt->getParent(),
1491 PHI->getIncomingBlock(i))
1492 ->getTerminator();
1495 // Now expand it into actual Instructions and patch it into place.
1496 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
1498 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
1499 << " into = " << *NewVal << "\n");
1501 if (!isValidRewrite(Op, NewVal)) {
1502 DeadInsts.push_back(NewVal);
1503 continue;
1505 // Inform ScalarEvolution that this value is changing. The change doesn't
1506 // affect its value, but it does potentially affect which use lists the
1507 // value will be on after the replacement, which affects ScalarEvolution's
1508 // ability to walk use lists and drop dangling pointers when a value is
1509 // deleted.
1510 SE->forgetValue(User);
1512 // Patch the new value into place.
1513 if (Op->hasName())
1514 NewVal->takeName(Op);
1515 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
1516 NewValI->setDebugLoc(User->getDebugLoc());
1517 User->replaceUsesOfWith(Op, NewVal);
1518 UI->setOperandValToReplace(NewVal);
1520 ++NumRemoved;
1521 Changed = true;
1523 // The old value may be dead now.
1524 DeadInsts.push_back(Op);
1528 /// If there's a single exit block, sink any loop-invariant values that
1529 /// were defined in the preheader but not used inside the loop into the
1530 /// exit block to reduce register pressure in the loop.
1531 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1532 BasicBlock *ExitBlock = L->getExitBlock();
1533 if (!ExitBlock) return;
1535 BasicBlock *Preheader = L->getLoopPreheader();
1536 if (!Preheader) return;
1538 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
1539 BasicBlock::iterator I = Preheader->getTerminator();
1540 while (I != Preheader->begin()) {
1541 --I;
1542 // New instructions were inserted at the end of the preheader.
1543 if (isa<PHINode>(I))
1544 break;
1546 // Don't move instructions which might have side effects, since the side
1547 // effects need to complete before instructions inside the loop. Also don't
1548 // move instructions which might read memory, since the loop may modify
1549 // memory. Note that it's okay if the instruction might have undefined
1550 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1551 // block.
1552 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
1553 continue;
1555 // Skip debug info intrinsics.
1556 if (isa<DbgInfoIntrinsic>(I))
1557 continue;
1559 // Don't sink static AllocaInsts out of the entry block, which would
1560 // turn them into dynamic allocas!
1561 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1562 if (AI->isStaticAlloca())
1563 continue;
1565 // Determine if there is a use in or before the loop (direct or
1566 // otherwise).
1567 bool UsedInLoop = false;
1568 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1569 UI != UE; ++UI) {
1570 User *U = *UI;
1571 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1572 if (PHINode *P = dyn_cast<PHINode>(U)) {
1573 unsigned i =
1574 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1575 UseBB = P->getIncomingBlock(i);
1577 if (UseBB == Preheader || L->contains(UseBB)) {
1578 UsedInLoop = true;
1579 break;
1583 // If there is, the def must remain in the preheader.
1584 if (UsedInLoop)
1585 continue;
1587 // Otherwise, sink it to the exit block.
1588 Instruction *ToMove = I;
1589 bool Done = false;
1591 if (I != Preheader->begin()) {
1592 // Skip debug info intrinsics.
1593 do {
1594 --I;
1595 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1597 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1598 Done = true;
1599 } else {
1600 Done = true;
1603 ToMove->moveBefore(InsertPt);
1604 if (Done) break;
1605 InsertPt = ToMove;
1609 /// ConvertToSInt - Convert APF to an integer, if possible.
1610 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
1611 bool isExact = false;
1612 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
1613 return false;
1614 // See if we can convert this to an int64_t
1615 uint64_t UIntVal;
1616 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
1617 &isExact) != APFloat::opOK || !isExact)
1618 return false;
1619 IntVal = UIntVal;
1620 return true;
1623 /// HandleFloatingPointIV - If the loop has floating induction variable
1624 /// then insert corresponding integer induction variable if possible.
1625 /// For example,
1626 /// for(double i = 0; i < 10000; ++i)
1627 /// bar(i)
1628 /// is converted into
1629 /// for(int i = 0; i < 10000; ++i)
1630 /// bar((double)i);
1632 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
1633 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1634 unsigned BackEdge = IncomingEdge^1;
1636 // Check incoming value.
1637 ConstantFP *InitValueVal =
1638 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
1640 int64_t InitValue;
1641 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
1642 return;
1644 // Check IV increment. Reject this PN if increment operation is not
1645 // an add or increment value can not be represented by an integer.
1646 BinaryOperator *Incr =
1647 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
1648 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
1650 // If this is not an add of the PHI with a constantfp, or if the constant fp
1651 // is not an integer, bail out.
1652 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
1653 int64_t IncValue;
1654 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
1655 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
1656 return;
1658 // Check Incr uses. One user is PN and the other user is an exit condition
1659 // used by the conditional terminator.
1660 Value::use_iterator IncrUse = Incr->use_begin();
1661 Instruction *U1 = cast<Instruction>(*IncrUse++);
1662 if (IncrUse == Incr->use_end()) return;
1663 Instruction *U2 = cast<Instruction>(*IncrUse++);
1664 if (IncrUse != Incr->use_end()) return;
1666 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
1667 // only used by a branch, we can't transform it.
1668 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
1669 if (!Compare)
1670 Compare = dyn_cast<FCmpInst>(U2);
1671 if (Compare == 0 || !Compare->hasOneUse() ||
1672 !isa<BranchInst>(Compare->use_back()))
1673 return;
1675 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
1677 // We need to verify that the branch actually controls the iteration count
1678 // of the loop. If not, the new IV can overflow and no one will notice.
1679 // The branch block must be in the loop and one of the successors must be out
1680 // of the loop.
1681 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
1682 if (!L->contains(TheBr->getParent()) ||
1683 (L->contains(TheBr->getSuccessor(0)) &&
1684 L->contains(TheBr->getSuccessor(1))))
1685 return;
1688 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
1689 // transform it.
1690 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
1691 int64_t ExitValue;
1692 if (ExitValueVal == 0 ||
1693 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
1694 return;
1696 // Find new predicate for integer comparison.
1697 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
1698 switch (Compare->getPredicate()) {
1699 default: return; // Unknown comparison.
1700 case CmpInst::FCMP_OEQ:
1701 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
1702 case CmpInst::FCMP_ONE:
1703 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
1704 case CmpInst::FCMP_OGT:
1705 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
1706 case CmpInst::FCMP_OGE:
1707 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
1708 case CmpInst::FCMP_OLT:
1709 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
1710 case CmpInst::FCMP_OLE:
1711 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
1714 // We convert the floating point induction variable to a signed i32 value if
1715 // we can. This is only safe if the comparison will not overflow in a way
1716 // that won't be trapped by the integer equivalent operations. Check for this
1717 // now.
1718 // TODO: We could use i64 if it is native and the range requires it.
1720 // The start/stride/exit values must all fit in signed i32.
1721 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
1722 return;
1724 // If not actually striding (add x, 0.0), avoid touching the code.
1725 if (IncValue == 0)
1726 return;
1728 // Positive and negative strides have different safety conditions.
1729 if (IncValue > 0) {
1730 // If we have a positive stride, we require the init to be less than the
1731 // exit value and an equality or less than comparison.
1732 if (InitValue >= ExitValue ||
1733 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
1734 return;
1736 uint32_t Range = uint32_t(ExitValue-InitValue);
1737 if (NewPred == CmpInst::ICMP_SLE) {
1738 // Normalize SLE -> SLT, check for infinite loop.
1739 if (++Range == 0) return; // Range overflows.
1742 unsigned Leftover = Range % uint32_t(IncValue);
1744 // If this is an equality comparison, we require that the strided value
1745 // exactly land on the exit value, otherwise the IV condition will wrap
1746 // around and do things the fp IV wouldn't.
1747 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1748 Leftover != 0)
1749 return;
1751 // If the stride would wrap around the i32 before exiting, we can't
1752 // transform the IV.
1753 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
1754 return;
1756 } else {
1757 // If we have a negative stride, we require the init to be greater than the
1758 // exit value and an equality or greater than comparison.
1759 if (InitValue >= ExitValue ||
1760 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
1761 return;
1763 uint32_t Range = uint32_t(InitValue-ExitValue);
1764 if (NewPred == CmpInst::ICMP_SGE) {
1765 // Normalize SGE -> SGT, check for infinite loop.
1766 if (++Range == 0) return; // Range overflows.
1769 unsigned Leftover = Range % uint32_t(-IncValue);
1771 // If this is an equality comparison, we require that the strided value
1772 // exactly land on the exit value, otherwise the IV condition will wrap
1773 // around and do things the fp IV wouldn't.
1774 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1775 Leftover != 0)
1776 return;
1778 // If the stride would wrap around the i32 before exiting, we can't
1779 // transform the IV.
1780 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
1781 return;
1784 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
1786 // Insert new integer induction variable.
1787 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
1788 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
1789 PN->getIncomingBlock(IncomingEdge));
1791 Value *NewAdd =
1792 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
1793 Incr->getName()+".int", Incr);
1794 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
1796 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1797 ConstantInt::get(Int32Ty, ExitValue),
1798 Compare->getName());
1800 // In the following deletions, PN may become dead and may be deleted.
1801 // Use a WeakVH to observe whether this happens.
1802 WeakVH WeakPH = PN;
1804 // Delete the old floating point exit comparison. The branch starts using the
1805 // new comparison.
1806 NewCompare->takeName(Compare);
1807 Compare->replaceAllUsesWith(NewCompare);
1808 RecursivelyDeleteTriviallyDeadInstructions(Compare);
1810 // Delete the old floating point increment.
1811 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
1812 RecursivelyDeleteTriviallyDeadInstructions(Incr);
1814 // If the FP induction variable still has uses, this is because something else
1815 // in the loop uses its value. In order to canonicalize the induction
1816 // variable, we chose to eliminate the IV and rewrite it in terms of an
1817 // int->fp cast.
1819 // We give preference to sitofp over uitofp because it is faster on most
1820 // platforms.
1821 if (WeakPH) {
1822 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1823 PN->getParent()->getFirstNonPHI());
1824 PN->replaceAllUsesWith(Conv);
1825 RecursivelyDeleteTriviallyDeadInstructions(PN);
1828 // Add a new IVUsers entry for the newly-created integer PHI.
1829 if (IU)
1830 IU->AddUsersIfInteresting(NewPHI);