Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 1 | //===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file was developed by Nate Begeman and is distributed under the |
| 6 | // University of Illinois Open Source License. See LICENSE.TXT for details. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass performs a strength reduction on array references inside loops that |
| 11 | // have as one or more of their components the loop induction variable. This is |
| 12 | // accomplished by creating a new Value to hold the initial value of the array |
| 13 | // access for the first iteration, and then creating a new GEP instruction in |
| 14 | // the loop to increment the value by the appropriate amount. |
| 15 | // |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 16 | //===----------------------------------------------------------------------===// |
| 17 | |
Chris Lattner | bb78c97 | 2005-08-03 23:30:08 +0000 | [diff] [blame] | 18 | #define DEBUG_TYPE "loop-reduce" |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 19 | #include "llvm/Transforms/Scalar.h" |
| 20 | #include "llvm/Constants.h" |
| 21 | #include "llvm/Instructions.h" |
| 22 | #include "llvm/Type.h" |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 23 | #include "llvm/DerivedTypes.h" |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/Dominators.h" |
| 25 | #include "llvm/Analysis/LoopInfo.h" |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 27 | #include "llvm/Support/CFG.h" |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 28 | #include "llvm/Support/GetElementPtrTypeIterator.h" |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 29 | #include "llvm/Transforms/Utils/Local.h" |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 30 | #include "llvm/Target/TargetData.h" |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 31 | #include "llvm/ADT/Statistic.h" |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 32 | #include "llvm/Support/Debug.h" |
Jeff Cohen | c500991 | 2005-07-30 18:22:27 +0000 | [diff] [blame] | 33 | #include <algorithm> |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 34 | #include <set> |
| 35 | using namespace llvm; |
| 36 | |
| 37 | namespace { |
| 38 | Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced"); |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 39 | Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted"); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 40 | |
Chris Lattner | 430d002 | 2005-08-03 22:21:05 +0000 | [diff] [blame] | 41 | /// IVStrideUse - Keep track of one use of a strided induction variable, where |
| 42 | /// the stride is stored externally. The Offset member keeps track of the |
| 43 | /// offset from the IV, User is the actual user of the operand, and 'Operand' |
| 44 | /// is the operand # of the User that is the use. |
| 45 | struct IVStrideUse { |
| 46 | SCEVHandle Offset; |
| 47 | Instruction *User; |
| 48 | Value *OperandValToReplace; |
Chris Lattner | 9bfa6f8 | 2005-08-08 05:28:22 +0000 | [diff] [blame] | 49 | |
| 50 | // isUseOfPostIncrementedValue - True if this should use the |
| 51 | // post-incremented version of this IV, not the preincremented version. |
| 52 | // This can only be set in special cases, such as the terminating setcc |
| 53 | // instruction for a loop. |
| 54 | bool isUseOfPostIncrementedValue; |
Chris Lattner | 430d002 | 2005-08-03 22:21:05 +0000 | [diff] [blame] | 55 | |
| 56 | IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O) |
Chris Lattner | 9bfa6f8 | 2005-08-08 05:28:22 +0000 | [diff] [blame] | 57 | : Offset(Offs), User(U), OperandValToReplace(O), |
| 58 | isUseOfPostIncrementedValue(false) {} |
Chris Lattner | 430d002 | 2005-08-03 22:21:05 +0000 | [diff] [blame] | 59 | }; |
| 60 | |
| 61 | /// IVUsersOfOneStride - This structure keeps track of all instructions that |
| 62 | /// have an operand that is based on the trip count multiplied by some stride. |
| 63 | /// The stride for all of these users is common and kept external to this |
| 64 | /// structure. |
| 65 | struct IVUsersOfOneStride { |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 66 | /// Users - Keep track of all of the users of this stride as well as the |
Chris Lattner | 430d002 | 2005-08-03 22:21:05 +0000 | [diff] [blame] | 67 | /// initial value and the operand that uses the IV. |
| 68 | std::vector<IVStrideUse> Users; |
| 69 | |
| 70 | void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) { |
| 71 | Users.push_back(IVStrideUse(Offset, User, Operand)); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 72 | } |
| 73 | }; |
| 74 | |
| 75 | |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 76 | class LoopStrengthReduce : public FunctionPass { |
| 77 | LoopInfo *LI; |
| 78 | DominatorSet *DS; |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 79 | ScalarEvolution *SE; |
| 80 | const TargetData *TD; |
| 81 | const Type *UIntPtrTy; |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 82 | bool Changed; |
Chris Lattner | 75a44e1 | 2005-08-02 02:52:02 +0000 | [diff] [blame] | 83 | |
| 84 | /// MaxTargetAMSize - This is the maximum power-of-two scale value that the |
| 85 | /// target can handle for free with its addressing modes. |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 86 | unsigned MaxTargetAMSize; |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 87 | |
| 88 | /// IVUsesByStride - Keep track of all uses of induction variables that we |
| 89 | /// are interested in. The key of the map is the stride of the access. |
Chris Lattner | 430d002 | 2005-08-03 22:21:05 +0000 | [diff] [blame] | 90 | std::map<Value*, IVUsersOfOneStride> IVUsesByStride; |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 91 | |
Chris Lattner | 6f286b7 | 2005-08-04 01:19:13 +0000 | [diff] [blame] | 92 | /// CastedValues - As we need to cast values to uintptr_t, this keeps track |
| 93 | /// of the casted version of each value. This is accessed by |
| 94 | /// getCastedVersionOf. |
| 95 | std::map<Value*, Value*> CastedPointers; |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 96 | |
| 97 | /// DeadInsts - Keep track of instructions we may have made dead, so that |
| 98 | /// we can remove them after we are done working. |
| 99 | std::set<Instruction*> DeadInsts; |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 100 | public: |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 101 | LoopStrengthReduce(unsigned MTAMS = 1) |
| 102 | : MaxTargetAMSize(MTAMS) { |
| 103 | } |
| 104 | |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 105 | virtual bool runOnFunction(Function &) { |
| 106 | LI = &getAnalysis<LoopInfo>(); |
| 107 | DS = &getAnalysis<DominatorSet>(); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 108 | SE = &getAnalysis<ScalarEvolution>(); |
| 109 | TD = &getAnalysis<TargetData>(); |
| 110 | UIntPtrTy = TD->getIntPtrType(); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 111 | Changed = false; |
| 112 | |
| 113 | for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) |
| 114 | runOnLoop(*I); |
Chris Lattner | 6f286b7 | 2005-08-04 01:19:13 +0000 | [diff] [blame] | 115 | |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 116 | return Changed; |
| 117 | } |
| 118 | |
| 119 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 120 | AU.setPreservesCFG(); |
Jeff Cohen | 39751c3 | 2005-02-27 19:37:07 +0000 | [diff] [blame] | 121 | AU.addRequiredID(LoopSimplifyID); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 122 | AU.addRequired<LoopInfo>(); |
| 123 | AU.addRequired<DominatorSet>(); |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 124 | AU.addRequired<TargetData>(); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 125 | AU.addRequired<ScalarEvolution>(); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 126 | } |
Chris Lattner | 6f286b7 | 2005-08-04 01:19:13 +0000 | [diff] [blame] | 127 | |
| 128 | /// getCastedVersionOf - Return the specified value casted to uintptr_t. |
| 129 | /// |
| 130 | Value *getCastedVersionOf(Value *V); |
| 131 | private: |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 132 | void runOnLoop(Loop *L); |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 133 | bool AddUsersIfInteresting(Instruction *I, Loop *L, |
| 134 | std::set<Instruction*> &Processed); |
| 135 | SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L); |
| 136 | |
Chris Lattner | 9bfa6f8 | 2005-08-08 05:28:22 +0000 | [diff] [blame] | 137 | void OptimizeIndvars(Loop *L); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 138 | |
Chris Lattner | 430d002 | 2005-08-03 22:21:05 +0000 | [diff] [blame] | 139 | void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses, |
| 140 | Loop *L, bool isOnlyStride); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 141 | void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts); |
| 142 | }; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 143 | RegisterOpt<LoopStrengthReduce> X("loop-reduce", |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 144 | "Strength Reduce GEP Uses of Ind. Vars"); |
| 145 | } |
| 146 | |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 147 | FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) { |
| 148 | return new LoopStrengthReduce(MaxTargetAMSize); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 149 | } |
| 150 | |
Chris Lattner | 6f286b7 | 2005-08-04 01:19:13 +0000 | [diff] [blame] | 151 | /// getCastedVersionOf - Return the specified value casted to uintptr_t. |
| 152 | /// |
| 153 | Value *LoopStrengthReduce::getCastedVersionOf(Value *V) { |
| 154 | if (V->getType() == UIntPtrTy) return V; |
| 155 | if (Constant *CB = dyn_cast<Constant>(V)) |
| 156 | return ConstantExpr::getCast(CB, UIntPtrTy); |
| 157 | |
| 158 | Value *&New = CastedPointers[V]; |
| 159 | if (New) return New; |
| 160 | |
| 161 | BasicBlock::iterator InsertPt; |
| 162 | if (Argument *Arg = dyn_cast<Argument>(V)) { |
| 163 | // Insert into the entry of the function, after any allocas. |
| 164 | InsertPt = Arg->getParent()->begin()->begin(); |
| 165 | while (isa<AllocaInst>(InsertPt)) ++InsertPt; |
| 166 | } else { |
| 167 | if (InvokeInst *II = dyn_cast<InvokeInst>(V)) { |
| 168 | InsertPt = II->getNormalDest()->begin(); |
| 169 | } else { |
| 170 | InsertPt = cast<Instruction>(V); |
| 171 | ++InsertPt; |
| 172 | } |
| 173 | |
| 174 | // Do not insert casts into the middle of PHI node blocks. |
| 175 | while (isa<PHINode>(InsertPt)) ++InsertPt; |
| 176 | } |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 177 | |
| 178 | New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt); |
| 179 | DeadInsts.insert(cast<Instruction>(New)); |
| 180 | return New; |
Chris Lattner | 6f286b7 | 2005-08-04 01:19:13 +0000 | [diff] [blame] | 181 | } |
| 182 | |
| 183 | |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 184 | /// DeleteTriviallyDeadInstructions - If any of the instructions is the |
| 185 | /// specified set are trivially dead, delete them and see if this makes any of |
| 186 | /// their operands subsequently dead. |
| 187 | void LoopStrengthReduce:: |
| 188 | DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) { |
| 189 | while (!Insts.empty()) { |
| 190 | Instruction *I = *Insts.begin(); |
| 191 | Insts.erase(Insts.begin()); |
| 192 | if (isInstructionTriviallyDead(I)) { |
Jeff Cohen | 8ea6f9e | 2005-03-01 03:46:11 +0000 | [diff] [blame] | 193 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) |
| 194 | if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i))) |
| 195 | Insts.insert(U); |
Chris Lattner | 84e9baa | 2005-08-03 21:36:09 +0000 | [diff] [blame] | 196 | SE->deleteInstructionFromRecords(I); |
| 197 | I->eraseFromParent(); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 198 | Changed = true; |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
Jeff Cohen | 39751c3 | 2005-02-27 19:37:07 +0000 | [diff] [blame] | 203 | |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 204 | /// GetExpressionSCEV - Compute and return the SCEV for the specified |
| 205 | /// instruction. |
| 206 | SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) { |
| 207 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp); |
| 208 | if (!GEP) |
| 209 | return SE->getSCEV(Exp); |
| 210 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 211 | // Analyze all of the subscripts of this getelementptr instruction, looking |
| 212 | // for uses that are determined by the trip count of L. First, skip all |
| 213 | // operands the are not dependent on the IV. |
| 214 | |
| 215 | // Build up the base expression. Insert an LLVM cast of the pointer to |
| 216 | // uintptr_t first. |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 217 | SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0))); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 218 | |
| 219 | gep_type_iterator GTI = gep_type_begin(GEP); |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 220 | |
| 221 | for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) { |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 222 | // If this is a use of a recurrence that we can analyze, and it comes before |
| 223 | // Op does in the GEP operand list, we will handle this when we process this |
| 224 | // operand. |
| 225 | if (const StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 226 | const StructLayout *SL = TD->getStructLayout(STy); |
| 227 | unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue(); |
| 228 | uint64_t Offset = SL->MemberOffsets[Idx]; |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 229 | GEPVal = SCEVAddExpr::get(GEPVal, |
| 230 | SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy)); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 231 | } else { |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 232 | Value *OpVal = getCastedVersionOf(GEP->getOperand(i)); |
| 233 | SCEVHandle Idx = SE->getSCEV(OpVal); |
| 234 | |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 235 | uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType()); |
| 236 | if (TypeSize != 1) |
| 237 | Idx = SCEVMulExpr::get(Idx, |
| 238 | SCEVConstant::get(ConstantUInt::get(UIntPtrTy, |
| 239 | TypeSize))); |
| 240 | GEPVal = SCEVAddExpr::get(GEPVal, Idx); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 241 | } |
| 242 | } |
| 243 | |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 244 | return GEPVal; |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 245 | } |
| 246 | |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 247 | /// getSCEVStartAndStride - Compute the start and stride of this expression, |
| 248 | /// returning false if the expression is not a start/stride pair, or true if it |
| 249 | /// is. The stride must be a loop invariant expression, but the start may be |
| 250 | /// a mix of loop invariant and loop variant expressions. |
| 251 | static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L, |
| 252 | SCEVHandle &Start, Value *&Stride) { |
| 253 | SCEVHandle TheAddRec = Start; // Initialize to zero. |
| 254 | |
| 255 | // If the outer level is an AddExpr, the operands are all start values except |
| 256 | // for a nested AddRecExpr. |
| 257 | if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) { |
| 258 | for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i) |
| 259 | if (SCEVAddRecExpr *AddRec = |
| 260 | dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) { |
| 261 | if (AddRec->getLoop() == L) |
| 262 | TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec); |
| 263 | else |
| 264 | return false; // Nested IV of some sort? |
| 265 | } else { |
| 266 | Start = SCEVAddExpr::get(Start, AE->getOperand(i)); |
| 267 | } |
| 268 | |
| 269 | } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) { |
| 270 | TheAddRec = SH; |
| 271 | } else { |
| 272 | return false; // not analyzable. |
| 273 | } |
| 274 | |
| 275 | SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec); |
| 276 | if (!AddRec || AddRec->getLoop() != L) return false; |
| 277 | |
| 278 | // FIXME: Generalize to non-affine IV's. |
| 279 | if (!AddRec->isAffine()) return false; |
| 280 | |
| 281 | Start = SCEVAddExpr::get(Start, AddRec->getOperand(0)); |
| 282 | |
| 283 | // FIXME: generalize to IV's with more complex strides (must emit stride |
| 284 | // expression outside of loop!) |
| 285 | if (!isa<SCEVConstant>(AddRec->getOperand(1))) |
| 286 | return false; |
| 287 | |
| 288 | SCEVConstant *StrideC = cast<SCEVConstant>(AddRec->getOperand(1)); |
| 289 | Stride = StrideC->getValue(); |
| 290 | |
| 291 | assert(Stride->getType()->isUnsigned() && |
| 292 | "Constants should be canonicalized to unsigned!"); |
| 293 | return true; |
| 294 | } |
| 295 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 296 | /// AddUsersIfInteresting - Inspect the specified instruction. If it is a |
| 297 | /// reducible SCEV, recursively add its users to the IVUsesByStride set and |
| 298 | /// return true. Otherwise, return false. |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 299 | bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L, |
| 300 | std::set<Instruction*> &Processed) { |
Nate Begeman | 17a0e2af | 2005-07-30 00:21:31 +0000 | [diff] [blame] | 301 | if (I->getType() == Type::VoidTy) return false; |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 302 | if (!Processed.insert(I).second) |
| 303 | return true; // Instruction already handled. |
| 304 | |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 305 | // Get the symbolic expression for this instruction. |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 306 | SCEVHandle ISE = GetExpressionSCEV(I, L); |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 307 | if (isa<SCEVCouldNotCompute>(ISE)) return false; |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 308 | |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 309 | // Get the start and stride for this expression. |
| 310 | SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType()); |
| 311 | Value *Stride = 0; |
| 312 | if (!getSCEVStartAndStride(ISE, L, Start, Stride)) |
| 313 | return false; // Non-reducible symbolic expression, bail out. |
| 314 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 315 | for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){ |
| 316 | Instruction *User = cast<Instruction>(*UI); |
| 317 | |
| 318 | // Do not infinitely recurse on PHI nodes. |
| 319 | if (isa<PHINode>(User) && User->getParent() == L->getHeader()) |
| 320 | continue; |
| 321 | |
| 322 | // If this is an instruction defined in a nested loop, or outside this loop, |
Chris Lattner | a0102fb | 2005-08-04 00:14:11 +0000 | [diff] [blame] | 323 | // don't recurse into it. |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 324 | bool AddUserToIVUsers = false; |
Chris Lattner | a0102fb | 2005-08-04 00:14:11 +0000 | [diff] [blame] | 325 | if (LI->getLoopFor(User->getParent()) != L) { |
| 326 | DEBUG(std::cerr << "FOUND USER in nested loop: " << *User |
| 327 | << " OF SCEV: " << *ISE << "\n"); |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 328 | AddUserToIVUsers = true; |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 329 | } else if (!AddUsersIfInteresting(User, L, Processed)) { |
Chris Lattner | 6510749 | 2005-08-04 00:40:47 +0000 | [diff] [blame] | 330 | DEBUG(std::cerr << "FOUND USER: " << *User |
| 331 | << " OF SCEV: " << *ISE << "\n"); |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 332 | AddUserToIVUsers = true; |
| 333 | } |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 334 | |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 335 | if (AddUserToIVUsers) { |
Chris Lattner | 6510749 | 2005-08-04 00:40:47 +0000 | [diff] [blame] | 336 | // Okay, we found a user that we cannot reduce. Analyze the instruction |
| 337 | // and decide what to do with it. |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 338 | IVUsesByStride[Stride].addUser(Start, User, I); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 339 | } |
| 340 | } |
| 341 | return true; |
| 342 | } |
| 343 | |
| 344 | namespace { |
| 345 | /// BasedUser - For a particular base value, keep information about how we've |
| 346 | /// partitioned the expression so far. |
| 347 | struct BasedUser { |
| 348 | /// Inst - The instruction using the induction variable. |
| 349 | Instruction *Inst; |
| 350 | |
Chris Lattner | 430d002 | 2005-08-03 22:21:05 +0000 | [diff] [blame] | 351 | /// OperandValToReplace - The operand value of Inst to replace with the |
| 352 | /// EmittedBase. |
| 353 | Value *OperandValToReplace; |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 354 | |
| 355 | /// Imm - The immediate value that should be added to the base immediately |
| 356 | /// before Inst, because it will be folded into the imm field of the |
| 357 | /// instruction. |
| 358 | SCEVHandle Imm; |
| 359 | |
| 360 | /// EmittedBase - The actual value* to use for the base value of this |
| 361 | /// operation. This is null if we should just use zero so far. |
| 362 | Value *EmittedBase; |
| 363 | |
Chris Lattner | 9bfa6f8 | 2005-08-08 05:28:22 +0000 | [diff] [blame] | 364 | // isUseOfPostIncrementedValue - True if this should use the |
| 365 | // post-incremented version of this IV, not the preincremented version. |
| 366 | // This can only be set in special cases, such as the terminating setcc |
| 367 | // instruction for a loop. |
| 368 | bool isUseOfPostIncrementedValue; |
| 369 | |
| 370 | BasedUser(Instruction *I, Value *Op, const SCEVHandle &IMM, bool iUOPIV) |
| 371 | : Inst(I), OperandValToReplace(Op), Imm(IMM), EmittedBase(0), |
| 372 | isUseOfPostIncrementedValue(iUOPIV) {} |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 373 | |
Chris Lattner | a6d7c35 | 2005-08-04 20:03:32 +0000 | [diff] [blame] | 374 | // Once we rewrite the code to insert the new IVs we want, update the |
| 375 | // operands of Inst to use the new expression 'NewBase', with 'Imm' added |
| 376 | // to it. |
| 377 | void RewriteInstructionToUseNewBase(Value *NewBase, SCEVExpander &Rewriter); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 378 | |
| 379 | // No need to compare these. |
| 380 | bool operator<(const BasedUser &BU) const { return 0; } |
| 381 | |
| 382 | void dump() const; |
| 383 | }; |
| 384 | } |
| 385 | |
| 386 | void BasedUser::dump() const { |
| 387 | std::cerr << " Imm=" << *Imm; |
| 388 | if (EmittedBase) |
| 389 | std::cerr << " EB=" << *EmittedBase; |
| 390 | |
| 391 | std::cerr << " Inst: " << *Inst; |
| 392 | } |
| 393 | |
Chris Lattner | a6d7c35 | 2005-08-04 20:03:32 +0000 | [diff] [blame] | 394 | // Once we rewrite the code to insert the new IVs we want, update the |
| 395 | // operands of Inst to use the new expression 'NewBase', with 'Imm' added |
| 396 | // to it. |
| 397 | void BasedUser::RewriteInstructionToUseNewBase(Value *NewBase, |
| 398 | SCEVExpander &Rewriter) { |
| 399 | if (!isa<PHINode>(Inst)) { |
| 400 | SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewBase), Imm); |
| 401 | Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst, |
| 402 | OperandValToReplace->getType()); |
| 403 | |
| 404 | // Replace the use of the operand Value with the new Phi we just created. |
| 405 | Inst->replaceUsesOfWith(OperandValToReplace, NewVal); |
| 406 | DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst); |
| 407 | return; |
| 408 | } |
| 409 | |
| 410 | // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm |
| 411 | // expression into each operand block that uses it. |
| 412 | PHINode *PN = cast<PHINode>(Inst); |
| 413 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 414 | if (PN->getIncomingValue(i) == OperandValToReplace) { |
| 415 | // FIXME: this should split any critical edges. |
| 416 | |
| 417 | // Insert the code into the end of the predecessor block. |
| 418 | BasicBlock::iterator InsertPt = PN->getIncomingBlock(i)->getTerminator(); |
| 419 | |
| 420 | SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewBase), Imm); |
| 421 | Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, InsertPt, |
| 422 | OperandValToReplace->getType()); |
| 423 | |
| 424 | // Replace the use of the operand Value with the new Phi we just created. |
| 425 | PN->setIncomingValue(i, NewVal); |
| 426 | Rewriter.clear(); |
| 427 | } |
| 428 | } |
| 429 | DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst); |
| 430 | } |
| 431 | |
| 432 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 433 | /// isTargetConstant - Return true if the following can be referenced by the |
| 434 | /// immediate field of a target instruction. |
| 435 | static bool isTargetConstant(const SCEVHandle &V) { |
Jeff Cohen | 546fd59 | 2005-07-30 18:33:25 +0000 | [diff] [blame] | 436 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 437 | // FIXME: Look at the target to decide if &GV is a legal constant immediate. |
Chris Lattner | 14203e8 | 2005-08-08 06:25:50 +0000 | [diff] [blame^] | 438 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) { |
| 439 | // PPC allows a sign-extended 16-bit immediate field. |
| 440 | if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) && |
| 441 | (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1) |
| 442 | return true; |
| 443 | return false; |
| 444 | } |
Jeff Cohen | 546fd59 | 2005-07-30 18:33:25 +0000 | [diff] [blame] | 445 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 446 | return false; // ENABLE this for x86 |
Jeff Cohen | 546fd59 | 2005-07-30 18:33:25 +0000 | [diff] [blame] | 447 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 448 | if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) |
| 449 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue())) |
| 450 | if (CE->getOpcode() == Instruction::Cast) |
| 451 | if (isa<GlobalValue>(CE->getOperand(0))) |
| 452 | // FIXME: should check to see that the dest is uintptr_t! |
| 453 | return true; |
| 454 | return false; |
| 455 | } |
| 456 | |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 457 | /// MoveImmediateValues - Look at Val, and pull out any additions of constants |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 458 | /// that can fit into the immediate field of instructions in the target. |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 459 | /// Accumulate these immediate values into the Imm value. |
| 460 | static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm, |
| 461 | bool isAddress, Loop *L) { |
Chris Lattner | fc62470 | 2005-08-03 23:44:42 +0000 | [diff] [blame] | 462 | if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) { |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 463 | std::vector<SCEVHandle> NewOps; |
| 464 | NewOps.reserve(SAE->getNumOperands()); |
| 465 | |
| 466 | for (unsigned i = 0; i != SAE->getNumOperands(); ++i) |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 467 | if (isAddress && isTargetConstant(SAE->getOperand(i))) { |
| 468 | Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i)); |
| 469 | } else if (!SAE->getOperand(i)->isLoopInvariant(L)) { |
| 470 | // If this is a loop-variant expression, it must stay in the immediate |
| 471 | // field of the expression. |
| 472 | Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i)); |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 473 | } else { |
| 474 | NewOps.push_back(SAE->getOperand(i)); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 475 | } |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 476 | |
| 477 | if (NewOps.empty()) |
| 478 | Val = SCEVUnknown::getIntegerSCEV(0, Val->getType()); |
| 479 | else |
| 480 | Val = SCEVAddExpr::get(NewOps); |
| 481 | return; |
Chris Lattner | fc62470 | 2005-08-03 23:44:42 +0000 | [diff] [blame] | 482 | } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) { |
| 483 | // Try to pull immediates out of the start value of nested addrec's. |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 484 | SCEVHandle Start = SARE->getStart(); |
| 485 | MoveImmediateValues(Start, Imm, isAddress, L); |
| 486 | |
| 487 | if (Start != SARE->getStart()) { |
| 488 | std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end()); |
| 489 | Ops[0] = Start; |
| 490 | Val = SCEVAddRecExpr::get(Ops, SARE->getLoop()); |
| 491 | } |
| 492 | return; |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 493 | } |
| 494 | |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 495 | // Loop-variant expressions must stay in the immediate field of the |
| 496 | // expression. |
| 497 | if ((isAddress && isTargetConstant(Val)) || |
| 498 | !Val->isLoopInvariant(L)) { |
| 499 | Imm = SCEVAddExpr::get(Imm, Val); |
| 500 | Val = SCEVUnknown::getIntegerSCEV(0, Val->getType()); |
| 501 | return; |
Chris Lattner | 0f7c0fa | 2005-08-04 19:26:19 +0000 | [diff] [blame] | 502 | } |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 503 | |
| 504 | // Otherwise, no immediates to move. |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 505 | } |
| 506 | |
| 507 | /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single |
| 508 | /// stride of IV. All of the users may have different starting values, and this |
| 509 | /// may not be the only stride (we know it is if isOnlyStride is true). |
| 510 | void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride, |
Chris Lattner | 430d002 | 2005-08-03 22:21:05 +0000 | [diff] [blame] | 511 | IVUsersOfOneStride &Uses, |
| 512 | Loop *L, |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 513 | bool isOnlyStride) { |
| 514 | // Transform our list of users and offsets to a bit more complex table. In |
| 515 | // this new vector, the first entry for each element is the base of the |
| 516 | // strided access, and the second is the BasedUser object for the use. We |
| 517 | // progressively move information from the first to the second entry, until we |
| 518 | // eventually emit the object. |
| 519 | std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess; |
| 520 | UsersToProcess.reserve(Uses.Users.size()); |
Jeff Cohen | 546fd59 | 2005-07-30 18:33:25 +0000 | [diff] [blame] | 521 | |
| 522 | SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0, |
Chris Lattner | 430d002 | 2005-08-03 22:21:05 +0000 | [diff] [blame] | 523 | Uses.Users[0].Offset->getType()); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 524 | |
| 525 | for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) |
Chris Lattner | 430d002 | 2005-08-03 22:21:05 +0000 | [diff] [blame] | 526 | UsersToProcess.push_back(std::make_pair(Uses.Users[i].Offset, |
| 527 | BasedUser(Uses.Users[i].User, |
| 528 | Uses.Users[i].OperandValToReplace, |
Chris Lattner | 9bfa6f8 | 2005-08-08 05:28:22 +0000 | [diff] [blame] | 529 | ZeroBase, |
| 530 | Uses.Users[i].isUseOfPostIncrementedValue))); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 531 | |
| 532 | // First pass, figure out what we can represent in the immediate fields of |
| 533 | // instructions. If we can represent anything there, move it to the imm |
| 534 | // fields of the BasedUsers. |
| 535 | for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) { |
Chris Lattner | acc42c4 | 2005-08-04 19:08:16 +0000 | [diff] [blame] | 536 | // Addressing modes can be folded into loads and stores. Be careful that |
| 537 | // the store is through the expression, not of the expression though. |
| 538 | bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst); |
| 539 | if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].second.Inst)) |
| 540 | if (SI->getOperand(1) == UsersToProcess[i].second.OperandValToReplace) |
| 541 | isAddress = true; |
| 542 | |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 543 | MoveImmediateValues(UsersToProcess[i].first, UsersToProcess[i].second.Imm, |
| 544 | isAddress, L); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 545 | |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 546 | assert(UsersToProcess[i].first->isLoopInvariant(L) && |
| 547 | "Base value is not loop invariant!"); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 548 | } |
| 549 | |
| 550 | SCEVExpander Rewriter(*SE, *LI); |
Chris Lattner | c70bbc0 | 2005-08-08 05:47:49 +0000 | [diff] [blame] | 551 | SCEVExpander PreheaderRewriter(*SE, *LI); |
| 552 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 553 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 554 | Instruction *PreInsertPt = Preheader->getTerminator(); |
| 555 | Instruction *PhiInsertBefore = L->getHeader()->begin(); |
| 556 | |
Jeff Cohen | 546fd59 | 2005-07-30 18:33:25 +0000 | [diff] [blame] | 557 | assert(isa<PHINode>(PhiInsertBefore) && |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 558 | "How could this loop have IV's without any phis?"); |
| 559 | PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore); |
| 560 | assert(SomeLoopPHI->getNumIncomingValues() == 2 && |
| 561 | "This loop isn't canonicalized right"); |
| 562 | BasicBlock *LatchBlock = |
| 563 | SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader); |
Jeff Cohen | 546fd59 | 2005-07-30 18:33:25 +0000 | [diff] [blame] | 564 | |
Chris Lattner | bb78c97 | 2005-08-03 23:30:08 +0000 | [diff] [blame] | 565 | DEBUG(std::cerr << "INSERTING IVs of STRIDE " << *Stride << ":\n"); |
| 566 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 567 | // FIXME: This loop needs increasing levels of intelligence. |
Chris Lattner | db23c74 | 2005-08-03 22:51:21 +0000 | [diff] [blame] | 568 | // STAGE 0: just emit everything as its own base. |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 569 | // STAGE 1: factor out common vars from bases, and try and push resulting |
Chris Lattner | db23c74 | 2005-08-03 22:51:21 +0000 | [diff] [blame] | 570 | // constants into Imm field. <-- We are here |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 571 | // STAGE 2: factor out large constants to try and make more constants |
| 572 | // acceptable for target loads and stores. |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 573 | |
Chris Lattner | db23c74 | 2005-08-03 22:51:21 +0000 | [diff] [blame] | 574 | // Sort by the base value, so that all IVs with identical bases are next to |
| 575 | // each other. |
| 576 | std::sort(UsersToProcess.begin(), UsersToProcess.end()); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 577 | while (!UsersToProcess.empty()) { |
Chris Lattner | db23c74 | 2005-08-03 22:51:21 +0000 | [diff] [blame] | 578 | SCEVHandle Base = UsersToProcess.front().first; |
Chris Lattner | bb78c97 | 2005-08-03 23:30:08 +0000 | [diff] [blame] | 579 | |
| 580 | DEBUG(std::cerr << " INSERTING PHI with BASE = " << *Base << ":\n"); |
| 581 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 582 | // Create a new Phi for this base, and stick it in the loop header. |
Chris Lattner | db23c74 | 2005-08-03 22:51:21 +0000 | [diff] [blame] | 583 | const Type *ReplacedTy = Base->getType(); |
| 584 | PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore); |
Chris Lattner | 45f8b6e | 2005-08-04 22:34:05 +0000 | [diff] [blame] | 585 | ++NumInserted; |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 586 | |
Jeff Cohen | 546fd59 | 2005-07-30 18:33:25 +0000 | [diff] [blame] | 587 | // Emit the initial base value into the loop preheader, and add it to the |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 588 | // Phi node. |
Chris Lattner | c70bbc0 | 2005-08-08 05:47:49 +0000 | [diff] [blame] | 589 | Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt, |
| 590 | ReplacedTy); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 591 | NewPHI->addIncoming(BaseV, Preheader); |
| 592 | |
| 593 | // Emit the increment of the base value before the terminator of the loop |
| 594 | // latch block, and add it to the Phi node. |
| 595 | SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI), |
| 596 | SCEVUnknown::get(Stride)); |
| 597 | |
| 598 | Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(), |
| 599 | ReplacedTy); |
| 600 | IncV->setName(NewPHI->getName()+".inc"); |
| 601 | NewPHI->addIncoming(IncV, LatchBlock); |
| 602 | |
| 603 | // Emit the code to add the immediate offset to the Phi value, just before |
Chris Lattner | db23c74 | 2005-08-03 22:51:21 +0000 | [diff] [blame] | 604 | // the instructions that we identified as using this stride and base. |
| 605 | while (!UsersToProcess.empty() && UsersToProcess.front().first == Base) { |
| 606 | BasedUser &User = UsersToProcess.front().second; |
Jeff Cohen | 546fd59 | 2005-07-30 18:33:25 +0000 | [diff] [blame] | 607 | |
Chris Lattner | db23c74 | 2005-08-03 22:51:21 +0000 | [diff] [blame] | 608 | // Clear the SCEVExpander's expression map so that we are guaranteed |
| 609 | // to have the code emitted where we expect it. |
| 610 | Rewriter.clear(); |
Chris Lattner | a6d7c35 | 2005-08-04 20:03:32 +0000 | [diff] [blame] | 611 | |
| 612 | // Now that we know what we need to do, insert code before User for the |
| 613 | // immediate and any loop-variant expressions. |
Chris Lattner | 9bfa6f8 | 2005-08-08 05:28:22 +0000 | [diff] [blame] | 614 | Value *NewBase = NewPHI; |
| 615 | |
| 616 | // If this instruction wants to use the post-incremented value, move it |
| 617 | // after the post-inc and use its value instead of the PHI. |
| 618 | if (User.isUseOfPostIncrementedValue) { |
| 619 | NewBase = IncV; |
| 620 | User.Inst->moveBefore(LatchBlock->getTerminator()); |
| 621 | } |
| 622 | User.RewriteInstructionToUseNewBase(NewBase, Rewriter); |
Jeff Cohen | 546fd59 | 2005-07-30 18:33:25 +0000 | [diff] [blame] | 623 | |
Chris Lattner | db23c74 | 2005-08-03 22:51:21 +0000 | [diff] [blame] | 624 | // Mark old value we replaced as possibly dead, so that it is elminated |
| 625 | // if we just replaced the last use of that value. |
Chris Lattner | a6d7c35 | 2005-08-04 20:03:32 +0000 | [diff] [blame] | 626 | DeadInsts.insert(cast<Instruction>(User.OperandValToReplace)); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 627 | |
Chris Lattner | db23c74 | 2005-08-03 22:51:21 +0000 | [diff] [blame] | 628 | UsersToProcess.erase(UsersToProcess.begin()); |
| 629 | ++NumReduced; |
| 630 | } |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 631 | // TODO: Next, find out which base index is the most common, pull it out. |
| 632 | } |
| 633 | |
| 634 | // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but |
| 635 | // different starting values, into different PHIs. |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 636 | } |
| 637 | |
Chris Lattner | 9bfa6f8 | 2005-08-08 05:28:22 +0000 | [diff] [blame] | 638 | // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar |
| 639 | // uses in the loop, look to see if we can eliminate some, in favor of using |
| 640 | // common indvars for the different uses. |
| 641 | void LoopStrengthReduce::OptimizeIndvars(Loop *L) { |
| 642 | // TODO: implement optzns here. |
| 643 | |
| 644 | |
| 645 | |
| 646 | |
| 647 | // Finally, get the terminating condition for the loop if possible. If we |
| 648 | // can, we want to change it to use a post-incremented version of its |
| 649 | // induction variable, to allow coallescing the live ranges for the IV into |
| 650 | // one register value. |
| 651 | PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin()); |
| 652 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 653 | BasicBlock *LatchBlock = |
| 654 | SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader); |
| 655 | BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator()); |
| 656 | if (!TermBr || TermBr->isUnconditional() || |
| 657 | !isa<SetCondInst>(TermBr->getCondition())) |
| 658 | return; |
| 659 | SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition()); |
| 660 | |
| 661 | // Search IVUsesByStride to find Cond's IVUse if there is one. |
| 662 | IVStrideUse *CondUse = 0; |
| 663 | Value *CondStride = 0; |
| 664 | |
| 665 | for (std::map<Value*, IVUsersOfOneStride>::iterator I =IVUsesByStride.begin(), |
| 666 | E = IVUsesByStride.end(); I != E && !CondUse; ++I) |
| 667 | for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(), |
| 668 | E = I->second.Users.end(); UI != E; ++UI) |
| 669 | if (UI->User == Cond) { |
| 670 | CondUse = &*UI; |
| 671 | CondStride = I->first; |
| 672 | // NOTE: we could handle setcc instructions with multiple uses here, but |
| 673 | // InstCombine does it as well for simple uses, it's not clear that it |
| 674 | // occurs enough in real life to handle. |
| 675 | break; |
| 676 | } |
| 677 | if (!CondUse) return; // setcc doesn't use the IV. |
| 678 | |
| 679 | // setcc stride is complex, don't mess with users. |
| 680 | if (!isa<ConstantInt>(CondStride)) return; |
| 681 | |
| 682 | // It's possible for the setcc instruction to be anywhere in the loop, and |
| 683 | // possible for it to have multiple users. If it is not immediately before |
| 684 | // the latch block branch, move it. |
| 685 | if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) { |
| 686 | if (Cond->hasOneUse()) { // Condition has a single use, just move it. |
| 687 | Cond->moveBefore(TermBr); |
| 688 | } else { |
| 689 | // Otherwise, clone the terminating condition and insert into the loopend. |
| 690 | Cond = cast<SetCondInst>(Cond->clone()); |
| 691 | Cond->setName(L->getHeader()->getName() + ".termcond"); |
| 692 | LatchBlock->getInstList().insert(TermBr, Cond); |
| 693 | |
| 694 | // Clone the IVUse, as the old use still exists! |
| 695 | IVUsesByStride[CondStride].addUser(CondUse->Offset, Cond, |
| 696 | CondUse->OperandValToReplace); |
| 697 | CondUse = &IVUsesByStride[CondStride].Users.back(); |
| 698 | } |
| 699 | } |
| 700 | |
| 701 | // If we get to here, we know that we can transform the setcc instruction to |
| 702 | // use the post-incremented version of the IV, allowing us to coallesce the |
| 703 | // live ranges for the IV correctly. |
| 704 | CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, |
| 705 | SCEVUnknown::get(CondStride)); |
| 706 | CondUse->isUseOfPostIncrementedValue = true; |
| 707 | } |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 708 | |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 709 | void LoopStrengthReduce::runOnLoop(Loop *L) { |
| 710 | // First step, transform all loops nesting inside of this loop. |
| 711 | for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 712 | runOnLoop(*I); |
| 713 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 714 | // Next, find all uses of induction variables in this loop, and catagorize |
| 715 | // them by stride. Start by finding all of the PHI nodes in the header for |
| 716 | // this loop. If they are induction variables, inspect their uses. |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 717 | std::set<Instruction*> Processed; // Don't reprocess instructions. |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 718 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) |
Chris Lattner | eaf2472 | 2005-08-04 17:40:30 +0000 | [diff] [blame] | 719 | AddUsersIfInteresting(I, L, Processed); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 720 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 721 | // If we have nothing to do, return. |
Chris Lattner | 9bfa6f8 | 2005-08-08 05:28:22 +0000 | [diff] [blame] | 722 | if (IVUsesByStride.empty()) return; |
| 723 | |
| 724 | // Optimize induction variables. Some indvar uses can be transformed to use |
| 725 | // strides that will be needed for other purposes. A common example of this |
| 726 | // is the exit test for the loop, which can often be rewritten to use the |
| 727 | // computation of some other indvar to decide when to terminate the loop. |
| 728 | OptimizeIndvars(L); |
| 729 | |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 730 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 731 | // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of |
| 732 | // doing computation in byte values, promote to 32-bit values if safe. |
| 733 | |
| 734 | // FIXME: Attempt to reuse values across multiple IV's. In particular, we |
| 735 | // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be |
| 736 | // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need |
| 737 | // to be careful that IV's are all the same type. Only works for intptr_t |
| 738 | // indvars. |
| 739 | |
| 740 | // If we only have one stride, we can more aggressively eliminate some things. |
| 741 | bool HasOneStride = IVUsesByStride.size() == 1; |
| 742 | |
Chris Lattner | 430d002 | 2005-08-03 22:21:05 +0000 | [diff] [blame] | 743 | for (std::map<Value*, IVUsersOfOneStride>::iterator SI |
| 744 | = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI) |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 745 | StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 746 | |
| 747 | // Clean up after ourselves |
| 748 | if (!DeadInsts.empty()) { |
| 749 | DeleteTriviallyDeadInstructions(DeadInsts); |
| 750 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 751 | BasicBlock::iterator I = L->getHeader()->begin(); |
| 752 | PHINode *PN; |
Chris Lattner | dcce49e | 2005-08-02 02:44:31 +0000 | [diff] [blame] | 753 | while ((PN = dyn_cast<PHINode>(I))) { |
Chris Lattner | 564900e | 2005-08-02 00:41:11 +0000 | [diff] [blame] | 754 | ++I; // Preincrement iterator to avoid invalidating it when deleting PN. |
| 755 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 756 | // At this point, we know that we have killed one or more GEP instructions. |
| 757 | // It is worth checking to see if the cann indvar is also dead, so that we |
| 758 | // can remove it as well. The requirements for the cann indvar to be |
| 759 | // considered dead are: |
| 760 | // 1. the cann indvar has one use |
| 761 | // 2. the use is an add instruction |
| 762 | // 3. the add has one use |
| 763 | // 4. the add is used by the cann indvar |
| 764 | // If all four cases above are true, then we can remove both the add and |
| 765 | // the cann indvar. |
| 766 | // FIXME: this needs to eliminate an induction variable even if it's being |
| 767 | // compared against some value to decide loop termination. |
| 768 | if (PN->hasOneUse()) { |
| 769 | BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin())); |
Chris Lattner | 75a44e1 | 2005-08-02 02:52:02 +0000 | [diff] [blame] | 770 | if (BO && BO->hasOneUse()) { |
| 771 | if (PN == *(BO->use_begin())) { |
| 772 | DeadInsts.insert(BO); |
| 773 | // Break the cycle, then delete the PHI. |
| 774 | PN->replaceAllUsesWith(UndefValue::get(PN->getType())); |
Chris Lattner | 84e9baa | 2005-08-03 21:36:09 +0000 | [diff] [blame] | 775 | SE->deleteInstructionFromRecords(PN); |
Chris Lattner | 75a44e1 | 2005-08-02 02:52:02 +0000 | [diff] [blame] | 776 | PN->eraseFromParent(); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 777 | } |
Chris Lattner | 75a44e1 | 2005-08-02 02:52:02 +0000 | [diff] [blame] | 778 | } |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 779 | } |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 780 | } |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 781 | DeleteTriviallyDeadInstructions(DeadInsts); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 782 | } |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 783 | |
Chris Lattner | 11e7a5e | 2005-08-05 01:30:11 +0000 | [diff] [blame] | 784 | CastedPointers.clear(); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 785 | IVUsesByStride.clear(); |
| 786 | return; |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 787 | } |