Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 1 | //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
John Criswell | b576c94 | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | 4ee451d | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
John Criswell | b576c94 | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 9 | // |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 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. |
| 13 | // |
Reid Spencer | 47a53ac | 2006-08-18 09:01:07 +0000 | [diff] [blame] | 14 | // This transformation makes the following changes to each loop with an |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 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. |
Dan Gohman | ea73f3c | 2009-06-14 22:38:41 +0000 | [diff] [blame] | 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. |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 24 | // |
| 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. |
| 35 | // |
| 36 | // This transformation should be followed by strength reduction after all of the |
Dan Gohman | c2c4cbf | 2009-05-19 20:38:47 +0000 | [diff] [blame] | 37 | // desired loop transformations have been performed. |
Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 38 | // |
| 39 | //===----------------------------------------------------------------------===// |
| 40 | |
Chris Lattner | 0e5f499 | 2006-12-19 21:40:18 +0000 | [diff] [blame] | 41 | #define DEBUG_TYPE "indvars" |
Chris Lattner | 022103b | 2002-05-07 20:03:00 +0000 | [diff] [blame] | 42 | #include "llvm/Transforms/Scalar.h" |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 43 | #include "llvm/BasicBlock.h" |
Chris Lattner | 59fdaee | 2004-04-15 15:21:43 +0000 | [diff] [blame] | 44 | #include "llvm/Constants.h" |
Chris Lattner | 18b3c97 | 2003-12-22 05:02:01 +0000 | [diff] [blame] | 45 | #include "llvm/Instructions.h" |
Devang Patel | 7b9f6b1 | 2010-03-15 22:23:03 +0000 | [diff] [blame] | 46 | #include "llvm/IntrinsicInst.h" |
Owen Anderson | d672ecb | 2009-07-03 00:17:18 +0000 | [diff] [blame] | 47 | #include "llvm/LLVMContext.h" |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 48 | #include "llvm/Type.h" |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 49 | #include "llvm/Analysis/Dominators.h" |
| 50 | #include "llvm/Analysis/IVUsers.h" |
Nate Begeman | 36f891b | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 51 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
John Criswell | 47df12d | 2003-12-18 17:19:19 +0000 | [diff] [blame] | 52 | #include "llvm/Analysis/LoopInfo.h" |
Devang Patel | 5ee9997 | 2007-03-07 06:39:01 +0000 | [diff] [blame] | 53 | #include "llvm/Analysis/LoopPass.h" |
Chris Lattner | 455889a | 2002-02-12 22:39:50 +0000 | [diff] [blame] | 54 | #include "llvm/Support/CFG.h" |
Andrew Trick | 56caa09 | 2011-06-28 03:01:46 +0000 | [diff] [blame] | 55 | #include "llvm/Support/CommandLine.h" |
Chris Lattner | ee4f13a | 2007-01-07 01:14:12 +0000 | [diff] [blame] | 56 | #include "llvm/Support/Debug.h" |
Chris Lattner | bdff548 | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 57 | #include "llvm/Support/raw_ostream.h" |
John Criswell | 47df12d | 2003-12-18 17:19:19 +0000 | [diff] [blame] | 58 | #include "llvm/Transforms/Utils/Local.h" |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 59 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 60 | #include "llvm/Target/TargetData.h" |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 61 | #include "llvm/ADT/DenseMap.h" |
Reid Spencer | a54b7cb | 2007-01-12 07:05:14 +0000 | [diff] [blame] | 62 | #include "llvm/ADT/SmallVector.h" |
Reid Spencer | 551ccae | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 63 | #include "llvm/ADT/Statistic.h" |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 64 | #include "llvm/ADT/STLExtras.h" |
John Criswell | 47df12d | 2003-12-18 17:19:19 +0000 | [diff] [blame] | 65 | using namespace llvm; |
Brian Gaeke | d0fde30 | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 66 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 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"); |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 76 | STATISTIC(NumElimIV , "Number of congruent IVs eliminated"); |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 77 | |
Andrew Trick | 56caa09 | 2011-06-28 03:01:46 +0000 | [diff] [blame] | 78 | static cl::opt<bool> DisableIVRewrite( |
| 79 | "disable-iv-rewrite", cl::Hidden, |
| 80 | cl::desc("Disable canonical induction variable rewriting")); |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 81 | |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 82 | // Temporary flag for use with -disable-iv-rewrite to force a canonical IV for |
| 83 | // LFTR purposes. |
| 84 | static cl::opt<bool> ForceLFTR( |
| 85 | "force-lftr", cl::Hidden, |
| 86 | cl::desc("Enable forced linear function test replacement")); |
| 87 | |
Chris Lattner | 0e5f499 | 2006-12-19 21:40:18 +0000 | [diff] [blame] | 88 | namespace { |
Chris Lattner | 3e8b663 | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 89 | class IndVarSimplify : public LoopPass { |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 90 | IVUsers *IU; |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 91 | LoopInfo *LI; |
| 92 | ScalarEvolution *SE; |
Dan Gohman | de53dc0 | 2009-06-27 05:16:57 +0000 | [diff] [blame] | 93 | DominatorTree *DT; |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 94 | TargetData *TD; |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 95 | |
Andrew Trick | b12a754 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 96 | SmallVector<WeakVH, 16> DeadInsts; |
Chris Lattner | 15cad75 | 2003-12-23 07:47:09 +0000 | [diff] [blame] | 97 | bool Changed; |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 98 | public: |
Devang Patel | 794fd75 | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 99 | |
Dan Gohman | 5668cf7 | 2009-07-15 01:26:32 +0000 | [diff] [blame] | 100 | static char ID; // Pass identification, replacement for typeid |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 101 | IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0), |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 102 | Changed(false) { |
Owen Anderson | 081c34b | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 103 | initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry()); |
| 104 | } |
Devang Patel | 794fd75 | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 105 | |
Dan Gohman | 5668cf7 | 2009-07-15 01:26:32 +0000 | [diff] [blame] | 106 | virtual bool runOnLoop(Loop *L, LPPassManager &LPM); |
Dan Gohman | 60f8a63 | 2009-02-17 20:49:49 +0000 | [diff] [blame] | 107 | |
Dan Gohman | 5668cf7 | 2009-07-15 01:26:32 +0000 | [diff] [blame] | 108 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 109 | AU.addRequired<DominatorTree>(); |
| 110 | AU.addRequired<LoopInfo>(); |
| 111 | AU.addRequired<ScalarEvolution>(); |
| 112 | AU.addRequiredID(LoopSimplifyID); |
| 113 | AU.addRequiredID(LCSSAID); |
Andrew Trick | 56caa09 | 2011-06-28 03:01:46 +0000 | [diff] [blame] | 114 | if (!DisableIVRewrite) |
| 115 | AU.addRequired<IVUsers>(); |
Dan Gohman | 5668cf7 | 2009-07-15 01:26:32 +0000 | [diff] [blame] | 116 | AU.addPreserved<ScalarEvolution>(); |
| 117 | AU.addPreservedID(LoopSimplifyID); |
| 118 | AU.addPreservedID(LCSSAID); |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 119 | if (!DisableIVRewrite) |
| 120 | AU.addPreserved<IVUsers>(); |
Dan Gohman | 5668cf7 | 2009-07-15 01:26:32 +0000 | [diff] [blame] | 121 | AU.setPreservesCFG(); |
| 122 | } |
Chris Lattner | 15cad75 | 2003-12-23 07:47:09 +0000 | [diff] [blame] | 123 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 124 | private: |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 125 | virtual void releaseMemory() { |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 126 | DeadInsts.clear(); |
| 127 | } |
| 128 | |
Andrew Trick | b12a754 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 129 | bool isValidRewrite(Value *FromVal, Value *ToVal); |
Devang Patel | 5ee9997 | 2007-03-07 06:39:01 +0000 | [diff] [blame] | 130 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 131 | void HandleFloatingPointIV(Loop *L, PHINode *PH); |
| 132 | void RewriteNonIntegerIVs(Loop *L); |
| 133 | |
| 134 | void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter); |
| 135 | |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 136 | void SimplifyIVUsers(SCEVExpander &Rewriter); |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 137 | void SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter); |
| 138 | |
| 139 | bool EliminateIVUser(Instruction *UseInst, Instruction *IVOperand); |
Andrew Trick | aeee461 | 2011-05-12 00:04:28 +0000 | [diff] [blame] | 140 | void EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand); |
| 141 | void EliminateIVRemainder(BinaryOperator *Rem, |
| 142 | Value *IVOperand, |
Andrew Trick | 4417e53 | 2011-06-21 15:43:52 +0000 | [diff] [blame] | 143 | bool IsSigned); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 144 | |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 145 | void SimplifyCongruentIVs(Loop *L); |
| 146 | |
Dan Gohman | 454d26d | 2010-02-22 04:11:59 +0000 | [diff] [blame] | 147 | void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter); |
Devang Patel | d22a849 | 2008-09-09 21:41:07 +0000 | [diff] [blame] | 148 | |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 149 | Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount, |
| 150 | PHINode *IndVar, SCEVExpander &Rewriter); |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 151 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 152 | void SinkUnusedInvariants(Loop *L); |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 153 | }; |
Chris Lattner | 5e76140 | 2002-09-10 05:24:05 +0000 | [diff] [blame] | 154 | } |
Chris Lattner | 394437f | 2001-12-04 04:32:29 +0000 | [diff] [blame] | 155 | |
Dan Gohman | 844731a | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 156 | char IndVarSimplify::ID = 0; |
Owen Anderson | 2ab36d3 | 2010-10-12 19:48:12 +0000 | [diff] [blame] | 157 | INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars", |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 158 | "Induction Variable Simplification", false, false) |
Owen Anderson | 2ab36d3 | 2010-10-12 19:48:12 +0000 | [diff] [blame] | 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", |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 166 | "Induction Variable Simplification", false, false) |
Dan Gohman | 844731a | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 167 | |
Daniel Dunbar | 394f044 | 2008-10-22 23:32:42 +0000 | [diff] [blame] | 168 | Pass *llvm::createIndVarSimplifyPass() { |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 169 | return new IndVarSimplify(); |
Chris Lattner | 394437f | 2001-12-04 04:32:29 +0000 | [diff] [blame] | 170 | } |
| 171 | |
Andrew Trick | b12a754 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 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. |
| 184 | // |
| 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(); |
| 191 | } |
| 192 | if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) { |
| 193 | ToPtr = GEP->getPointerOperand(); |
| 194 | } |
| 195 | if (FromPtr != FromVal || ToPtr != ToVal) { |
| 196 | // Quickly check the common case |
| 197 | if (FromPtr == ToPtr) |
| 198 | return true; |
| 199 | |
| 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; |
| 210 | |
| 211 | DEBUG(dbgs() << "INDVARS: GEP rewrite bail out " |
| 212 | << *FromBase << " != " << *ToBase << "\n"); |
| 213 | |
| 214 | return false; |
| 215 | } |
| 216 | return true; |
| 217 | } |
| 218 | |
Andrew Trick | 86c9814 | 2011-07-20 05:32:06 +0000 | [diff] [blame] | 219 | /// Determine the insertion point for this user. By default, insert immediately |
| 220 | /// before the user. SCEVExpander or LICM will hoist loop invariants out of the |
| 221 | /// loop. For PHI nodes, there may be multiple uses, so compute the nearest |
| 222 | /// common dominator for the incoming blocks. |
| 223 | static Instruction *getInsertPointForUses(Instruction *User, Value *Def, |
| 224 | DominatorTree *DT) { |
| 225 | PHINode *PHI = dyn_cast<PHINode>(User); |
| 226 | if (!PHI) |
| 227 | return User; |
| 228 | |
| 229 | Instruction *InsertPt = 0; |
| 230 | for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) { |
| 231 | if (PHI->getIncomingValue(i) != Def) |
| 232 | continue; |
| 233 | |
| 234 | BasicBlock *InsertBB = PHI->getIncomingBlock(i); |
| 235 | if (!InsertPt) { |
| 236 | InsertPt = InsertBB->getTerminator(); |
| 237 | continue; |
| 238 | } |
| 239 | InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB); |
| 240 | InsertPt = InsertBB->getTerminator(); |
| 241 | } |
| 242 | assert(InsertPt && "Missing phi operand"); |
Jay Foad | 626f52d | 2011-07-20 08:15:21 +0000 | [diff] [blame] | 243 | assert((!isa<Instruction>(Def) || |
| 244 | DT->dominates(cast<Instruction>(Def), InsertPt)) && |
Andrew Trick | 86c9814 | 2011-07-20 05:32:06 +0000 | [diff] [blame] | 245 | "def does not dominate all uses"); |
| 246 | return InsertPt; |
| 247 | } |
| 248 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 249 | //===----------------------------------------------------------------------===// |
| 250 | // RewriteNonIntegerIVs and helpers. Prefer integer IVs. |
| 251 | //===----------------------------------------------------------------------===// |
Andrew Trick | 4dfdf24 | 2011-05-03 22:24:10 +0000 | [diff] [blame] | 252 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 253 | /// ConvertToSInt - Convert APF to an integer, if possible. |
| 254 | static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) { |
| 255 | bool isExact = false; |
| 256 | if (&APF.getSemantics() == &APFloat::PPCDoubleDouble) |
Andrew Trick | 4dfdf24 | 2011-05-03 22:24:10 +0000 | [diff] [blame] | 257 | return false; |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 258 | // See if we can convert this to an int64_t |
| 259 | uint64_t UIntVal; |
| 260 | if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero, |
| 261 | &isExact) != APFloat::opOK || !isExact) |
Andrew Trick | 4dfdf24 | 2011-05-03 22:24:10 +0000 | [diff] [blame] | 262 | return false; |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 263 | IntVal = UIntVal; |
Andrew Trick | 4dfdf24 | 2011-05-03 22:24:10 +0000 | [diff] [blame] | 264 | return true; |
| 265 | } |
| 266 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 267 | /// HandleFloatingPointIV - If the loop has floating induction variable |
| 268 | /// then insert corresponding integer induction variable if possible. |
| 269 | /// For example, |
| 270 | /// for(double i = 0; i < 10000; ++i) |
| 271 | /// bar(i) |
| 272 | /// is converted into |
| 273 | /// for(int i = 0; i < 10000; ++i) |
| 274 | /// bar((double)i); |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 275 | /// |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 276 | void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) { |
| 277 | unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); |
| 278 | unsigned BackEdge = IncomingEdge^1; |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 279 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 280 | // Check incoming value. |
| 281 | ConstantFP *InitValueVal = |
| 282 | dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge)); |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 283 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 284 | int64_t InitValue; |
| 285 | if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue)) |
| 286 | return; |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 287 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 288 | // Check IV increment. Reject this PN if increment operation is not |
| 289 | // an add or increment value can not be represented by an integer. |
| 290 | BinaryOperator *Incr = |
| 291 | dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge)); |
| 292 | if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return; |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 293 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 294 | // If this is not an add of the PHI with a constantfp, or if the constant fp |
| 295 | // is not an integer, bail out. |
| 296 | ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1)); |
| 297 | int64_t IncValue; |
| 298 | if (IncValueVal == 0 || Incr->getOperand(0) != PN || |
| 299 | !ConvertToSInt(IncValueVal->getValueAPF(), IncValue)) |
| 300 | return; |
| 301 | |
| 302 | // Check Incr uses. One user is PN and the other user is an exit condition |
| 303 | // used by the conditional terminator. |
| 304 | Value::use_iterator IncrUse = Incr->use_begin(); |
| 305 | Instruction *U1 = cast<Instruction>(*IncrUse++); |
| 306 | if (IncrUse == Incr->use_end()) return; |
| 307 | Instruction *U2 = cast<Instruction>(*IncrUse++); |
| 308 | if (IncrUse != Incr->use_end()) return; |
| 309 | |
| 310 | // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't |
| 311 | // only used by a branch, we can't transform it. |
| 312 | FCmpInst *Compare = dyn_cast<FCmpInst>(U1); |
| 313 | if (!Compare) |
| 314 | Compare = dyn_cast<FCmpInst>(U2); |
| 315 | if (Compare == 0 || !Compare->hasOneUse() || |
| 316 | !isa<BranchInst>(Compare->use_back())) |
| 317 | return; |
| 318 | |
| 319 | BranchInst *TheBr = cast<BranchInst>(Compare->use_back()); |
| 320 | |
| 321 | // We need to verify that the branch actually controls the iteration count |
| 322 | // of the loop. If not, the new IV can overflow and no one will notice. |
| 323 | // The branch block must be in the loop and one of the successors must be out |
| 324 | // of the loop. |
| 325 | assert(TheBr->isConditional() && "Can't use fcmp if not conditional"); |
| 326 | if (!L->contains(TheBr->getParent()) || |
| 327 | (L->contains(TheBr->getSuccessor(0)) && |
| 328 | L->contains(TheBr->getSuccessor(1)))) |
| 329 | return; |
| 330 | |
| 331 | |
| 332 | // If it isn't a comparison with an integer-as-fp (the exit value), we can't |
| 333 | // transform it. |
| 334 | ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1)); |
| 335 | int64_t ExitValue; |
| 336 | if (ExitValueVal == 0 || |
| 337 | !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue)) |
| 338 | return; |
| 339 | |
| 340 | // Find new predicate for integer comparison. |
| 341 | CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE; |
| 342 | switch (Compare->getPredicate()) { |
| 343 | default: return; // Unknown comparison. |
| 344 | case CmpInst::FCMP_OEQ: |
| 345 | case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break; |
| 346 | case CmpInst::FCMP_ONE: |
| 347 | case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break; |
| 348 | case CmpInst::FCMP_OGT: |
| 349 | case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break; |
| 350 | case CmpInst::FCMP_OGE: |
| 351 | case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break; |
| 352 | case CmpInst::FCMP_OLT: |
| 353 | case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break; |
| 354 | case CmpInst::FCMP_OLE: |
| 355 | case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break; |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 356 | } |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 357 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 358 | // We convert the floating point induction variable to a signed i32 value if |
| 359 | // we can. This is only safe if the comparison will not overflow in a way |
| 360 | // that won't be trapped by the integer equivalent operations. Check for this |
| 361 | // now. |
| 362 | // TODO: We could use i64 if it is native and the range requires it. |
Dan Gohman | ca9b703 | 2010-04-12 21:13:43 +0000 | [diff] [blame] | 363 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 364 | // The start/stride/exit values must all fit in signed i32. |
| 365 | if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue)) |
| 366 | return; |
| 367 | |
| 368 | // If not actually striding (add x, 0.0), avoid touching the code. |
| 369 | if (IncValue == 0) |
| 370 | return; |
| 371 | |
| 372 | // Positive and negative strides have different safety conditions. |
| 373 | if (IncValue > 0) { |
| 374 | // If we have a positive stride, we require the init to be less than the |
| 375 | // exit value and an equality or less than comparison. |
| 376 | if (InitValue >= ExitValue || |
| 377 | NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE) |
| 378 | return; |
| 379 | |
| 380 | uint32_t Range = uint32_t(ExitValue-InitValue); |
| 381 | if (NewPred == CmpInst::ICMP_SLE) { |
| 382 | // Normalize SLE -> SLT, check for infinite loop. |
| 383 | if (++Range == 0) return; // Range overflows. |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame] | 384 | } |
Chris Lattner | 59fdaee | 2004-04-15 15:21:43 +0000 | [diff] [blame] | 385 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 386 | unsigned Leftover = Range % uint32_t(IncValue); |
| 387 | |
| 388 | // If this is an equality comparison, we require that the strided value |
| 389 | // exactly land on the exit value, otherwise the IV condition will wrap |
| 390 | // around and do things the fp IV wouldn't. |
| 391 | if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && |
| 392 | Leftover != 0) |
| 393 | return; |
| 394 | |
| 395 | // If the stride would wrap around the i32 before exiting, we can't |
| 396 | // transform the IV. |
| 397 | if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue) |
| 398 | return; |
| 399 | |
Chris Lattner | d244057 | 2004-04-15 20:26:22 +0000 | [diff] [blame] | 400 | } else { |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 401 | // If we have a negative stride, we require the init to be greater than the |
| 402 | // exit value and an equality or greater than comparison. |
| 403 | if (InitValue >= ExitValue || |
| 404 | NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE) |
| 405 | return; |
| 406 | |
| 407 | uint32_t Range = uint32_t(InitValue-ExitValue); |
| 408 | if (NewPred == CmpInst::ICMP_SGE) { |
| 409 | // Normalize SGE -> SGT, check for infinite loop. |
| 410 | if (++Range == 0) return; // Range overflows. |
| 411 | } |
| 412 | |
| 413 | unsigned Leftover = Range % uint32_t(-IncValue); |
| 414 | |
| 415 | // If this is an equality comparison, we require that the strided value |
| 416 | // exactly land on the exit value, otherwise the IV condition will wrap |
| 417 | // around and do things the fp IV wouldn't. |
| 418 | if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && |
| 419 | Leftover != 0) |
| 420 | return; |
| 421 | |
| 422 | // If the stride would wrap around the i32 before exiting, we can't |
| 423 | // transform the IV. |
| 424 | if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue) |
| 425 | return; |
Chris Lattner | d244057 | 2004-04-15 20:26:22 +0000 | [diff] [blame] | 426 | } |
Chris Lattner | 59fdaee | 2004-04-15 15:21:43 +0000 | [diff] [blame] | 427 | |
Chris Lattner | db125cf | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 428 | IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext()); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 429 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 430 | // Insert new integer induction variable. |
| 431 | PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN); |
| 432 | NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue), |
| 433 | PN->getIncomingBlock(IncomingEdge)); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 434 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 435 | Value *NewAdd = |
| 436 | BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue), |
| 437 | Incr->getName()+".int", Incr); |
| 438 | NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge)); |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame] | 439 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 440 | ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd, |
| 441 | ConstantInt::get(Int32Ty, ExitValue), |
| 442 | Compare->getName()); |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 443 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 444 | // In the following deletions, PN may become dead and may be deleted. |
| 445 | // Use a WeakVH to observe whether this happens. |
| 446 | WeakVH WeakPH = PN; |
| 447 | |
| 448 | // Delete the old floating point exit comparison. The branch starts using the |
| 449 | // new comparison. |
| 450 | NewCompare->takeName(Compare); |
| 451 | Compare->replaceAllUsesWith(NewCompare); |
| 452 | RecursivelyDeleteTriviallyDeadInstructions(Compare); |
| 453 | |
| 454 | // Delete the old floating point increment. |
| 455 | Incr->replaceAllUsesWith(UndefValue::get(Incr->getType())); |
| 456 | RecursivelyDeleteTriviallyDeadInstructions(Incr); |
| 457 | |
| 458 | // If the FP induction variable still has uses, this is because something else |
| 459 | // in the loop uses its value. In order to canonicalize the induction |
| 460 | // variable, we chose to eliminate the IV and rewrite it in terms of an |
| 461 | // int->fp cast. |
| 462 | // |
| 463 | // We give preference to sitofp over uitofp because it is faster on most |
| 464 | // platforms. |
| 465 | if (WeakPH) { |
| 466 | Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv", |
| 467 | PN->getParent()->getFirstNonPHI()); |
| 468 | PN->replaceAllUsesWith(Conv); |
| 469 | RecursivelyDeleteTriviallyDeadInstructions(PN); |
| 470 | } |
| 471 | |
| 472 | // Add a new IVUsers entry for the newly-created integer PHI. |
| 473 | if (IU) |
| 474 | IU->AddUsersIfInteresting(NewPHI); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 475 | } |
| 476 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 477 | void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) { |
| 478 | // First step. Check to see if there are any floating-point recurrences. |
| 479 | // If there are, change them into integer recurrences, permitting analysis by |
| 480 | // the SCEV routines. |
| 481 | // |
| 482 | BasicBlock *Header = L->getHeader(); |
| 483 | |
| 484 | SmallVector<WeakVH, 8> PHIs; |
| 485 | for (BasicBlock::iterator I = Header->begin(); |
| 486 | PHINode *PN = dyn_cast<PHINode>(I); ++I) |
| 487 | PHIs.push_back(PN); |
| 488 | |
| 489 | for (unsigned i = 0, e = PHIs.size(); i != e; ++i) |
| 490 | if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i])) |
| 491 | HandleFloatingPointIV(L, PN); |
| 492 | |
| 493 | // If the loop previously had floating-point IV, ScalarEvolution |
| 494 | // may not have been able to compute a trip count. Now that we've done some |
| 495 | // re-writing, the trip count may be computable. |
| 496 | if (Changed) |
| 497 | SE->forgetLoop(L); |
| 498 | } |
| 499 | |
| 500 | //===----------------------------------------------------------------------===// |
| 501 | // RewriteLoopExitValues - Optimize IV users outside the loop. |
| 502 | // As a side effect, reduces the amount of IV processing within the loop. |
| 503 | //===----------------------------------------------------------------------===// |
| 504 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 505 | /// RewriteLoopExitValues - Check to see if this loop has a computable |
| 506 | /// loop-invariant execution count. If so, this means that we can compute the |
| 507 | /// final value of any expressions that are recurrent in the loop, and |
| 508 | /// substitute the exit values from the loop into any instructions outside of |
| 509 | /// the loop that use the final values of the current expressions. |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 510 | /// |
| 511 | /// This is mostly redundant with the regular IndVarSimplify activities that |
| 512 | /// happen later, except that it's more powerful in some cases, because it's |
| 513 | /// able to brute-force evaluate arbitrary instructions as long as they have |
| 514 | /// constant operands at the beginning of the loop. |
Chris Lattner | f185989 | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 515 | void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) { |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 516 | // Verify the input to the pass in already in LCSSA form. |
Dan Gohman | bbf81d8 | 2010-03-10 19:38:49 +0000 | [diff] [blame] | 517 | assert(L->isLCSSAForm(*DT)); |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 518 | |
Devang Patel | b7211a2 | 2007-08-21 00:31:24 +0000 | [diff] [blame] | 519 | SmallVector<BasicBlock*, 8> ExitBlocks; |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 520 | L->getUniqueExitBlocks(ExitBlocks); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 521 | |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 522 | // Find all values that are computed inside the loop, but used outside of it. |
| 523 | // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan |
| 524 | // the exit blocks of the loop to find them. |
| 525 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { |
| 526 | BasicBlock *ExitBB = ExitBlocks[i]; |
Dan Gohman | cafb813 | 2009-02-17 19:13:57 +0000 | [diff] [blame] | 527 | |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 528 | // If there are no PHI nodes in this exit block, then no values defined |
| 529 | // inside the loop are used on this path, skip it. |
| 530 | PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); |
| 531 | if (!PN) continue; |
Dan Gohman | cafb813 | 2009-02-17 19:13:57 +0000 | [diff] [blame] | 532 | |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 533 | unsigned NumPreds = PN->getNumIncomingValues(); |
Dan Gohman | cafb813 | 2009-02-17 19:13:57 +0000 | [diff] [blame] | 534 | |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 535 | // Iterate over all of the PHI nodes. |
| 536 | BasicBlock::iterator BBI = ExitBB->begin(); |
| 537 | while ((PN = dyn_cast<PHINode>(BBI++))) { |
Torok Edwin | 3790fb0 | 2009-05-24 19:36:09 +0000 | [diff] [blame] | 538 | if (PN->use_empty()) |
| 539 | continue; // dead use, don't replace it |
Dan Gohman | 814f2b2 | 2010-02-18 21:34:02 +0000 | [diff] [blame] | 540 | |
| 541 | // SCEV only supports integer expressions for now. |
| 542 | if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy()) |
| 543 | continue; |
| 544 | |
Dale Johannesen | 45a2d7d | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 545 | // It's necessary to tell ScalarEvolution about this explicitly so that |
| 546 | // it can walk the def-use list and forget all SCEVs, as it may not be |
| 547 | // watching the PHI itself. Once the new exit value is in place, there |
| 548 | // may not be a def-use connection between the loop and every instruction |
| 549 | // which got a SCEVAddRecExpr for that loop. |
| 550 | SE->forgetValue(PN); |
| 551 | |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 552 | // Iterate over all of the values in all the PHI nodes. |
| 553 | for (unsigned i = 0; i != NumPreds; ++i) { |
| 554 | // If the value being merged in is not integer or is not defined |
| 555 | // in the loop, skip it. |
| 556 | Value *InVal = PN->getIncomingValue(i); |
Dan Gohman | 814f2b2 | 2010-02-18 21:34:02 +0000 | [diff] [blame] | 557 | if (!isa<Instruction>(InVal)) |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 558 | continue; |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 559 | |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 560 | // If this pred is for a subloop, not L itself, skip it. |
Dan Gohman | cafb813 | 2009-02-17 19:13:57 +0000 | [diff] [blame] | 561 | if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 562 | continue; // The Block is in a subloop, skip it. |
| 563 | |
| 564 | // Check that InVal is defined in the loop. |
| 565 | Instruction *Inst = cast<Instruction>(InVal); |
Dan Gohman | 92329c7 | 2009-12-18 01:24:09 +0000 | [diff] [blame] | 566 | if (!L->contains(Inst)) |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 567 | continue; |
Dan Gohman | cafb813 | 2009-02-17 19:13:57 +0000 | [diff] [blame] | 568 | |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 569 | // Okay, this instruction has a user outside of the current loop |
| 570 | // and varies predictably *inside* the loop. Evaluate the value it |
| 571 | // contains when the loop exits, if possible. |
Dan Gohman | 0bba49c | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 572 | const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); |
Dan Gohman | 17ead4f | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 573 | if (!SE->isLoopInvariant(ExitValue, L)) |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 574 | continue; |
Chris Lattner | 9caed54 | 2007-03-04 01:00:28 +0000 | [diff] [blame] | 575 | |
Dan Gohman | 667d787 | 2009-06-26 22:53:46 +0000 | [diff] [blame] | 576 | Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst); |
Dan Gohman | cafb813 | 2009-02-17 19:13:57 +0000 | [diff] [blame] | 577 | |
David Greene | f67ef31 | 2010-01-05 01:27:06 +0000 | [diff] [blame] | 578 | DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n' |
Chris Lattner | bdff548 | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 579 | << " LoopVal = " << *Inst << "\n"); |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 580 | |
Andrew Trick | b12a754 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 581 | if (!isValidRewrite(Inst, ExitVal)) { |
| 582 | DeadInsts.push_back(ExitVal); |
| 583 | continue; |
| 584 | } |
| 585 | Changed = true; |
| 586 | ++NumReplaced; |
| 587 | |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 588 | PN->setIncomingValue(i, ExitVal); |
Dan Gohman | cafb813 | 2009-02-17 19:13:57 +0000 | [diff] [blame] | 589 | |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 590 | // If this instruction is dead now, delete it. |
| 591 | RecursivelyDeleteTriviallyDeadInstructions(Inst); |
Dan Gohman | cafb813 | 2009-02-17 19:13:57 +0000 | [diff] [blame] | 592 | |
Dan Gohman | 65d1e2b | 2009-07-14 01:09:02 +0000 | [diff] [blame] | 593 | if (NumPreds == 1) { |
| 594 | // Completely replace a single-pred PHI. This is safe, because the |
| 595 | // NewVal won't be variant in the loop, so we don't need an LCSSA phi |
| 596 | // node anymore. |
Chris Lattner | 9f3d738 | 2007-03-04 03:43:23 +0000 | [diff] [blame] | 597 | PN->replaceAllUsesWith(ExitVal); |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 598 | RecursivelyDeleteTriviallyDeadInstructions(PN); |
Chris Lattner | c9838f2 | 2007-03-03 22:48:48 +0000 | [diff] [blame] | 599 | } |
| 600 | } |
Dan Gohman | 65d1e2b | 2009-07-14 01:09:02 +0000 | [diff] [blame] | 601 | if (NumPreds != 1) { |
Dan Gohman | 667d787 | 2009-06-26 22:53:46 +0000 | [diff] [blame] | 602 | // Clone the PHI and delete the original one. This lets IVUsers and |
| 603 | // any other maps purge the original user from their records. |
Devang Patel | 50b6e33 | 2009-10-27 22:16:29 +0000 | [diff] [blame] | 604 | PHINode *NewPN = cast<PHINode>(PN->clone()); |
Dan Gohman | 667d787 | 2009-06-26 22:53:46 +0000 | [diff] [blame] | 605 | NewPN->takeName(PN); |
| 606 | NewPN->insertBefore(PN); |
| 607 | PN->replaceAllUsesWith(NewPN); |
| 608 | PN->eraseFromParent(); |
| 609 | } |
Chris Lattner | c9838f2 | 2007-03-03 22:48:48 +0000 | [diff] [blame] | 610 | } |
| 611 | } |
Dan Gohman | 472fdf7 | 2010-03-20 03:53:53 +0000 | [diff] [blame] | 612 | |
| 613 | // The insertion point instruction may have been deleted; clear it out |
| 614 | // so that the rewriter doesn't trip over it later. |
| 615 | Rewriter.clearInsertPoint(); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 616 | } |
| 617 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 618 | //===----------------------------------------------------------------------===// |
| 619 | // Rewrite IV users based on a canonical IV. |
| 620 | // To be replaced by -disable-iv-rewrite. |
| 621 | //===----------------------------------------------------------------------===// |
Dale Johannesen | c671d89 | 2009-04-15 23:31:51 +0000 | [diff] [blame] | 622 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 623 | /// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this |
| 624 | /// loop. IVUsers is treated as a worklist. Each successive simplification may |
| 625 | /// push more users which may themselves be candidates for simplification. |
| 626 | /// |
| 627 | /// This is the old approach to IV simplification to be replaced by |
| 628 | /// SimplifyIVUsersNoRewrite. |
| 629 | /// |
| 630 | void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) { |
| 631 | // Each round of simplification involves a round of eliminating operations |
| 632 | // followed by a round of widening IVs. A single IVUsers worklist is used |
| 633 | // across all rounds. The inner loop advances the user. If widening exposes |
| 634 | // more uses, then another pass through the outer loop is triggered. |
| 635 | for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) { |
| 636 | Instruction *UseInst = I->getUser(); |
| 637 | Value *IVOperand = I->getOperandValToReplace(); |
| 638 | |
| 639 | if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) { |
| 640 | EliminateIVComparison(ICmp, IVOperand); |
| 641 | continue; |
| 642 | } |
| 643 | if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) { |
| 644 | bool IsSigned = Rem->getOpcode() == Instruction::SRem; |
| 645 | if (IsSigned || Rem->getOpcode() == Instruction::URem) { |
Andrew Trick | 4417e53 | 2011-06-21 15:43:52 +0000 | [diff] [blame] | 646 | EliminateIVRemainder(Rem, IVOperand, IsSigned); |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 647 | continue; |
| 648 | } |
| 649 | } |
| 650 | } |
| 651 | } |
| 652 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 653 | // FIXME: It is an extremely bad idea to indvar substitute anything more |
| 654 | // complex than affine induction variables. Doing so will put expensive |
| 655 | // polynomial evaluations inside of the loop, and the str reduction pass |
| 656 | // currently can only reduce affine polynomials. For now just disable |
| 657 | // indvar subst on anything more complex than an affine addrec, unless |
| 658 | // it can be expanded to a trivial value. |
| 659 | static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) { |
| 660 | // Loop-invariant values are safe. |
| 661 | if (SE->isLoopInvariant(S, L)) return true; |
| 662 | |
| 663 | // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how |
| 664 | // to transform them into efficient code. |
| 665 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) |
| 666 | return AR->isAffine(); |
| 667 | |
| 668 | // An add is safe it all its operands are safe. |
| 669 | if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) { |
| 670 | for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(), |
| 671 | E = Commutative->op_end(); I != E; ++I) |
| 672 | if (!isSafe(*I, L, SE)) return false; |
| 673 | return true; |
| 674 | } |
| 675 | |
| 676 | // A cast is safe if its operand is. |
| 677 | if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) |
| 678 | return isSafe(C->getOperand(), L, SE); |
| 679 | |
| 680 | // A udiv is safe if its operands are. |
| 681 | if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S)) |
| 682 | return isSafe(UD->getLHS(), L, SE) && |
| 683 | isSafe(UD->getRHS(), L, SE); |
| 684 | |
| 685 | // SCEVUnknown is always safe. |
| 686 | if (isa<SCEVUnknown>(S)) |
| 687 | return true; |
| 688 | |
| 689 | // Nothing else is safe. |
| 690 | return false; |
| 691 | } |
| 692 | |
| 693 | void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) { |
| 694 | // Rewrite all induction variable expressions in terms of the canonical |
| 695 | // induction variable. |
| 696 | // |
| 697 | // If there were induction variables of other sizes or offsets, manually |
| 698 | // add the offsets to the primary induction variable and cast, avoiding |
| 699 | // the need for the code evaluation methods to insert induction variables |
| 700 | // of different sizes. |
| 701 | for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) { |
| 702 | Value *Op = UI->getOperandValToReplace(); |
Chris Lattner | db125cf | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 703 | Type *UseTy = Op->getType(); |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 704 | Instruction *User = UI->getUser(); |
| 705 | |
| 706 | // Compute the final addrec to expand into code. |
| 707 | const SCEV *AR = IU->getReplacementExpr(*UI); |
| 708 | |
| 709 | // Evaluate the expression out of the loop, if possible. |
| 710 | if (!L->contains(UI->getUser())) { |
| 711 | const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop()); |
| 712 | if (SE->isLoopInvariant(ExitVal, L)) |
| 713 | AR = ExitVal; |
| 714 | } |
| 715 | |
| 716 | // FIXME: It is an extremely bad idea to indvar substitute anything more |
| 717 | // complex than affine induction variables. Doing so will put expensive |
| 718 | // polynomial evaluations inside of the loop, and the str reduction pass |
| 719 | // currently can only reduce affine polynomials. For now just disable |
| 720 | // indvar subst on anything more complex than an affine addrec, unless |
| 721 | // it can be expanded to a trivial value. |
| 722 | if (!isSafe(AR, L, SE)) |
| 723 | continue; |
| 724 | |
| 725 | // Determine the insertion point for this user. By default, insert |
| 726 | // immediately before the user. The SCEVExpander class will automatically |
| 727 | // hoist loop invariants out of the loop. For PHI nodes, there may be |
| 728 | // multiple uses, so compute the nearest common dominator for the |
| 729 | // incoming blocks. |
Andrew Trick | 86c9814 | 2011-07-20 05:32:06 +0000 | [diff] [blame] | 730 | Instruction *InsertPt = getInsertPointForUses(User, Op, DT); |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 731 | |
| 732 | // Now expand it into actual Instructions and patch it into place. |
| 733 | Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt); |
| 734 | |
| 735 | DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n' |
| 736 | << " into = " << *NewVal << "\n"); |
| 737 | |
| 738 | if (!isValidRewrite(Op, NewVal)) { |
| 739 | DeadInsts.push_back(NewVal); |
| 740 | continue; |
| 741 | } |
| 742 | // Inform ScalarEvolution that this value is changing. The change doesn't |
| 743 | // affect its value, but it does potentially affect which use lists the |
| 744 | // value will be on after the replacement, which affects ScalarEvolution's |
| 745 | // ability to walk use lists and drop dangling pointers when a value is |
| 746 | // deleted. |
| 747 | SE->forgetValue(User); |
| 748 | |
| 749 | // Patch the new value into place. |
| 750 | if (Op->hasName()) |
| 751 | NewVal->takeName(Op); |
| 752 | if (Instruction *NewValI = dyn_cast<Instruction>(NewVal)) |
| 753 | NewValI->setDebugLoc(User->getDebugLoc()); |
| 754 | User->replaceUsesOfWith(Op, NewVal); |
| 755 | UI->setOperandValToReplace(NewVal); |
| 756 | |
| 757 | ++NumRemoved; |
| 758 | Changed = true; |
| 759 | |
| 760 | // The old value may be dead now. |
| 761 | DeadInsts.push_back(Op); |
| 762 | } |
| 763 | } |
| 764 | |
| 765 | //===----------------------------------------------------------------------===// |
| 766 | // IV Widening - Extend the width of an IV to cover its widest uses. |
| 767 | //===----------------------------------------------------------------------===// |
| 768 | |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 769 | namespace { |
| 770 | // Collect information about induction variables that are used by sign/zero |
| 771 | // extend operations. This information is recorded by CollectExtend and |
| 772 | // provides the input to WidenIV. |
| 773 | struct WideIVInfo { |
Chris Lattner | db125cf | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 774 | Type *WidestNativeType; // Widest integer type created [sz]ext |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 775 | bool IsSigned; // Was an sext user seen before a zext? |
| 776 | |
| 777 | WideIVInfo() : WidestNativeType(0), IsSigned(false) {} |
| 778 | }; |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 779 | } |
| 780 | |
| 781 | /// CollectExtend - Update information about the induction variable that is |
| 782 | /// extended by this sign or zero extend operation. This is used to determine |
| 783 | /// the final width of the IV before actually widening it. |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 784 | static void CollectExtend(CastInst *Cast, bool IsSigned, WideIVInfo &WI, |
| 785 | ScalarEvolution *SE, const TargetData *TD) { |
Chris Lattner | db125cf | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 786 | Type *Ty = Cast->getType(); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 787 | uint64_t Width = SE->getTypeSizeInBits(Ty); |
| 788 | if (TD && !TD->isLegalInteger(Width)) |
| 789 | return; |
| 790 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 791 | if (!WI.WidestNativeType) { |
| 792 | WI.WidestNativeType = SE->getEffectiveSCEVType(Ty); |
| 793 | WI.IsSigned = IsSigned; |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 794 | return; |
| 795 | } |
| 796 | |
| 797 | // We extend the IV to satisfy the sign of its first user, arbitrarily. |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 798 | if (WI.IsSigned != IsSigned) |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 799 | return; |
| 800 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 801 | if (Width > SE->getTypeSizeInBits(WI.WidestNativeType)) |
| 802 | WI.WidestNativeType = SE->getEffectiveSCEVType(Ty); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 803 | } |
| 804 | |
| 805 | namespace { |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 806 | |
| 807 | /// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the |
| 808 | /// WideIV that computes the same value as the Narrow IV def. This avoids |
| 809 | /// caching Use* pointers. |
| 810 | struct NarrowIVDefUse { |
| 811 | Instruction *NarrowDef; |
| 812 | Instruction *NarrowUse; |
| 813 | Instruction *WideDef; |
| 814 | |
| 815 | NarrowIVDefUse(): NarrowDef(0), NarrowUse(0), WideDef(0) {} |
| 816 | |
| 817 | NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD): |
| 818 | NarrowDef(ND), NarrowUse(NU), WideDef(WD) {} |
| 819 | }; |
| 820 | |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 821 | /// WidenIV - The goal of this transform is to remove sign and zero extends |
| 822 | /// without creating any new induction variables. To do this, it creates a new |
| 823 | /// phi of the wider type and redirects all users, either removing extends or |
| 824 | /// inserting truncs whenever we stop propagating the type. |
| 825 | /// |
| 826 | class WidenIV { |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 827 | // Parameters |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 828 | PHINode *OrigPhi; |
Chris Lattner | db125cf | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 829 | Type *WideType; |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 830 | bool IsSigned; |
| 831 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 832 | // Context |
| 833 | LoopInfo *LI; |
| 834 | Loop *L; |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 835 | ScalarEvolution *SE; |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 836 | DominatorTree *DT; |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 837 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 838 | // Result |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 839 | PHINode *WidePhi; |
| 840 | Instruction *WideInc; |
| 841 | const SCEV *WideIncExpr; |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 842 | SmallVectorImpl<WeakVH> &DeadInsts; |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 843 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 844 | SmallPtrSet<Instruction*,16> Widened; |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 845 | SmallVector<NarrowIVDefUse, 8> NarrowIVUsers; |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 846 | |
| 847 | public: |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 848 | WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo, |
| 849 | ScalarEvolution *SEv, DominatorTree *DTree, |
Andrew Trick | fcdc9a4 | 2011-05-26 00:46:11 +0000 | [diff] [blame] | 850 | SmallVectorImpl<WeakVH> &DI) : |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 851 | OrigPhi(PN), |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 852 | WideType(WI.WidestNativeType), |
| 853 | IsSigned(WI.IsSigned), |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 854 | LI(LInfo), |
| 855 | L(LI->getLoopFor(OrigPhi->getParent())), |
| 856 | SE(SEv), |
Andrew Trick | fcdc9a4 | 2011-05-26 00:46:11 +0000 | [diff] [blame] | 857 | DT(DTree), |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 858 | WidePhi(0), |
| 859 | WideInc(0), |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 860 | WideIncExpr(0), |
| 861 | DeadInsts(DI) { |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 862 | assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV"); |
| 863 | } |
| 864 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 865 | PHINode *CreateWideIV(SCEVExpander &Rewriter); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 866 | |
| 867 | protected: |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 868 | Instruction *CloneIVUser(NarrowIVDefUse DU); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 869 | |
Andrew Trick | e0dc2fa | 2011-07-05 18:19:39 +0000 | [diff] [blame] | 870 | const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse); |
| 871 | |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 872 | Instruction *WidenIVUse(NarrowIVDefUse DU); |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 873 | |
| 874 | void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 875 | }; |
| 876 | } // anonymous namespace |
| 877 | |
Chris Lattner | db125cf | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 878 | static Value *getExtend( Value *NarrowOper, Type *WideType, |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 879 | bool IsSigned, IRBuilder<> &Builder) { |
| 880 | return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) : |
| 881 | Builder.CreateZExt(NarrowOper, WideType); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 882 | } |
| 883 | |
| 884 | /// CloneIVUser - Instantiate a wide operation to replace a narrow |
| 885 | /// operation. This only needs to handle operations that can evaluation to |
| 886 | /// SCEVAddRec. It can safely return 0 for any operation we decide not to clone. |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 887 | Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) { |
| 888 | unsigned Opcode = DU.NarrowUse->getOpcode(); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 889 | switch (Opcode) { |
| 890 | default: |
| 891 | return 0; |
| 892 | case Instruction::Add: |
| 893 | case Instruction::Mul: |
| 894 | case Instruction::UDiv: |
| 895 | case Instruction::Sub: |
| 896 | case Instruction::And: |
| 897 | case Instruction::Or: |
| 898 | case Instruction::Xor: |
| 899 | case Instruction::Shl: |
| 900 | case Instruction::LShr: |
| 901 | case Instruction::AShr: |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 902 | DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n"); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 903 | |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 904 | IRBuilder<> Builder(DU.NarrowUse); |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 905 | |
| 906 | // Replace NarrowDef operands with WideDef. Otherwise, we don't know |
| 907 | // anything about the narrow operand yet so must insert a [sz]ext. It is |
| 908 | // probably loop invariant and will be folded or hoisted. If it actually |
| 909 | // comes from a widened IV, it should be removed during a future call to |
| 910 | // WidenIVUse. |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 911 | Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef : |
| 912 | getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, Builder); |
| 913 | Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef : |
| 914 | getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, Builder); |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 915 | |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 916 | BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 917 | BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 918 | LHS, RHS, |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 919 | NarrowBO->getName()); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 920 | Builder.Insert(WideBO); |
Andrew Trick | 6e0ce24 | 2011-06-30 19:02:17 +0000 | [diff] [blame] | 921 | if (const OverflowingBinaryOperator *OBO = |
| 922 | dyn_cast<OverflowingBinaryOperator>(NarrowBO)) { |
| 923 | if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap(); |
| 924 | if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap(); |
| 925 | } |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 926 | return WideBO; |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 927 | } |
| 928 | llvm_unreachable(0); |
| 929 | } |
| 930 | |
Andrew Trick | fcdc9a4 | 2011-05-26 00:46:11 +0000 | [diff] [blame] | 931 | /// HoistStep - Attempt to hoist an IV increment above a potential use. |
| 932 | /// |
| 933 | /// To successfully hoist, two criteria must be met: |
| 934 | /// - IncV operands dominate InsertPos and |
| 935 | /// - InsertPos dominates IncV |
| 936 | /// |
| 937 | /// Meeting the second condition means that we don't need to check all of IncV's |
| 938 | /// existing uses (it's moving up in the domtree). |
| 939 | /// |
| 940 | /// This does not yet recursively hoist the operands, although that would |
| 941 | /// not be difficult. |
| 942 | static bool HoistStep(Instruction *IncV, Instruction *InsertPos, |
| 943 | const DominatorTree *DT) |
| 944 | { |
| 945 | if (DT->dominates(IncV, InsertPos)) |
| 946 | return true; |
| 947 | |
| 948 | if (!DT->dominates(InsertPos->getParent(), IncV->getParent())) |
| 949 | return false; |
| 950 | |
| 951 | if (IncV->mayHaveSideEffects()) |
| 952 | return false; |
| 953 | |
| 954 | // Attempt to hoist IncV |
| 955 | for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end(); |
| 956 | OI != OE; ++OI) { |
| 957 | Instruction *OInst = dyn_cast<Instruction>(OI); |
| 958 | if (OInst && !DT->dominates(OInst, InsertPos)) |
| 959 | return false; |
| 960 | } |
| 961 | IncV->moveBefore(InsertPos); |
| 962 | return true; |
| 963 | } |
| 964 | |
Andrew Trick | e0dc2fa | 2011-07-05 18:19:39 +0000 | [diff] [blame] | 965 | // GetWideRecurrence - Is this instruction potentially interesting from IVUsers' |
| 966 | // perspective after widening it's type? In other words, can the extend be |
| 967 | // safely hoisted out of the loop with SCEV reducing the value to a recurrence |
| 968 | // on the same loop. If so, return the sign or zero extended |
| 969 | // recurrence. Otherwise return NULL. |
| 970 | const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) { |
| 971 | if (!SE->isSCEVable(NarrowUse->getType())) |
| 972 | return 0; |
| 973 | |
| 974 | const SCEV *NarrowExpr = SE->getSCEV(NarrowUse); |
| 975 | if (SE->getTypeSizeInBits(NarrowExpr->getType()) |
| 976 | >= SE->getTypeSizeInBits(WideType)) { |
| 977 | // NarrowUse implicitly widens its operand. e.g. a gep with a narrow |
| 978 | // index. So don't follow this use. |
| 979 | return 0; |
| 980 | } |
| 981 | |
| 982 | const SCEV *WideExpr = IsSigned ? |
| 983 | SE->getSignExtendExpr(NarrowExpr, WideType) : |
| 984 | SE->getZeroExtendExpr(NarrowExpr, WideType); |
| 985 | const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr); |
| 986 | if (!AddRec || AddRec->getLoop() != L) |
| 987 | return 0; |
| 988 | |
| 989 | return AddRec; |
| 990 | } |
| 991 | |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 992 | /// WidenIVUse - Determine whether an individual user of the narrow IV can be |
| 993 | /// widened. If so, return the wide clone of the user. |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 994 | Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU) { |
Andrew Trick | cc359d9 | 2011-06-29 23:03:57 +0000 | [diff] [blame] | 995 | |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 996 | // Stop traversing the def-use chain at inner-loop phis or post-loop phis. |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 997 | if (isa<PHINode>(DU.NarrowUse) && |
| 998 | LI->getLoopFor(DU.NarrowUse->getParent()) != L) |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 999 | return 0; |
| 1000 | |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1001 | // Our raison d'etre! Eliminate sign and zero extension. |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1002 | if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) { |
| 1003 | Value *NewDef = DU.WideDef; |
| 1004 | if (DU.NarrowUse->getType() != WideType) { |
| 1005 | unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType()); |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 1006 | unsigned IVWidth = SE->getTypeSizeInBits(WideType); |
| 1007 | if (CastWidth < IVWidth) { |
| 1008 | // The cast isn't as wide as the IV, so insert a Trunc. |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1009 | IRBuilder<> Builder(DU.NarrowUse); |
| 1010 | NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType()); |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 1011 | } |
| 1012 | else { |
| 1013 | // A wider extend was hidden behind a narrower one. This may induce |
| 1014 | // another round of IV widening in which the intermediate IV becomes |
| 1015 | // dead. It should be very rare. |
| 1016 | DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1017 | << " not wide enough to subsume " << *DU.NarrowUse << "\n"); |
| 1018 | DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); |
| 1019 | NewDef = DU.NarrowUse; |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 1020 | } |
| 1021 | } |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1022 | if (NewDef != DU.NarrowUse) { |
| 1023 | DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse |
| 1024 | << " replaced by " << *DU.WideDef << "\n"); |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 1025 | ++NumElimExt; |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1026 | DU.NarrowUse->replaceAllUsesWith(NewDef); |
| 1027 | DeadInsts.push_back(DU.NarrowUse); |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 1028 | } |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1029 | // Now that the extend is gone, we want to expose it's uses for potential |
| 1030 | // further simplification. We don't need to directly inform SimplifyIVUsers |
| 1031 | // of the new users, because their parent IV will be processed later as a |
| 1032 | // new loop phi. If we preserved IVUsers analysis, we would also want to |
| 1033 | // push the uses of WideDef here. |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1034 | |
| 1035 | // No further widening is needed. The deceased [sz]ext had done it for us. |
| 1036 | return 0; |
| 1037 | } |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1038 | |
| 1039 | // Does this user itself evaluate to a recurrence after widening? |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1040 | const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1041 | if (!WideAddRec) { |
| 1042 | // This user does not evaluate to a recurence after widening, so don't |
| 1043 | // follow it. Instead insert a Trunc to kill off the original use, |
| 1044 | // eventually isolating the original narrow IV so it can be removed. |
Andrew Trick | 86c9814 | 2011-07-20 05:32:06 +0000 | [diff] [blame] | 1045 | IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT)); |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1046 | Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType()); |
| 1047 | DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1048 | return 0; |
| 1049 | } |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1050 | // Assume block terminators cannot evaluate to a recurrence. We can't to |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1051 | // insert a Trunc after a terminator if there happens to be a critical edge. |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1052 | assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() && |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1053 | "SCEV is not expected to evaluate a block terminator"); |
Andrew Trick | cc359d9 | 2011-06-29 23:03:57 +0000 | [diff] [blame] | 1054 | |
Andrew Trick | fcdc9a4 | 2011-05-26 00:46:11 +0000 | [diff] [blame] | 1055 | // Reuse the IV increment that SCEVExpander created as long as it dominates |
| 1056 | // NarrowUse. |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1057 | Instruction *WideUse = 0; |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1058 | if (WideAddRec == WideIncExpr && HoistStep(WideInc, DU.NarrowUse, DT)) { |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1059 | WideUse = WideInc; |
| 1060 | } |
| 1061 | else { |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1062 | WideUse = CloneIVUser(DU); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1063 | if (!WideUse) |
| 1064 | return 0; |
| 1065 | } |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1066 | // Evaluation of WideAddRec ensured that the narrow expression could be |
| 1067 | // extended outside the loop without overflow. This suggests that the wide use |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1068 | // evaluates to the same expression as the extended narrow use, but doesn't |
| 1069 | // absolutely guarantee it. Hence the following failsafe check. In rare cases |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1070 | // where it fails, we simply throw away the newly created wide use. |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1071 | if (WideAddRec != SE->getSCEV(WideUse)) { |
| 1072 | DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse |
| 1073 | << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n"); |
| 1074 | DeadInsts.push_back(WideUse); |
| 1075 | return 0; |
| 1076 | } |
| 1077 | |
| 1078 | // Returning WideUse pushes it on the worklist. |
| 1079 | return WideUse; |
| 1080 | } |
| 1081 | |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1082 | /// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers. |
| 1083 | /// |
| 1084 | void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) { |
| 1085 | for (Value::use_iterator UI = NarrowDef->use_begin(), |
| 1086 | UE = NarrowDef->use_end(); UI != UE; ++UI) { |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1087 | Instruction *NarrowUse = cast<Instruction>(*UI); |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1088 | |
| 1089 | // Handle data flow merges and bizarre phi cycles. |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1090 | if (!Widened.insert(NarrowUse)) |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1091 | continue; |
| 1092 | |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1093 | NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUse, WideDef)); |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1094 | } |
| 1095 | } |
| 1096 | |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1097 | /// CreateWideIV - Process a single induction variable. First use the |
| 1098 | /// SCEVExpander to create a wide induction variable that evaluates to the same |
| 1099 | /// recurrence as the original narrow IV. Then use a worklist to forward |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1100 | /// traverse the narrow IV's def-use chain. After WidenIVUse has processed all |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1101 | /// interesting IV users, the narrow IV will be isolated for removal by |
| 1102 | /// DeleteDeadPHIs. |
| 1103 | /// |
| 1104 | /// It would be simpler to delete uses as they are processed, but we must avoid |
| 1105 | /// invalidating SCEV expressions. |
| 1106 | /// |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1107 | PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) { |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1108 | // Is this phi an induction variable? |
| 1109 | const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi)); |
| 1110 | if (!AddRec) |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1111 | return NULL; |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1112 | |
| 1113 | // Widen the induction variable expression. |
| 1114 | const SCEV *WideIVExpr = IsSigned ? |
| 1115 | SE->getSignExtendExpr(AddRec, WideType) : |
| 1116 | SE->getZeroExtendExpr(AddRec, WideType); |
| 1117 | |
| 1118 | assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType && |
| 1119 | "Expect the new IV expression to preserve its type"); |
| 1120 | |
| 1121 | // Can the IV be extended outside the loop without overflow? |
| 1122 | AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr); |
| 1123 | if (!AddRec || AddRec->getLoop() != L) |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1124 | return NULL; |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1125 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1126 | // An AddRec must have loop-invariant operands. Since this AddRec is |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1127 | // materialized by a loop header phi, the expression cannot have any post-loop |
| 1128 | // operands, so they must dominate the loop header. |
| 1129 | assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) && |
| 1130 | SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) |
| 1131 | && "Loop header phi recurrence inputs do not dominate the loop"); |
| 1132 | |
| 1133 | // The rewriter provides a value for the desired IV expression. This may |
| 1134 | // either find an existing phi or materialize a new one. Either way, we |
| 1135 | // expect a well-formed cyclic phi-with-increments. i.e. any operand not part |
| 1136 | // of the phi-SCC dominates the loop entry. |
| 1137 | Instruction *InsertPt = L->getHeader()->begin(); |
| 1138 | WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt)); |
| 1139 | |
| 1140 | // Remembering the WideIV increment generated by SCEVExpander allows |
| 1141 | // WidenIVUse to reuse it when widening the narrow IV's increment. We don't |
| 1142 | // employ a general reuse mechanism because the call above is the only call to |
| 1143 | // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses. |
Andrew Trick | fcdc9a4 | 2011-05-26 00:46:11 +0000 | [diff] [blame] | 1144 | if (BasicBlock *LatchBlock = L->getLoopLatch()) { |
| 1145 | WideInc = |
| 1146 | cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock)); |
| 1147 | WideIncExpr = SE->getSCEV(WideInc); |
| 1148 | } |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1149 | |
| 1150 | DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n"); |
| 1151 | ++NumWidened; |
| 1152 | |
| 1153 | // Traverse the def-use chain using a worklist starting at the original IV. |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1154 | assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" ); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1155 | |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1156 | Widened.insert(OrigPhi); |
| 1157 | pushNarrowIVUsers(OrigPhi, WidePhi); |
| 1158 | |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1159 | while (!NarrowIVUsers.empty()) { |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1160 | NarrowIVDefUse DU = NarrowIVUsers.pop_back_val(); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1161 | |
Andrew Trick | fcdc9a4 | 2011-05-26 00:46:11 +0000 | [diff] [blame] | 1162 | // Process a def-use edge. This may replace the use, so don't hold a |
| 1163 | // use_iterator across it. |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1164 | Instruction *WideUse = WidenIVUse(DU); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1165 | |
Andrew Trick | fcdc9a4 | 2011-05-26 00:46:11 +0000 | [diff] [blame] | 1166 | // Follow all def-use edges from the previous narrow use. |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1167 | if (WideUse) |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1168 | pushNarrowIVUsers(DU.NarrowUse, WideUse); |
Andrew Trick | 4b02915 | 2011-07-02 02:34:25 +0000 | [diff] [blame] | 1169 | |
Andrew Trick | fcdc9a4 | 2011-05-26 00:46:11 +0000 | [diff] [blame] | 1170 | // WidenIVUse may have removed the def-use edge. |
Andrew Trick | 13bcf2e | 2011-07-20 04:39:24 +0000 | [diff] [blame] | 1171 | if (DU.NarrowDef->use_empty()) |
| 1172 | DeadInsts.push_back(DU.NarrowDef); |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1173 | } |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1174 | return WidePhi; |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 1175 | } |
| 1176 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1177 | //===----------------------------------------------------------------------===// |
| 1178 | // Simplification of IV users based on SCEV evaluation. |
| 1179 | //===----------------------------------------------------------------------===// |
| 1180 | |
Andrew Trick | aeee461 | 2011-05-12 00:04:28 +0000 | [diff] [blame] | 1181 | void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) { |
| 1182 | unsigned IVOperIdx = 0; |
| 1183 | ICmpInst::Predicate Pred = ICmp->getPredicate(); |
| 1184 | if (IVOperand != ICmp->getOperand(0)) { |
| 1185 | // Swapped |
| 1186 | assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); |
| 1187 | IVOperIdx = 1; |
| 1188 | Pred = ICmpInst::getSwappedPredicate(Pred); |
Dan Gohman | a590b79 | 2010-04-13 01:46:36 +0000 | [diff] [blame] | 1189 | } |
Andrew Trick | aeee461 | 2011-05-12 00:04:28 +0000 | [diff] [blame] | 1190 | |
| 1191 | // Get the SCEVs for the ICmp operands. |
| 1192 | const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx)); |
| 1193 | const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx)); |
| 1194 | |
| 1195 | // Simplify unnecessary loops away. |
| 1196 | const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); |
| 1197 | S = SE->getSCEVAtScope(S, ICmpLoop); |
| 1198 | X = SE->getSCEVAtScope(X, ICmpLoop); |
| 1199 | |
| 1200 | // If the condition is always true or always false, replace it with |
| 1201 | // a constant value. |
| 1202 | if (SE->isKnownPredicate(Pred, S, X)) |
| 1203 | ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext())); |
| 1204 | else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) |
| 1205 | ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext())); |
| 1206 | else |
| 1207 | return; |
| 1208 | |
| 1209 | DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 1210 | ++NumElimCmp; |
Andrew Trick | 074397d | 2011-05-20 03:37:48 +0000 | [diff] [blame] | 1211 | Changed = true; |
Andrew Trick | aeee461 | 2011-05-12 00:04:28 +0000 | [diff] [blame] | 1212 | DeadInsts.push_back(ICmp); |
| 1213 | } |
| 1214 | |
| 1215 | void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem, |
| 1216 | Value *IVOperand, |
Andrew Trick | 4417e53 | 2011-06-21 15:43:52 +0000 | [diff] [blame] | 1217 | bool IsSigned) { |
Andrew Trick | aeee461 | 2011-05-12 00:04:28 +0000 | [diff] [blame] | 1218 | // We're only interested in the case where we know something about |
| 1219 | // the numerator. |
| 1220 | if (IVOperand != Rem->getOperand(0)) |
| 1221 | return; |
| 1222 | |
| 1223 | // Get the SCEVs for the ICmp operands. |
| 1224 | const SCEV *S = SE->getSCEV(Rem->getOperand(0)); |
| 1225 | const SCEV *X = SE->getSCEV(Rem->getOperand(1)); |
| 1226 | |
| 1227 | // Simplify unnecessary loops away. |
| 1228 | const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent()); |
| 1229 | S = SE->getSCEVAtScope(S, ICmpLoop); |
| 1230 | X = SE->getSCEVAtScope(X, ICmpLoop); |
| 1231 | |
| 1232 | // i % n --> i if i is in [0,n). |
Andrew Trick | 074397d | 2011-05-20 03:37:48 +0000 | [diff] [blame] | 1233 | if ((!IsSigned || SE->isKnownNonNegative(S)) && |
| 1234 | SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, |
Andrew Trick | aeee461 | 2011-05-12 00:04:28 +0000 | [diff] [blame] | 1235 | S, X)) |
| 1236 | Rem->replaceAllUsesWith(Rem->getOperand(0)); |
| 1237 | else { |
| 1238 | // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n). |
| 1239 | const SCEV *LessOne = |
| 1240 | SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1)); |
Andrew Trick | 074397d | 2011-05-20 03:37:48 +0000 | [diff] [blame] | 1241 | if (IsSigned && !SE->isKnownNonNegative(LessOne)) |
Andrew Trick | aeee461 | 2011-05-12 00:04:28 +0000 | [diff] [blame] | 1242 | return; |
| 1243 | |
Andrew Trick | 074397d | 2011-05-20 03:37:48 +0000 | [diff] [blame] | 1244 | if (!SE->isKnownPredicate(IsSigned ? |
Andrew Trick | aeee461 | 2011-05-12 00:04:28 +0000 | [diff] [blame] | 1245 | ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, |
| 1246 | LessOne, X)) |
| 1247 | return; |
| 1248 | |
| 1249 | ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, |
| 1250 | Rem->getOperand(0), Rem->getOperand(1), |
| 1251 | "tmp"); |
| 1252 | SelectInst *Sel = |
| 1253 | SelectInst::Create(ICmp, |
| 1254 | ConstantInt::get(Rem->getType(), 0), |
| 1255 | Rem->getOperand(0), "tmp", Rem); |
| 1256 | Rem->replaceAllUsesWith(Sel); |
| 1257 | } |
| 1258 | |
| 1259 | // Inform IVUsers about the new users. |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1260 | if (IU) { |
| 1261 | if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0))) |
Andrew Trick | 4417e53 | 2011-06-21 15:43:52 +0000 | [diff] [blame] | 1262 | IU->AddUsersIfInteresting(I); |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1263 | } |
Andrew Trick | aeee461 | 2011-05-12 00:04:28 +0000 | [diff] [blame] | 1264 | DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 1265 | ++NumElimRem; |
Andrew Trick | 074397d | 2011-05-20 03:37:48 +0000 | [diff] [blame] | 1266 | Changed = true; |
Andrew Trick | aeee461 | 2011-05-12 00:04:28 +0000 | [diff] [blame] | 1267 | DeadInsts.push_back(Rem); |
Dan Gohman | a590b79 | 2010-04-13 01:46:36 +0000 | [diff] [blame] | 1268 | } |
| 1269 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1270 | /// EliminateIVUser - Eliminate an operation that consumes a simple IV and has |
| 1271 | /// no observable side-effect given the range of IV values. |
| 1272 | bool IndVarSimplify::EliminateIVUser(Instruction *UseInst, |
| 1273 | Instruction *IVOperand) { |
| 1274 | if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) { |
| 1275 | EliminateIVComparison(ICmp, IVOperand); |
| 1276 | return true; |
| 1277 | } |
| 1278 | if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) { |
| 1279 | bool IsSigned = Rem->getOpcode() == Instruction::SRem; |
| 1280 | if (IsSigned || Rem->getOpcode() == Instruction::URem) { |
Andrew Trick | 4417e53 | 2011-06-21 15:43:52 +0000 | [diff] [blame] | 1281 | EliminateIVRemainder(Rem, IVOperand, IsSigned); |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1282 | return true; |
| 1283 | } |
| 1284 | } |
| 1285 | |
| 1286 | // Eliminate any operation that SCEV can prove is an identity function. |
| 1287 | if (!SE->isSCEVable(UseInst->getType()) || |
Andrew Trick | 11745d4 | 2011-06-29 03:13:40 +0000 | [diff] [blame] | 1288 | (UseInst->getType() != IVOperand->getType()) || |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1289 | (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand))) |
| 1290 | return false; |
| 1291 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1292 | DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n'); |
Andrew Trick | 60ac719 | 2011-06-30 01:27:23 +0000 | [diff] [blame] | 1293 | |
| 1294 | UseInst->replaceAllUsesWith(IVOperand); |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1295 | ++NumElimIdentity; |
| 1296 | Changed = true; |
| 1297 | DeadInsts.push_back(UseInst); |
| 1298 | return true; |
| 1299 | } |
| 1300 | |
| 1301 | /// pushIVUsers - Add all uses of Def to the current IV's worklist. |
| 1302 | /// |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1303 | static void pushIVUsers( |
| 1304 | Instruction *Def, |
| 1305 | SmallPtrSet<Instruction*,16> &Simplified, |
| 1306 | SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) { |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1307 | |
| 1308 | for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end(); |
| 1309 | UI != E; ++UI) { |
| 1310 | Instruction *User = cast<Instruction>(*UI); |
| 1311 | |
| 1312 | // Avoid infinite or exponential worklist processing. |
| 1313 | // Also ensure unique worklist users. |
Andrew Trick | 60ac719 | 2011-06-30 01:27:23 +0000 | [diff] [blame] | 1314 | // If Def is a LoopPhi, it may not be in the Simplified set, so check for |
| 1315 | // self edges first. |
| 1316 | if (User != Def && Simplified.insert(User)) |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1317 | SimpleIVUsers.push_back(std::make_pair(User, Def)); |
| 1318 | } |
| 1319 | } |
| 1320 | |
| 1321 | /// isSimpleIVUser - Return true if this instruction generates a simple SCEV |
| 1322 | /// expression in terms of that IV. |
| 1323 | /// |
| 1324 | /// This is similar to IVUsers' isInsteresting() but processes each instruction |
| 1325 | /// non-recursively when the operand is already known to be a simpleIVUser. |
| 1326 | /// |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1327 | static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) { |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1328 | if (!SE->isSCEVable(I->getType())) |
| 1329 | return false; |
| 1330 | |
| 1331 | // Get the symbolic expression for this instruction. |
| 1332 | const SCEV *S = SE->getSCEV(I); |
| 1333 | |
| 1334 | // Only consider affine recurrences. |
| 1335 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); |
| 1336 | if (AR && AR->getLoop() == L) |
| 1337 | return true; |
| 1338 | |
| 1339 | return false; |
| 1340 | } |
| 1341 | |
| 1342 | /// SimplifyIVUsersNoRewrite - Iteratively perform simplification on a worklist |
| 1343 | /// of IV users. Each successive simplification may push more users which may |
| 1344 | /// themselves be candidates for simplification. |
| 1345 | /// |
| 1346 | /// The "NoRewrite" algorithm does not require IVUsers analysis. Instead, it |
| 1347 | /// simplifies instructions in-place during analysis. Rather than rewriting |
| 1348 | /// induction variables bottom-up from their users, it transforms a chain of |
| 1349 | /// IVUsers top-down, updating the IR only when it encouters a clear |
| 1350 | /// optimization opportunitiy. A SCEVExpander "Rewriter" instance is still |
| 1351 | /// needed, but only used to generate a new IV (phi) of wider type for sign/zero |
| 1352 | /// extend elimination. |
| 1353 | /// |
| 1354 | /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers. |
| 1355 | /// |
| 1356 | void IndVarSimplify::SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter) { |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1357 | std::map<PHINode *, WideIVInfo> WideIVMap; |
| 1358 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1359 | SmallVector<PHINode*, 8> LoopPhis; |
| 1360 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
| 1361 | LoopPhis.push_back(cast<PHINode>(I)); |
| 1362 | } |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1363 | // Each round of simplification iterates through the SimplifyIVUsers worklist |
| 1364 | // for all current phis, then determines whether any IVs can be |
| 1365 | // widened. Widening adds new phis to LoopPhis, inducing another round of |
| 1366 | // simplification on the wide IVs. |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1367 | while (!LoopPhis.empty()) { |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1368 | // Evaluate as many IV expressions as possible before widening any IVs. This |
Andrew Trick | 99a92f6 | 2011-06-28 16:45:04 +0000 | [diff] [blame] | 1369 | // forces SCEV to set no-wrap flags before evaluating sign/zero |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1370 | // extension. The first time SCEV attempts to normalize sign/zero extension, |
| 1371 | // the result becomes final. So for the most predictable results, we delay |
| 1372 | // evaluation of sign/zero extend evaluation until needed, and avoid running |
| 1373 | // other SCEV based analysis prior to SimplifyIVUsersNoRewrite. |
| 1374 | do { |
| 1375 | PHINode *CurrIV = LoopPhis.pop_back_val(); |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1376 | |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1377 | // Information about sign/zero extensions of CurrIV. |
| 1378 | WideIVInfo WI; |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1379 | |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1380 | // Instructions processed by SimplifyIVUsers for CurrIV. |
| 1381 | SmallPtrSet<Instruction*,16> Simplified; |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1382 | |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 1383 | // Use-def pairs if IV users waiting to be processed for CurrIV. |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1384 | SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers; |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1385 | |
Andrew Trick | 60ac719 | 2011-06-30 01:27:23 +0000 | [diff] [blame] | 1386 | // Push users of the current LoopPhi. In rare cases, pushIVUsers may be |
| 1387 | // called multiple times for the same LoopPhi. This is the proper thing to |
| 1388 | // do for loop header phis that use each other. |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1389 | pushIVUsers(CurrIV, Simplified, SimpleIVUsers); |
| 1390 | |
| 1391 | while (!SimpleIVUsers.empty()) { |
| 1392 | Instruction *UseInst, *Operand; |
| 1393 | tie(UseInst, Operand) = SimpleIVUsers.pop_back_val(); |
Andrew Trick | 6e0ce24 | 2011-06-30 19:02:17 +0000 | [diff] [blame] | 1394 | // Bypass back edges to avoid extra work. |
| 1395 | if (UseInst == CurrIV) continue; |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1396 | |
| 1397 | if (EliminateIVUser(UseInst, Operand)) { |
| 1398 | pushIVUsers(Operand, Simplified, SimpleIVUsers); |
| 1399 | continue; |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1400 | } |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1401 | if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) { |
| 1402 | bool IsSigned = Cast->getOpcode() == Instruction::SExt; |
| 1403 | if (IsSigned || Cast->getOpcode() == Instruction::ZExt) { |
| 1404 | CollectExtend(Cast, IsSigned, WI, SE, TD); |
| 1405 | } |
| 1406 | continue; |
| 1407 | } |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1408 | if (isSimpleIVUser(UseInst, L, SE)) { |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1409 | pushIVUsers(UseInst, Simplified, SimpleIVUsers); |
| 1410 | } |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1411 | } |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1412 | if (WI.WidestNativeType) { |
| 1413 | WideIVMap[CurrIV] = WI; |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1414 | } |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1415 | } while(!LoopPhis.empty()); |
| 1416 | |
| 1417 | for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(), |
| 1418 | E = WideIVMap.end(); I != E; ++I) { |
| 1419 | WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts); |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1420 | if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) { |
| 1421 | Changed = true; |
| 1422 | LoopPhis.push_back(WidePhi); |
| 1423 | } |
| 1424 | } |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 1425 | WideIVMap.clear(); |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 1426 | } |
| 1427 | } |
| 1428 | |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 1429 | /// SimplifyCongruentIVs - Check for congruent phis in this loop header and |
| 1430 | /// populate ExprToIVMap for use later. |
| 1431 | /// |
| 1432 | void IndVarSimplify::SimplifyCongruentIVs(Loop *L) { |
Andrew Trick | 6f684b0 | 2011-07-16 01:06:48 +0000 | [diff] [blame] | 1433 | DenseMap<const SCEV *, PHINode *> ExprToIVMap; |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 1434 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
| 1435 | PHINode *Phi = cast<PHINode>(I); |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1436 | if (!SE->isSCEVable(Phi->getType())) |
| 1437 | continue; |
| 1438 | |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 1439 | const SCEV *S = SE->getSCEV(Phi); |
Andrew Trick | 6f684b0 | 2011-07-16 01:06:48 +0000 | [diff] [blame] | 1440 | DenseMap<const SCEV *, PHINode *>::const_iterator Pos; |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 1441 | bool Inserted; |
| 1442 | tie(Pos, Inserted) = ExprToIVMap.insert(std::make_pair(S, Phi)); |
| 1443 | if (Inserted) |
| 1444 | continue; |
| 1445 | PHINode *OrigPhi = Pos->second; |
Andrew Trick | f22d957 | 2011-07-20 02:08:58 +0000 | [diff] [blame] | 1446 | |
| 1447 | // If one phi derives from the other via GEPs, types may differ. |
| 1448 | if (OrigPhi->getType() != Phi->getType()) |
| 1449 | continue; |
| 1450 | |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 1451 | // Replacing the congruent phi is sufficient because acyclic redundancy |
| 1452 | // elimination, CSE/GVN, should handle the rest. However, once SCEV proves |
| 1453 | // that a phi is congruent, it's almost certain to be the head of an IV |
| 1454 | // user cycle that is isomorphic with the original phi. So it's worth |
| 1455 | // eagerly cleaning up the common case of a single IV increment. |
| 1456 | if (BasicBlock *LatchBlock = L->getLoopLatch()) { |
| 1457 | Instruction *OrigInc = |
| 1458 | cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock)); |
| 1459 | Instruction *IsomorphicInc = |
| 1460 | cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock)); |
| 1461 | if (OrigInc != IsomorphicInc && |
Andrew Trick | f22d957 | 2011-07-20 02:08:58 +0000 | [diff] [blame] | 1462 | OrigInc->getType() == IsomorphicInc->getType() && |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 1463 | SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) && |
| 1464 | HoistStep(OrigInc, IsomorphicInc, DT)) { |
| 1465 | DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: " |
| 1466 | << *IsomorphicInc << '\n'); |
| 1467 | IsomorphicInc->replaceAllUsesWith(OrigInc); |
| 1468 | DeadInsts.push_back(IsomorphicInc); |
| 1469 | } |
| 1470 | } |
| 1471 | DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n'); |
| 1472 | ++NumElimIV; |
| 1473 | Phi->replaceAllUsesWith(OrigPhi); |
| 1474 | DeadInsts.push_back(Phi); |
| 1475 | } |
| 1476 | } |
| 1477 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1478 | //===----------------------------------------------------------------------===// |
| 1479 | // LinearFunctionTestReplace and its kin. Rewrite the loop exit condition. |
| 1480 | //===----------------------------------------------------------------------===// |
| 1481 | |
Andrew Trick | 5241b79 | 2011-07-18 18:21:35 +0000 | [diff] [blame] | 1482 | // Check for expressions that ScalarEvolution generates to compute |
| 1483 | // BackedgeTakenInfo. If these expressions have not been reduced, then expanding |
| 1484 | // them may incur additional cost (albeit in the loop preheader). |
| 1485 | static bool isHighCostExpansion(const SCEV *S, BranchInst *BI, |
| 1486 | ScalarEvolution *SE) { |
| 1487 | // If the backedge-taken count is a UDiv, it's very likely a UDiv that |
| 1488 | // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a |
| 1489 | // precise expression, rather than a UDiv from the user's code. If we can't |
| 1490 | // find a UDiv in the code with some simple searching, assume the former and |
| 1491 | // forego rewriting the loop. |
| 1492 | if (isa<SCEVUDivExpr>(S)) { |
| 1493 | ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition()); |
| 1494 | if (!OrigCond) return true; |
| 1495 | const SCEV *R = SE->getSCEV(OrigCond->getOperand(1)); |
| 1496 | R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1)); |
| 1497 | if (R != S) { |
| 1498 | const SCEV *L = SE->getSCEV(OrigCond->getOperand(0)); |
| 1499 | L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1)); |
| 1500 | if (L != S) |
| 1501 | return true; |
| 1502 | } |
| 1503 | } |
| 1504 | |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1505 | if (!DisableIVRewrite || ForceLFTR) |
Andrew Trick | 5241b79 | 2011-07-18 18:21:35 +0000 | [diff] [blame] | 1506 | return false; |
| 1507 | |
| 1508 | // Recurse past add expressions, which commonly occur in the |
| 1509 | // BackedgeTakenCount. They may already exist in program code, and if not, |
| 1510 | // they are not too expensive rematerialize. |
| 1511 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { |
| 1512 | for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end(); |
| 1513 | I != E; ++I) { |
| 1514 | if (isHighCostExpansion(*I, BI, SE)) |
| 1515 | return true; |
| 1516 | } |
| 1517 | return false; |
| 1518 | } |
| 1519 | |
| 1520 | // HowManyLessThans uses a Max expression whenever the loop is not guarded by |
| 1521 | // the exit condition. |
| 1522 | if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S)) |
| 1523 | return true; |
| 1524 | |
| 1525 | // If we haven't recognized an expensive SCEV patter, assume its an expression |
| 1526 | // produced by program code. |
| 1527 | return false; |
| 1528 | } |
| 1529 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1530 | /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken |
| 1531 | /// count expression can be safely and cheaply expanded into an instruction |
| 1532 | /// sequence that can be used by LinearFunctionTestReplace. |
| 1533 | static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) { |
| 1534 | const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); |
| 1535 | if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) || |
| 1536 | BackedgeTakenCount->isZero()) |
| 1537 | return false; |
| 1538 | |
| 1539 | if (!L->getExitingBlock()) |
| 1540 | return false; |
| 1541 | |
| 1542 | // Can't rewrite non-branch yet. |
| 1543 | BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator()); |
| 1544 | if (!BI) |
| 1545 | return false; |
| 1546 | |
Andrew Trick | 5241b79 | 2011-07-18 18:21:35 +0000 | [diff] [blame] | 1547 | if (isHighCostExpansion(BackedgeTakenCount, BI, SE)) |
| 1548 | return false; |
| 1549 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1550 | return true; |
| 1551 | } |
| 1552 | |
| 1553 | /// getBackedgeIVType - Get the widest type used by the loop test after peeking |
| 1554 | /// through Truncs. |
| 1555 | /// |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1556 | /// TODO: Unnecessary when ForceLFTR is removed. |
Chris Lattner | db125cf | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1557 | static Type *getBackedgeIVType(Loop *L) { |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1558 | if (!L->getExitingBlock()) |
| 1559 | return 0; |
| 1560 | |
| 1561 | // Can't rewrite non-branch yet. |
| 1562 | BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator()); |
| 1563 | if (!BI) |
| 1564 | return 0; |
| 1565 | |
| 1566 | ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); |
| 1567 | if (!Cond) |
| 1568 | return 0; |
| 1569 | |
Chris Lattner | db125cf | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1570 | Type *Ty = 0; |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1571 | for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end(); |
| 1572 | OI != OE; ++OI) { |
| 1573 | assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types"); |
| 1574 | TruncInst *Trunc = dyn_cast<TruncInst>(*OI); |
| 1575 | if (!Trunc) |
| 1576 | continue; |
| 1577 | |
| 1578 | return Trunc->getSrcTy(); |
| 1579 | } |
| 1580 | return Ty; |
| 1581 | } |
| 1582 | |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1583 | /// isLoopInvariant - Perform a quick domtree based check for loop invariance |
| 1584 | /// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems |
| 1585 | /// gratuitous for this purpose. |
| 1586 | static bool isLoopInvariant(Value *V, Loop *L, DominatorTree *DT) { |
| 1587 | Instruction *Inst = dyn_cast<Instruction>(V); |
| 1588 | if (!Inst) |
| 1589 | return true; |
| 1590 | |
| 1591 | return DT->properlyDominates(Inst->getParent(), L->getHeader()); |
| 1592 | } |
| 1593 | |
| 1594 | /// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop |
| 1595 | /// invariant value to the phi. |
| 1596 | static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) { |
| 1597 | Instruction *IncI = dyn_cast<Instruction>(IncV); |
| 1598 | if (!IncI) |
| 1599 | return 0; |
| 1600 | |
| 1601 | switch (IncI->getOpcode()) { |
| 1602 | case Instruction::Add: |
| 1603 | case Instruction::Sub: |
| 1604 | break; |
| 1605 | case Instruction::GetElementPtr: |
| 1606 | // An IV counter must preserve its type. |
| 1607 | if (IncI->getNumOperands() == 2) |
| 1608 | break; |
| 1609 | default: |
| 1610 | return 0; |
| 1611 | } |
| 1612 | |
| 1613 | PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0)); |
| 1614 | if (Phi && Phi->getParent() == L->getHeader()) { |
| 1615 | if (isLoopInvariant(IncI->getOperand(1), L, DT)) |
| 1616 | return Phi; |
| 1617 | return 0; |
| 1618 | } |
| 1619 | if (IncI->getOpcode() == Instruction::GetElementPtr) |
| 1620 | return 0; |
| 1621 | |
| 1622 | // Allow add/sub to be commuted. |
| 1623 | Phi = dyn_cast<PHINode>(IncI->getOperand(1)); |
| 1624 | if (Phi && Phi->getParent() == L->getHeader()) { |
| 1625 | if (isLoopInvariant(IncI->getOperand(0), L, DT)) |
| 1626 | return Phi; |
| 1627 | } |
| 1628 | return 0; |
| 1629 | } |
| 1630 | |
| 1631 | /// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show |
| 1632 | /// that the current exit test is already sufficiently canonical. |
| 1633 | static bool needsLFTR(Loop *L, DominatorTree *DT) { |
| 1634 | assert(L->getExitingBlock() && "expected loop exit"); |
| 1635 | |
| 1636 | BasicBlock *LatchBlock = L->getLoopLatch(); |
| 1637 | // Don't bother with LFTR if the loop is not properly simplified. |
| 1638 | if (!LatchBlock) |
| 1639 | return false; |
| 1640 | |
| 1641 | BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator()); |
| 1642 | assert(BI && "expected exit branch"); |
| 1643 | |
| 1644 | // Do LFTR to simplify the exit condition to an ICMP. |
| 1645 | ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); |
| 1646 | if (!Cond) |
| 1647 | return true; |
| 1648 | |
| 1649 | // Do LFTR to simplify the exit ICMP to EQ/NE |
| 1650 | ICmpInst::Predicate Pred = Cond->getPredicate(); |
| 1651 | if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ) |
| 1652 | return true; |
| 1653 | |
| 1654 | // Look for a loop invariant RHS |
| 1655 | Value *LHS = Cond->getOperand(0); |
| 1656 | Value *RHS = Cond->getOperand(1); |
| 1657 | if (!isLoopInvariant(RHS, L, DT)) { |
| 1658 | if (!isLoopInvariant(LHS, L, DT)) |
| 1659 | return true; |
| 1660 | std::swap(LHS, RHS); |
| 1661 | } |
| 1662 | // Look for a simple IV counter LHS |
| 1663 | PHINode *Phi = dyn_cast<PHINode>(LHS); |
| 1664 | if (!Phi) |
| 1665 | Phi = getLoopPhiForCounter(LHS, L, DT); |
| 1666 | |
| 1667 | if (!Phi) |
| 1668 | return true; |
| 1669 | |
| 1670 | // Do LFTR if the exit condition's IV is *not* a simple counter. |
| 1671 | Value *IncV = Phi->getIncomingValueForBlock(L->getLoopLatch()); |
| 1672 | return Phi != getLoopPhiForCounter(IncV, L, DT); |
| 1673 | } |
| 1674 | |
| 1675 | /// AlmostDeadIV - Return true if this IV has any uses other than the (soon to |
| 1676 | /// be rewritten) loop exit test. |
| 1677 | static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) { |
| 1678 | int LatchIdx = Phi->getBasicBlockIndex(LatchBlock); |
| 1679 | Value *IncV = Phi->getIncomingValue(LatchIdx); |
| 1680 | |
| 1681 | for (Value::use_iterator UI = Phi->use_begin(), UE = Phi->use_end(); |
| 1682 | UI != UE; ++UI) { |
| 1683 | if (*UI != Cond && *UI != IncV) return false; |
| 1684 | } |
| 1685 | |
| 1686 | for (Value::use_iterator UI = IncV->use_begin(), UE = IncV->use_end(); |
| 1687 | UI != UE; ++UI) { |
| 1688 | if (*UI != Cond && *UI != Phi) return false; |
| 1689 | } |
| 1690 | return true; |
| 1691 | } |
| 1692 | |
| 1693 | /// FindLoopCounter - Find an affine IV in canonical form. |
| 1694 | /// |
| 1695 | /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount |
| 1696 | /// |
| 1697 | /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride. |
| 1698 | /// This is difficult in general for SCEV because of potential overflow. But we |
| 1699 | /// could at least handle constant BECounts. |
| 1700 | static PHINode * |
| 1701 | FindLoopCounter(Loop *L, const SCEV *BECount, |
| 1702 | ScalarEvolution *SE, DominatorTree *DT, const TargetData *TD) { |
| 1703 | // I'm not sure how BECount could be a pointer type, but we definitely don't |
| 1704 | // want to LFTR that. |
| 1705 | if (BECount->getType()->isPointerTy()) |
| 1706 | return 0; |
| 1707 | |
| 1708 | uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType()); |
| 1709 | |
| 1710 | Value *Cond = |
| 1711 | cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition(); |
| 1712 | |
| 1713 | // Loop over all of the PHI nodes, looking for a simple counter. |
| 1714 | PHINode *BestPhi = 0; |
| 1715 | const SCEV *BestInit = 0; |
| 1716 | BasicBlock *LatchBlock = L->getLoopLatch(); |
| 1717 | assert(LatchBlock && "needsLFTR should guarantee a loop latch"); |
| 1718 | |
| 1719 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
| 1720 | PHINode *Phi = cast<PHINode>(I); |
| 1721 | if (!SE->isSCEVable(Phi->getType())) |
| 1722 | continue; |
| 1723 | |
| 1724 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi)); |
| 1725 | if (!AR || AR->getLoop() != L || !AR->isAffine()) |
| 1726 | continue; |
| 1727 | |
| 1728 | // AR may be a pointer type, while BECount is an integer type. |
| 1729 | // AR may be wider than BECount. With eq/ne tests overflow is immaterial. |
| 1730 | // AR may not be a narrower type, or we may never exit. |
| 1731 | uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType()); |
| 1732 | if (PhiWidth < BCWidth || (TD && !TD->isLegalInteger(PhiWidth))) |
| 1733 | continue; |
| 1734 | |
| 1735 | const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)); |
| 1736 | if (!Step || !Step->isOne()) |
| 1737 | continue; |
| 1738 | |
| 1739 | int LatchIdx = Phi->getBasicBlockIndex(LatchBlock); |
| 1740 | Value *IncV = Phi->getIncomingValue(LatchIdx); |
| 1741 | if (getLoopPhiForCounter(IncV, L, DT) != Phi) |
| 1742 | continue; |
| 1743 | |
| 1744 | const SCEV *Init = AR->getStart(); |
| 1745 | |
| 1746 | if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) { |
| 1747 | // Don't force a live loop counter if another IV can be used. |
| 1748 | if (AlmostDeadIV(Phi, LatchBlock, Cond)) |
| 1749 | continue; |
| 1750 | |
| 1751 | // Prefer to count-from-zero. This is a more "canonical" counter form. It |
| 1752 | // also prefers integer to pointer IVs. |
| 1753 | if (BestInit->isZero() != Init->isZero()) { |
| 1754 | if (BestInit->isZero()) |
| 1755 | continue; |
| 1756 | } |
| 1757 | // If two IVs both count from zero or both count from nonzero then the |
| 1758 | // narrower is likely a dead phi that has been widened. Use the wider phi |
| 1759 | // to allow the other to be eliminated. |
| 1760 | if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType())) |
| 1761 | continue; |
| 1762 | } |
| 1763 | BestPhi = Phi; |
| 1764 | BestInit = Init; |
| 1765 | } |
| 1766 | return BestPhi; |
| 1767 | } |
| 1768 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1769 | /// LinearFunctionTestReplace - This method rewrites the exit condition of the |
| 1770 | /// loop to be a canonical != comparison against the incremented loop induction |
| 1771 | /// variable. This pass is able to rewrite the exit tests of any loop where the |
| 1772 | /// SCEV analysis can determine a loop-invariant trip count of the loop, which |
| 1773 | /// is actually a much broader range than just linear tests. |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1774 | Value *IndVarSimplify:: |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1775 | LinearFunctionTestReplace(Loop *L, |
| 1776 | const SCEV *BackedgeTakenCount, |
| 1777 | PHINode *IndVar, |
| 1778 | SCEVExpander &Rewriter) { |
| 1779 | assert(canExpandBackedgeTakenCount(L, SE) && "precondition"); |
| 1780 | BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator()); |
| 1781 | |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1782 | // In DisableIVRewrite mode, IndVar is not necessarily a canonical IV. In this |
| 1783 | // mode, LFTR can ignore IV overflow and truncate to the width of |
| 1784 | // BECount. This avoids materializing the add(zext(add)) expression. |
| 1785 | Type *CntTy = DisableIVRewrite ? |
| 1786 | BackedgeTakenCount->getType() : IndVar->getType(); |
| 1787 | |
| 1788 | const SCEV *IVLimit = BackedgeTakenCount; |
| 1789 | |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1790 | // If the exiting block is not the same as the backedge block, we must compare |
| 1791 | // against the preincremented value, otherwise we prefer to compare against |
| 1792 | // the post-incremented value. |
| 1793 | Value *CmpIndVar; |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1794 | if (L->getExitingBlock() == L->getLoopLatch()) { |
| 1795 | // Add one to the "backedge-taken" count to get the trip count. |
| 1796 | // If this addition may overflow, we have to be more pessimistic and |
| 1797 | // cast the induction variable before doing the add. |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1798 | const SCEV *N = |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1799 | SE->getAddExpr(IVLimit, SE->getConstant(IVLimit->getType(), 1)); |
| 1800 | if (CntTy == IVLimit->getType()) |
| 1801 | IVLimit = N; |
| 1802 | else { |
| 1803 | const SCEV *Zero = SE->getConstant(IVLimit->getType(), 0); |
| 1804 | if ((isa<SCEVConstant>(N) && !N->isZero()) || |
| 1805 | SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) { |
| 1806 | // No overflow. Cast the sum. |
| 1807 | IVLimit = SE->getTruncateOrZeroExtend(N, CntTy); |
| 1808 | } else { |
| 1809 | // Potential overflow. Cast before doing the add. |
| 1810 | IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy); |
| 1811 | IVLimit = SE->getAddExpr(IVLimit, SE->getConstant(CntTy, 1)); |
| 1812 | } |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1813 | } |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1814 | // The BackedgeTaken expression contains the number of times that the |
| 1815 | // backedge branches to the loop header. This is one less than the |
| 1816 | // number of times the loop executes, so use the incremented indvar. |
| 1817 | CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock()); |
| 1818 | } else { |
| 1819 | // We have to use the preincremented value... |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1820 | IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy); |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1821 | CmpIndVar = IndVar; |
| 1822 | } |
| 1823 | |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1824 | // For unit stride, IVLimit = Start + BECount with 2's complement overflow. |
| 1825 | // So for, non-zero start compute the IVLimit here. |
| 1826 | bool isPtrIV = false; |
| 1827 | Type *CmpTy = CntTy; |
| 1828 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar)); |
| 1829 | assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter"); |
| 1830 | if (!AR->getStart()->isZero()) { |
| 1831 | assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride"); |
| 1832 | const SCEV *IVInit = AR->getStart(); |
| 1833 | |
| 1834 | // For pointer types, sign extend BECount in order to materialize a GEP. |
| 1835 | // Note that for DisableIVRewrite, we never run SCEVExpander on a |
| 1836 | // pointer type, because we must preserve the existing GEPs. Instead we |
| 1837 | // directly generate a GEP later. |
| 1838 | if (IVInit->getType()->isPointerTy()) { |
| 1839 | isPtrIV = true; |
| 1840 | CmpTy = SE->getEffectiveSCEVType(IVInit->getType()); |
| 1841 | IVLimit = SE->getTruncateOrSignExtend(IVLimit, CmpTy); |
| 1842 | } |
| 1843 | // For integer types, truncate the IV before computing IVInit + BECount. |
| 1844 | else { |
| 1845 | if (SE->getTypeSizeInBits(IVInit->getType()) |
| 1846 | > SE->getTypeSizeInBits(CmpTy)) |
| 1847 | IVInit = SE->getTruncateExpr(IVInit, CmpTy); |
| 1848 | |
| 1849 | IVLimit = SE->getAddExpr(IVInit, IVLimit); |
| 1850 | } |
| 1851 | } |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1852 | // Expand the code for the iteration count. |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1853 | IRBuilder<> Builder(BI); |
| 1854 | |
| 1855 | assert(SE->isLoopInvariant(IVLimit, L) && |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1856 | "Computed iteration count is not loop invariant!"); |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1857 | Value *ExitCnt = Rewriter.expandCodeFor(IVLimit, CmpTy, BI); |
| 1858 | |
| 1859 | // Create a gep for IVInit + IVLimit from on an existing pointer base. |
| 1860 | assert(isPtrIV == IndVar->getType()->isPointerTy() && |
| 1861 | "IndVar type must match IVInit type"); |
| 1862 | if (isPtrIV) { |
| 1863 | Value *IVStart = IndVar->getIncomingValueForBlock(L->getLoopPreheader()); |
| 1864 | assert(AR->getStart() == SE->getSCEV(IVStart) && "bad loop counter"); |
Andrew Trick | 41e0d4e | 2011-07-18 21:15:03 +0000 | [diff] [blame] | 1865 | assert(SE->getSizeOfExpr( |
| 1866 | cast<PointerType>(IVStart->getType())->getElementType())->isOne() |
| 1867 | && "unit stride pointer IV must be i8*"); |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1868 | |
| 1869 | Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator()); |
| 1870 | ExitCnt = Builder.CreateGEP(IVStart, ExitCnt, "lftr.limit"); |
| 1871 | Builder.SetInsertPoint(BI); |
| 1872 | } |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1873 | |
| 1874 | // Insert a new icmp_ne or icmp_eq instruction before the branch. |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1875 | ICmpInst::Predicate P; |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1876 | if (L->contains(BI->getSuccessor(0))) |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1877 | P = ICmpInst::ICMP_NE; |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1878 | else |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1879 | P = ICmpInst::ICMP_EQ; |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1880 | |
| 1881 | DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n" |
| 1882 | << " LHS:" << *CmpIndVar << '\n' |
| 1883 | << " op:\t" |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1884 | << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n" |
| 1885 | << " RHS:\t" << *ExitCnt << "\n" |
| 1886 | << " Expr:\t" << *IVLimit << "\n"); |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1887 | |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 1888 | if (SE->getTypeSizeInBits(CmpIndVar->getType()) |
| 1889 | > SE->getTypeSizeInBits(CmpTy)) { |
| 1890 | CmpIndVar = Builder.CreateTrunc(CmpIndVar, CmpTy, "lftr.wideiv"); |
| 1891 | } |
| 1892 | |
| 1893 | Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond"); |
Andrew Trick | 1a54bb2 | 2011-07-12 00:08:50 +0000 | [diff] [blame] | 1894 | Value *OrigCond = BI->getCondition(); |
| 1895 | // It's tempting to use replaceAllUsesWith here to fully replace the old |
| 1896 | // comparison, but that's not immediately safe, since users of the old |
| 1897 | // comparison may not be dominated by the new comparison. Instead, just |
| 1898 | // update the branch to use the new comparison; in the common case this |
| 1899 | // will make old comparison dead. |
| 1900 | BI->setCondition(Cond); |
| 1901 | DeadInsts.push_back(OrigCond); |
| 1902 | |
| 1903 | ++NumLFTR; |
| 1904 | Changed = true; |
| 1905 | return Cond; |
| 1906 | } |
| 1907 | |
| 1908 | //===----------------------------------------------------------------------===// |
| 1909 | // SinkUnusedInvariants. A late subpass to cleanup loop preheaders. |
| 1910 | //===----------------------------------------------------------------------===// |
| 1911 | |
| 1912 | /// If there's a single exit block, sink any loop-invariant values that |
| 1913 | /// were defined in the preheader but not used inside the loop into the |
| 1914 | /// exit block to reduce register pressure in the loop. |
| 1915 | void IndVarSimplify::SinkUnusedInvariants(Loop *L) { |
| 1916 | BasicBlock *ExitBlock = L->getExitBlock(); |
| 1917 | if (!ExitBlock) return; |
| 1918 | |
| 1919 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 1920 | if (!Preheader) return; |
| 1921 | |
| 1922 | Instruction *InsertPt = ExitBlock->getFirstNonPHI(); |
| 1923 | BasicBlock::iterator I = Preheader->getTerminator(); |
| 1924 | while (I != Preheader->begin()) { |
| 1925 | --I; |
| 1926 | // New instructions were inserted at the end of the preheader. |
| 1927 | if (isa<PHINode>(I)) |
| 1928 | break; |
| 1929 | |
| 1930 | // Don't move instructions which might have side effects, since the side |
| 1931 | // effects need to complete before instructions inside the loop. Also don't |
| 1932 | // move instructions which might read memory, since the loop may modify |
| 1933 | // memory. Note that it's okay if the instruction might have undefined |
| 1934 | // behavior: LoopSimplify guarantees that the preheader dominates the exit |
| 1935 | // block. |
| 1936 | if (I->mayHaveSideEffects() || I->mayReadFromMemory()) |
| 1937 | continue; |
| 1938 | |
| 1939 | // Skip debug info intrinsics. |
| 1940 | if (isa<DbgInfoIntrinsic>(I)) |
| 1941 | continue; |
| 1942 | |
| 1943 | // Don't sink static AllocaInsts out of the entry block, which would |
| 1944 | // turn them into dynamic allocas! |
| 1945 | if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) |
| 1946 | if (AI->isStaticAlloca()) |
| 1947 | continue; |
| 1948 | |
| 1949 | // Determine if there is a use in or before the loop (direct or |
| 1950 | // otherwise). |
| 1951 | bool UsedInLoop = false; |
| 1952 | for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); |
| 1953 | UI != UE; ++UI) { |
| 1954 | User *U = *UI; |
| 1955 | BasicBlock *UseBB = cast<Instruction>(U)->getParent(); |
| 1956 | if (PHINode *P = dyn_cast<PHINode>(U)) { |
| 1957 | unsigned i = |
| 1958 | PHINode::getIncomingValueNumForOperand(UI.getOperandNo()); |
| 1959 | UseBB = P->getIncomingBlock(i); |
| 1960 | } |
| 1961 | if (UseBB == Preheader || L->contains(UseBB)) { |
| 1962 | UsedInLoop = true; |
| 1963 | break; |
| 1964 | } |
| 1965 | } |
| 1966 | |
| 1967 | // If there is, the def must remain in the preheader. |
| 1968 | if (UsedInLoop) |
| 1969 | continue; |
| 1970 | |
| 1971 | // Otherwise, sink it to the exit block. |
| 1972 | Instruction *ToMove = I; |
| 1973 | bool Done = false; |
| 1974 | |
| 1975 | if (I != Preheader->begin()) { |
| 1976 | // Skip debug info intrinsics. |
| 1977 | do { |
| 1978 | --I; |
| 1979 | } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin()); |
| 1980 | |
| 1981 | if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin()) |
| 1982 | Done = true; |
| 1983 | } else { |
| 1984 | Done = true; |
| 1985 | } |
| 1986 | |
| 1987 | ToMove->moveBefore(InsertPt); |
| 1988 | if (Done) break; |
| 1989 | InsertPt = ToMove; |
| 1990 | } |
| 1991 | } |
| 1992 | |
| 1993 | //===----------------------------------------------------------------------===// |
| 1994 | // IndVarSimplify driver. Manage several subpasses of IV simplification. |
| 1995 | //===----------------------------------------------------------------------===// |
| 1996 | |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame] | 1997 | bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) { |
Dan Gohman | a528382 | 2010-06-18 01:35:11 +0000 | [diff] [blame] | 1998 | // If LoopSimplify form is not available, stay out of trouble. Some notes: |
| 1999 | // - LSR currently only supports LoopSimplify-form loops. Indvars' |
| 2000 | // canonicalization can be a pessimization without LSR to "clean up" |
| 2001 | // afterwards. |
| 2002 | // - We depend on having a preheader; in particular, |
| 2003 | // Loop::getCanonicalInductionVariable only supports loops with preheaders, |
| 2004 | // and we're in trouble if we can't find the induction variable even when |
| 2005 | // we've manually inserted one. |
| 2006 | if (!L->isLoopSimplifyForm()) |
| 2007 | return false; |
| 2008 | |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 2009 | if (!DisableIVRewrite) |
| 2010 | IU = &getAnalysis<IVUsers>(); |
Devang Patel | 5ee9997 | 2007-03-07 06:39:01 +0000 | [diff] [blame] | 2011 | LI = &getAnalysis<LoopInfo>(); |
| 2012 | SE = &getAnalysis<ScalarEvolution>(); |
Dan Gohman | de53dc0 | 2009-06-27 05:16:57 +0000 | [diff] [blame] | 2013 | DT = &getAnalysis<DominatorTree>(); |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 2014 | TD = getAnalysisIfAvailable<TargetData>(); |
| 2015 | |
Andrew Trick | b12a754 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 2016 | DeadInsts.clear(); |
Devang Patel | 5ee9997 | 2007-03-07 06:39:01 +0000 | [diff] [blame] | 2017 | Changed = false; |
Dan Gohman | 60f8a63 | 2009-02-17 20:49:49 +0000 | [diff] [blame] | 2018 | |
Dan Gohman | 2d1be87 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 2019 | // If there are any floating-point recurrences, attempt to |
Dan Gohman | 60f8a63 | 2009-02-17 20:49:49 +0000 | [diff] [blame] | 2020 | // transform them to use integer recurrences. |
| 2021 | RewriteNonIntegerIVs(L); |
| 2022 | |
Dan Gohman | 0bba49c | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2023 | const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); |
Chris Lattner | 9caed54 | 2007-03-04 01:00:28 +0000 | [diff] [blame] | 2024 | |
Dan Gohman | 667d787 | 2009-06-26 22:53:46 +0000 | [diff] [blame] | 2025 | // Create a rewriter object which we'll use to transform the code with. |
Andrew Trick | 5e7645b | 2011-06-28 05:07:32 +0000 | [diff] [blame] | 2026 | SCEVExpander Rewriter(*SE, "indvars"); |
Andrew Trick | 156d460 | 2011-06-27 23:17:44 +0000 | [diff] [blame] | 2027 | |
| 2028 | // Eliminate redundant IV users. |
Andrew Trick | 15832f6 | 2011-06-28 02:49:20 +0000 | [diff] [blame] | 2029 | // |
| 2030 | // Simplification works best when run before other consumers of SCEV. We |
| 2031 | // attempt to avoid evaluating SCEVs for sign/zero extend operations until |
| 2032 | // other expressions involving loop IVs have been evaluated. This helps SCEV |
Andrew Trick | 99a92f6 | 2011-06-28 16:45:04 +0000 | [diff] [blame] | 2033 | // set no-wrap flags before normalizing sign/zero extension. |
Andrew Trick | 156d460 | 2011-06-27 23:17:44 +0000 | [diff] [blame] | 2034 | if (DisableIVRewrite) { |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 2035 | Rewriter.disableCanonicalMode(); |
Andrew Trick | 156d460 | 2011-06-27 23:17:44 +0000 | [diff] [blame] | 2036 | SimplifyIVUsersNoRewrite(L, Rewriter); |
| 2037 | } |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 2038 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 2039 | // Check to see if this loop has a computable loop-invariant execution count. |
| 2040 | // If so, this means that we can compute the final value of any expressions |
| 2041 | // that are recurrent in the loop, and substitute the exit values from the |
| 2042 | // loop into any instructions outside of the loop that use the final values of |
| 2043 | // the current expressions. |
Chris Lattner | 3dec1f2 | 2002-05-10 15:38:35 +0000 | [diff] [blame] | 2044 | // |
Dan Gohman | 46bdfb0 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 2045 | if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) |
Dan Gohman | 454d26d | 2010-02-22 04:11:59 +0000 | [diff] [blame] | 2046 | RewriteLoopExitValues(L, Rewriter); |
Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 2047 | |
Andrew Trick | f85092c | 2011-05-20 18:25:42 +0000 | [diff] [blame] | 2048 | // Eliminate redundant IV users. |
Andrew Trick | 156d460 | 2011-06-27 23:17:44 +0000 | [diff] [blame] | 2049 | if (!DisableIVRewrite) |
Andrew Trick | 2fabd46 | 2011-06-21 03:22:38 +0000 | [diff] [blame] | 2050 | SimplifyIVUsers(Rewriter); |
Dan Gohman | a590b79 | 2010-04-13 01:46:36 +0000 | [diff] [blame] | 2051 | |
Andrew Trick | 6f684b0 | 2011-07-16 01:06:48 +0000 | [diff] [blame] | 2052 | // Eliminate redundant IV cycles. |
Andrew Trick | 037d1c0 | 2011-07-06 20:50:43 +0000 | [diff] [blame] | 2053 | if (DisableIVRewrite) |
| 2054 | SimplifyCongruentIVs(L); |
| 2055 | |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 2056 | // Compute the type of the largest recurrence expression, and decide whether |
| 2057 | // a canonical induction variable should be inserted. |
Chris Lattner | db125cf | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2058 | Type *LargestType = 0; |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 2059 | bool NeedCannIV = false; |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 2060 | bool ReuseIVForExit = DisableIVRewrite && !ForceLFTR; |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 2061 | bool ExpandBECount = canExpandBackedgeTakenCount(L, SE); |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 2062 | if (ExpandBECount && !ReuseIVForExit) { |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 2063 | // If we have a known trip count and a single exit block, we'll be |
| 2064 | // rewriting the loop exit test condition below, which requires a |
| 2065 | // canonical induction variable. |
Andrew Trick | 4dfdf24 | 2011-05-03 22:24:10 +0000 | [diff] [blame] | 2066 | NeedCannIV = true; |
Chris Lattner | db125cf | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2067 | Type *Ty = BackedgeTakenCount->getType(); |
Andrew Trick | 03d3d3b | 2011-05-25 04:42:22 +0000 | [diff] [blame] | 2068 | if (DisableIVRewrite) { |
| 2069 | // In this mode, SimplifyIVUsers may have already widened the IV used by |
| 2070 | // the backedge test and inserted a Trunc on the compare's operand. Get |
| 2071 | // the wider type to avoid creating a redundant narrow IV only used by the |
| 2072 | // loop test. |
| 2073 | LargestType = getBackedgeIVType(L); |
| 2074 | } |
Andrew Trick | 4dfdf24 | 2011-05-03 22:24:10 +0000 | [diff] [blame] | 2075 | if (!LargestType || |
| 2076 | SE->getTypeSizeInBits(Ty) > |
| 2077 | SE->getTypeSizeInBits(LargestType)) |
| 2078 | LargestType = SE->getEffectiveSCEVType(Ty); |
Chris Lattner | f50af08 | 2004-04-17 18:08:33 +0000 | [diff] [blame] | 2079 | } |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 2080 | if (!DisableIVRewrite) { |
| 2081 | for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) { |
| 2082 | NeedCannIV = true; |
Chris Lattner | db125cf | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2083 | Type *Ty = |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 2084 | SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType()); |
| 2085 | if (!LargestType || |
| 2086 | SE->getTypeSizeInBits(Ty) > |
Dan Gohman | af79fb5 | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 2087 | SE->getTypeSizeInBits(LargestType)) |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 2088 | LargestType = Ty; |
| 2089 | } |
Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 2090 | } |
| 2091 | |
Dan Gohman | f451cb8 | 2010-02-10 16:03:48 +0000 | [diff] [blame] | 2092 | // Now that we know the largest of the induction variable expressions |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 2093 | // in this loop, insert a canonical induction variable of the largest size. |
Dan Gohman | 43ef3fb | 2010-07-20 17:18:52 +0000 | [diff] [blame] | 2094 | PHINode *IndVar = 0; |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 2095 | if (NeedCannIV) { |
Dan Gohman | 8566963 | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 2096 | // Check to see if the loop already has any canonical-looking induction |
| 2097 | // variables. If any are present and wider than the planned canonical |
| 2098 | // induction variable, temporarily remove them, so that the Rewriter |
| 2099 | // doesn't attempt to reuse them. |
| 2100 | SmallVector<PHINode *, 2> OldCannIVs; |
| 2101 | while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) { |
Dan Gohman | 4d8414f | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 2102 | if (SE->getTypeSizeInBits(OldCannIV->getType()) > |
| 2103 | SE->getTypeSizeInBits(LargestType)) |
| 2104 | OldCannIV->removeFromParent(); |
| 2105 | else |
Dan Gohman | 8566963 | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 2106 | break; |
| 2107 | OldCannIVs.push_back(OldCannIV); |
Dan Gohman | 4d8414f | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 2108 | } |
| 2109 | |
Dan Gohman | 667d787 | 2009-06-26 22:53:46 +0000 | [diff] [blame] | 2110 | IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType); |
Dan Gohman | 4d8414f | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 2111 | |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame] | 2112 | ++NumInserted; |
| 2113 | Changed = true; |
David Greene | f67ef31 | 2010-01-05 01:27:06 +0000 | [diff] [blame] | 2114 | DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n'); |
Dan Gohman | 4d8414f | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 2115 | |
| 2116 | // Now that the official induction variable is established, reinsert |
Dan Gohman | 8566963 | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 2117 | // any old canonical-looking variables after it so that the IR remains |
| 2118 | // consistent. They will be deleted as part of the dead-PHI deletion at |
Dan Gohman | 4d8414f | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 2119 | // the end of the pass. |
Dan Gohman | 8566963 | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 2120 | while (!OldCannIVs.empty()) { |
| 2121 | PHINode *OldCannIV = OldCannIVs.pop_back_val(); |
| 2122 | OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI()); |
| 2123 | } |
Dan Gohman | d19534a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 2124 | } |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 2125 | else if (ExpandBECount && ReuseIVForExit && needsLFTR(L, DT)) { |
| 2126 | IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD); |
| 2127 | } |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame] | 2128 | // If we have a trip count expression, rewrite the loop's exit condition |
| 2129 | // using it. We can currently only handle loops with a single exit. |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 2130 | Value *NewICmp = 0; |
| 2131 | if (ExpandBECount && IndVar) { |
Andrew Trick | 5614769 | 2011-07-16 01:18:53 +0000 | [diff] [blame] | 2132 | // Check preconditions for proper SCEVExpander operation. SCEV does not |
| 2133 | // express SCEVExpander's dependencies, such as LoopSimplify. Instead any |
| 2134 | // pass that uses the SCEVExpander must do it. This does not work well for |
| 2135 | // loop passes because SCEVExpander makes assumptions about all loops, while |
| 2136 | // LoopPassManager only forces the current loop to be simplified. |
| 2137 | // |
| 2138 | // FIXME: SCEV expansion has no way to bail out, so the caller must |
| 2139 | // explicitly check any assumptions made by SCEV. Brittle. |
| 2140 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount); |
| 2141 | if (!AR || AR->getLoop()->getLoopPreheader()) |
| 2142 | NewICmp = |
| 2143 | LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter); |
Chris Lattner | fcb81f5 | 2004-04-22 14:59:40 +0000 | [diff] [blame] | 2144 | } |
Andrew Trick | b12a754 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 2145 | // Rewrite IV-derived expressions. |
Andrew Trick | 37da408 | 2011-05-04 02:10:13 +0000 | [diff] [blame] | 2146 | if (!DisableIVRewrite) |
| 2147 | RewriteIVExpressions(L, Rewriter); |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame] | 2148 | |
Andrew Trick | b12a754 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 2149 | // Clear the rewriter cache, because values that are in the rewriter's cache |
| 2150 | // can be deleted in the loop below, causing the AssertingVH in the cache to |
| 2151 | // trigger. |
| 2152 | Rewriter.clear(); |
| 2153 | |
| 2154 | // Now that we're done iterating through lists, clean up any instructions |
| 2155 | // which are now dead. |
| 2156 | while (!DeadInsts.empty()) |
| 2157 | if (Instruction *Inst = |
| 2158 | dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val())) |
| 2159 | RecursivelyDeleteTriviallyDeadInstructions(Inst); |
| 2160 | |
Dan Gohman | 667d787 | 2009-06-26 22:53:46 +0000 | [diff] [blame] | 2161 | // The Rewriter may not be used from this point on. |
Torok Edwin | 3d43138 | 2009-05-24 20:08:21 +0000 | [diff] [blame] | 2162 | |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 2163 | // Loop-invariant instructions in the preheader that aren't used in the |
| 2164 | // loop may be sunk below the loop to reduce register pressure. |
Dan Gohman | 667d787 | 2009-06-26 22:53:46 +0000 | [diff] [blame] | 2165 | SinkUnusedInvariants(L); |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 2166 | |
| 2167 | // For completeness, inform IVUsers of the IV use in the newly-created |
| 2168 | // loop exit test instruction. |
Andrew Trick | fc933c0 | 2011-07-18 20:32:31 +0000 | [diff] [blame] | 2169 | if (IU && NewICmp) { |
| 2170 | ICmpInst *NewICmpInst = dyn_cast<ICmpInst>(NewICmp); |
| 2171 | if (NewICmpInst) |
| 2172 | IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(0))); |
| 2173 | } |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 2174 | // Clean up dead instructions. |
Dan Gohman | 9fff218 | 2010-01-05 16:31:45 +0000 | [diff] [blame] | 2175 | Changed |= DeleteDeadPHIs(L->getHeader()); |
Dan Gohman | 81db61a | 2009-05-12 02:17:14 +0000 | [diff] [blame] | 2176 | // Check a post-condition. |
Andrew Trick | f6a0dba | 2011-07-18 18:44:20 +0000 | [diff] [blame] | 2177 | assert(L->isLCSSAForm(*DT) && |
| 2178 | "Indvars did not leave the loop in lcssa form!"); |
| 2179 | |
| 2180 | // Verify that LFTR, and any other change have not interfered with SCEV's |
| 2181 | // ability to compute trip count. |
| 2182 | #ifndef NDEBUG |
| 2183 | if (DisableIVRewrite && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) { |
| 2184 | SE->forgetLoop(L); |
| 2185 | const SCEV *NewBECount = SE->getBackedgeTakenCount(L); |
| 2186 | if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) < |
| 2187 | SE->getTypeSizeInBits(NewBECount->getType())) |
| 2188 | NewBECount = SE->getTruncateOrNoop(NewBECount, |
| 2189 | BackedgeTakenCount->getType()); |
| 2190 | else |
| 2191 | BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, |
| 2192 | NewBECount->getType()); |
| 2193 | assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV"); |
| 2194 | } |
| 2195 | #endif |
| 2196 | |
Devang Patel | 5ee9997 | 2007-03-07 06:39:01 +0000 | [diff] [blame] | 2197 | return Changed; |
Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 2198 | } |