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