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 | |
| 18 | #include "llvm/Transforms/Scalar.h" |
| 19 | #include "llvm/Constants.h" |
| 20 | #include "llvm/Instructions.h" |
| 21 | #include "llvm/Type.h" |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 22 | #include "llvm/DerivedTypes.h" |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/Dominators.h" |
| 24 | #include "llvm/Analysis/LoopInfo.h" |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 26 | #include "llvm/Support/CFG.h" |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 27 | #include "llvm/Support/GetElementPtrTypeIterator.h" |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 28 | #include "llvm/Transforms/Utils/Local.h" |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 29 | #include "llvm/Target/TargetData.h" |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 30 | #include "llvm/ADT/Statistic.h" |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 31 | #include "llvm/Support/Debug.h" |
Jeff Cohen | c500991 | 2005-07-30 18:22:27 +0000 | [diff] [blame^] | 32 | #include <algorithm> |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 33 | #include <set> |
| 34 | using namespace llvm; |
| 35 | |
| 36 | namespace { |
| 37 | Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced"); |
| 38 | |
Chris Lattner | d3874fa | 2005-03-06 21:58:22 +0000 | [diff] [blame] | 39 | class GEPCache { |
Jeff Cohen | be37fa0 | 2005-03-05 22:40:34 +0000 | [diff] [blame] | 40 | public: |
| 41 | GEPCache() : CachedPHINode(0), Map() {} |
| 42 | |
Chris Lattner | d3874fa | 2005-03-06 21:58:22 +0000 | [diff] [blame] | 43 | GEPCache *get(Value *v) { |
Jeff Cohen | be37fa0 | 2005-03-05 22:40:34 +0000 | [diff] [blame] | 44 | std::map<Value *, GEPCache>::iterator I = Map.find(v); |
| 45 | if (I == Map.end()) |
| 46 | I = Map.insert(std::pair<Value *, GEPCache>(v, GEPCache())).first; |
Chris Lattner | d3874fa | 2005-03-06 21:58:22 +0000 | [diff] [blame] | 47 | return &I->second; |
Jeff Cohen | be37fa0 | 2005-03-05 22:40:34 +0000 | [diff] [blame] | 48 | } |
| 49 | |
| 50 | PHINode *CachedPHINode; |
| 51 | std::map<Value *, GEPCache> Map; |
| 52 | }; |
| 53 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 54 | struct IVUse { |
| 55 | /// Users - Keep track of all of the users of this stride as well as the |
| 56 | /// initial value. |
| 57 | std::vector<std::pair<SCEVHandle, Instruction*> > Users; |
| 58 | std::vector<Instruction *> UserOperands; |
| 59 | |
| 60 | void addUser(SCEVHandle &SH, Instruction *U, Instruction *V) { |
| 61 | Users.push_back(std::make_pair(SH, U)); |
| 62 | UserOperands.push_back(V); |
| 63 | } |
| 64 | }; |
| 65 | |
| 66 | |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 67 | class LoopStrengthReduce : public FunctionPass { |
| 68 | LoopInfo *LI; |
| 69 | DominatorSet *DS; |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 70 | ScalarEvolution *SE; |
| 71 | const TargetData *TD; |
| 72 | const Type *UIntPtrTy; |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 73 | bool Changed; |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 74 | unsigned MaxTargetAMSize; |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 75 | |
| 76 | /// IVUsesByStride - Keep track of all uses of induction variables that we |
| 77 | /// are interested in. The key of the map is the stride of the access. |
| 78 | std::map<Value*, IVUse> IVUsesByStride; |
| 79 | |
| 80 | /// CastedBasePointers - As we need to lower getelementptr instructions, we |
| 81 | /// cast the pointer input to uintptr_t. This keeps track of the casted |
| 82 | /// values for the pointers we have processed so far. |
| 83 | std::map<Value*, Value*> CastedBasePointers; |
| 84 | |
| 85 | /// DeadInsts - Keep track of instructions we may have made dead, so that |
| 86 | /// we can remove them after we are done working. |
| 87 | std::set<Instruction*> DeadInsts; |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 88 | public: |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 89 | LoopStrengthReduce(unsigned MTAMS = 1) |
| 90 | : MaxTargetAMSize(MTAMS) { |
| 91 | } |
| 92 | |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 93 | virtual bool runOnFunction(Function &) { |
| 94 | LI = &getAnalysis<LoopInfo>(); |
| 95 | DS = &getAnalysis<DominatorSet>(); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 96 | SE = &getAnalysis<ScalarEvolution>(); |
| 97 | TD = &getAnalysis<TargetData>(); |
| 98 | UIntPtrTy = TD->getIntPtrType(); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 99 | Changed = false; |
| 100 | |
| 101 | for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) |
| 102 | runOnLoop(*I); |
| 103 | return Changed; |
| 104 | } |
| 105 | |
| 106 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 107 | AU.setPreservesCFG(); |
Jeff Cohen | 39751c3 | 2005-02-27 19:37:07 +0000 | [diff] [blame] | 108 | AU.addRequiredID(LoopSimplifyID); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 109 | AU.addRequired<LoopInfo>(); |
| 110 | AU.addRequired<DominatorSet>(); |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 111 | AU.addRequired<TargetData>(); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 112 | AU.addRequired<ScalarEvolution>(); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 113 | } |
| 114 | private: |
| 115 | void runOnLoop(Loop *L); |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 116 | bool AddUsersIfInteresting(Instruction *I, Loop *L); |
| 117 | void AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP, Instruction *I, |
| 118 | Loop *L); |
| 119 | |
| 120 | void StrengthReduceStridedIVUsers(Value *Stride, IVUse &Uses, Loop *L, |
| 121 | bool isOnlyStride); |
| 122 | |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 123 | void strengthReduceGEP(GetElementPtrInst *GEPI, Loop *L, |
Jeff Cohen | be37fa0 | 2005-03-05 22:40:34 +0000 | [diff] [blame] | 124 | GEPCache* GEPCache, |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 125 | Instruction *InsertBefore, |
| 126 | std::set<Instruction*> &DeadInsts); |
| 127 | void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts); |
| 128 | }; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 129 | RegisterOpt<LoopStrengthReduce> X("loop-reduce", |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 130 | "Strength Reduce GEP Uses of Ind. Vars"); |
| 131 | } |
| 132 | |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 133 | FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) { |
| 134 | return new LoopStrengthReduce(MaxTargetAMSize); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 135 | } |
| 136 | |
| 137 | /// DeleteTriviallyDeadInstructions - If any of the instructions is the |
| 138 | /// specified set are trivially dead, delete them and see if this makes any of |
| 139 | /// their operands subsequently dead. |
| 140 | void LoopStrengthReduce:: |
| 141 | DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) { |
| 142 | while (!Insts.empty()) { |
| 143 | Instruction *I = *Insts.begin(); |
| 144 | Insts.erase(Insts.begin()); |
| 145 | if (isInstructionTriviallyDead(I)) { |
Jeff Cohen | 8ea6f9e | 2005-03-01 03:46:11 +0000 | [diff] [blame] | 146 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) |
| 147 | if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i))) |
| 148 | Insts.insert(U); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 149 | I->getParent()->getInstList().erase(I); |
| 150 | Changed = true; |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
Jeff Cohen | 39751c3 | 2005-02-27 19:37:07 +0000 | [diff] [blame] | 155 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 156 | /// CanReduceSCEV - Return true if we can strength reduce this scalar evolution |
| 157 | /// in the specified loop. |
| 158 | static bool CanReduceSCEV(const SCEVHandle &SH, Loop *L) { |
| 159 | SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH); |
| 160 | if (!AddRec || AddRec->getLoop() != L) return false; |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 161 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 162 | // FIXME: Generalize to non-affine IV's. |
| 163 | if (!AddRec->isAffine()) return false; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 164 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 165 | // FIXME: generalize to IV's with more complex strides (must emit stride |
| 166 | // expression outside of loop!) |
| 167 | if (isa<SCEVConstant>(AddRec->getOperand(1))) |
| 168 | return true; |
Jeff Cohen | a2c59b7 | 2005-03-04 04:04:26 +0000 | [diff] [blame] | 169 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 170 | // We handle steps by unsigned values, because we know we won't have to insert |
| 171 | // a cast for them. |
| 172 | if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(AddRec->getOperand(1))) |
| 173 | if (SU->getValue()->getType()->isUnsigned()) |
| 174 | return true; |
| 175 | |
| 176 | // Otherwise, no, we can't handle it yet. |
| 177 | return false; |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 178 | } |
| 179 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 180 | |
| 181 | /// GetAdjustedIndex - Adjust the specified GEP sequential type index to match |
| 182 | /// the size of the pointer type, and scale it by the type size. |
| 183 | static SCEVHandle GetAdjustedIndex(const SCEVHandle &Idx, uint64_t TySize, |
| 184 | const Type *UIntPtrTy) { |
| 185 | SCEVHandle Result = Idx; |
| 186 | if (Result->getType()->getUnsignedVersion() != UIntPtrTy) { |
| 187 | if (UIntPtrTy->getPrimitiveSize() < Result->getType()->getPrimitiveSize()) |
| 188 | Result = SCEVTruncateExpr::get(Result, UIntPtrTy); |
| 189 | else |
| 190 | Result = SCEVZeroExtendExpr::get(Result, UIntPtrTy); |
| 191 | } |
| 192 | |
| 193 | // This index is scaled by the type size being indexed. |
| 194 | if (TySize != 1) |
| 195 | Result = SCEVMulExpr::get(Result, |
| 196 | SCEVConstant::get(ConstantUInt::get(UIntPtrTy, |
| 197 | TySize))); |
| 198 | return Result; |
| 199 | } |
| 200 | |
| 201 | /// AnalyzeGetElementPtrUsers - Analyze all of the users of the specified |
| 202 | /// getelementptr instruction, adding them to the IVUsesByStride table. Note |
| 203 | /// that we only want to analyze a getelementptr instruction once, and it can |
| 204 | /// have multiple operands that are uses of the indvar (e.g. A[i][i]). Because |
| 205 | /// of this, we only process a GEP instruction if its first recurrent operand is |
| 206 | /// "op", otherwise we will either have already processed it or we will sometime |
| 207 | /// later. |
| 208 | void LoopStrengthReduce::AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP, |
| 209 | Instruction *Op, Loop *L) { |
| 210 | // Analyze all of the subscripts of this getelementptr instruction, looking |
| 211 | // for uses that are determined by the trip count of L. First, skip all |
| 212 | // operands the are not dependent on the IV. |
| 213 | |
| 214 | // Build up the base expression. Insert an LLVM cast of the pointer to |
| 215 | // uintptr_t first. |
| 216 | Value *BasePtr; |
| 217 | if (Constant *CB = dyn_cast<Constant>(GEP->getOperand(0))) |
| 218 | BasePtr = ConstantExpr::getCast(CB, UIntPtrTy); |
| 219 | else { |
| 220 | Value *&BP = CastedBasePointers[GEP->getOperand(0)]; |
| 221 | if (BP == 0) { |
| 222 | BasicBlock::iterator InsertPt; |
| 223 | if (isa<Argument>(GEP->getOperand(0))) { |
| 224 | InsertPt = GEP->getParent()->getParent()->begin()->begin(); |
| 225 | } else { |
| 226 | InsertPt = cast<Instruction>(GEP->getOperand(0)); |
| 227 | if (InvokeInst *II = dyn_cast<InvokeInst>(GEP->getOperand(0))) |
| 228 | InsertPt = II->getNormalDest()->begin(); |
| 229 | else |
| 230 | ++InsertPt; |
| 231 | } |
| 232 | BP = new CastInst(GEP->getOperand(0), UIntPtrTy, |
| 233 | GEP->getOperand(0)->getName(), InsertPt); |
| 234 | } |
| 235 | BasePtr = BP; |
| 236 | } |
| 237 | |
| 238 | SCEVHandle Base = SCEVUnknown::get(BasePtr); |
| 239 | |
| 240 | gep_type_iterator GTI = gep_type_begin(GEP); |
| 241 | unsigned i = 1; |
| 242 | for (; GEP->getOperand(i) != Op; ++i, ++GTI) { |
| 243 | // If this is a use of a recurrence that we can analyze, and it comes before |
| 244 | // Op does in the GEP operand list, we will handle this when we process this |
| 245 | // operand. |
| 246 | if (const StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 247 | const StructLayout *SL = TD->getStructLayout(STy); |
| 248 | unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue(); |
| 249 | uint64_t Offset = SL->MemberOffsets[Idx]; |
| 250 | Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset, |
| 251 | UIntPtrTy)); |
| 252 | } else { |
| 253 | SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i)); |
| 254 | if (CanReduceSCEV(Idx, L)) |
| 255 | return; |
| 256 | Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx, |
| 257 | TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy)); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | // Get the index, convert it to intptr_t. |
| 262 | SCEVHandle GEPIndexExpr = |
| 263 | GetAdjustedIndex(SE->getSCEV(Op), TD->getTypeSize(GTI.getIndexedType()), |
| 264 | UIntPtrTy); |
| 265 | |
| 266 | // Process all remaining subscripts in the GEP instruction. |
| 267 | for (++i, ++GTI; i != GEP->getNumOperands(); ++i, ++GTI) |
| 268 | if (const StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 269 | const StructLayout *SL = TD->getStructLayout(STy); |
| 270 | unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue(); |
| 271 | uint64_t Offset = SL->MemberOffsets[Idx]; |
| 272 | Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset, |
| 273 | UIntPtrTy)); |
| 274 | } else { |
| 275 | SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i)); |
| 276 | if (CanReduceSCEV(Idx, L)) { // Another IV subscript |
| 277 | GEPIndexExpr = SCEVAddExpr::get(GEPIndexExpr, |
| 278 | GetAdjustedIndex(Idx, TD->getTypeSize(GTI.getIndexedType()), |
| 279 | UIntPtrTy)); |
| 280 | assert(CanReduceSCEV(GEPIndexExpr, L) && |
| 281 | "Cannot reduce the sum of two reducible SCEV's??"); |
| 282 | } else { |
| 283 | Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx, |
| 284 | TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy)); |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | assert(CanReduceSCEV(GEPIndexExpr, L) && "Non reducible idx??"); |
| 289 | |
| 290 | Base = SCEVAddExpr::get(Base, cast<SCEVAddRecExpr>(GEPIndexExpr)->getStart()); |
| 291 | SCEVHandle Stride = cast<SCEVAddRecExpr>(GEPIndexExpr)->getOperand(1); |
| 292 | |
| 293 | DEBUG(std::cerr << "GEP BASE : " << *Base << "\n"); |
| 294 | DEBUG(std::cerr << "GEP STRIDE: " << *Stride << "\n"); |
| 295 | |
| 296 | Value *Step = 0; // Step of ISE. |
| 297 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) |
| 298 | /// Always get the step value as an unsigned value. |
| 299 | Step = ConstantExpr::getCast(SC->getValue(), |
| 300 | SC->getValue()->getType()->getUnsignedVersion()); |
| 301 | else |
| 302 | Step = cast<SCEVUnknown>(Stride)->getValue(); |
| 303 | assert(Step->getType()->isUnsigned() && "Bad step value!"); |
| 304 | |
| 305 | |
| 306 | // Now that we know the base and stride contributed by the GEP instruction, |
| 307 | // process all users. |
| 308 | for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end(); |
| 309 | UI != E; ++UI) { |
| 310 | Instruction *User = cast<Instruction>(*UI); |
| 311 | |
| 312 | // Do not infinitely recurse on PHI nodes. |
| 313 | if (isa<PHINode>(User) && User->getParent() == L->getHeader()) |
| 314 | continue; |
| 315 | |
| 316 | // If this is an instruction defined in a nested loop, or outside this loop, |
| 317 | // don't mess with it. |
| 318 | if (LI->getLoopFor(User->getParent()) != L) |
| 319 | continue; |
| 320 | |
| 321 | DEBUG(std::cerr << "FOUND USER: " << *User |
| 322 | << " OF STRIDE: " << *Step << " BASE = " << *Base << "\n"); |
| 323 | |
| 324 | |
| 325 | // Okay, we found a user that we cannot reduce. Analyze the instruction |
| 326 | // and decide what to do with it. |
| 327 | IVUsesByStride[Step].addUser(Base, User, GEP); |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | /// AddUsersIfInteresting - Inspect the specified instruction. If it is a |
| 332 | /// reducible SCEV, recursively add its users to the IVUsesByStride set and |
| 333 | /// return true. Otherwise, return false. |
| 334 | bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L) { |
Nate Begeman | 17a0e2af | 2005-07-30 00:21:31 +0000 | [diff] [blame] | 335 | if (I->getType() == Type::VoidTy) return false; |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 336 | SCEVHandle ISE = SE->getSCEV(I); |
| 337 | if (!CanReduceSCEV(ISE, L)) return false; |
| 338 | |
| 339 | SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(ISE); |
| 340 | SCEVHandle Start = AR->getStart(); |
| 341 | |
| 342 | // Get the step value, canonicalizing to an unsigned integer type so that |
| 343 | // lookups in the map will match. |
| 344 | Value *Step = 0; // Step of ISE. |
| 345 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(AR->getOperand(1))) |
| 346 | /// Always get the step value as an unsigned value. |
| 347 | Step = ConstantExpr::getCast(SC->getValue(), |
| 348 | SC->getValue()->getType()->getUnsignedVersion()); |
| 349 | else |
| 350 | Step = cast<SCEVUnknown>(AR->getOperand(1))->getValue(); |
| 351 | assert(Step->getType()->isUnsigned() && "Bad step value!"); |
| 352 | |
| 353 | std::set<GetElementPtrInst*> AnalyzedGEPs; |
| 354 | |
| 355 | for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){ |
| 356 | Instruction *User = cast<Instruction>(*UI); |
| 357 | |
| 358 | // Do not infinitely recurse on PHI nodes. |
| 359 | if (isa<PHINode>(User) && User->getParent() == L->getHeader()) |
| 360 | continue; |
| 361 | |
| 362 | // If this is an instruction defined in a nested loop, or outside this loop, |
| 363 | // don't mess with it. |
| 364 | if (LI->getLoopFor(User->getParent()) != L) |
| 365 | continue; |
| 366 | |
| 367 | // Next, see if this user is analyzable itself! |
| 368 | if (!AddUsersIfInteresting(User, L)) { |
| 369 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) { |
| 370 | // If this is a getelementptr instruction, figure out what linear |
| 371 | // expression of induction variable is actually being used. |
| 372 | // |
| 373 | if (AnalyzedGEPs.insert(GEP).second) // Not already analyzed? |
| 374 | AnalyzeGetElementPtrUsers(GEP, I, L); |
| 375 | } else { |
| 376 | DEBUG(std::cerr << "FOUND USER: " << *User |
| 377 | << " OF SCEV: " << *ISE << "\n"); |
| 378 | |
| 379 | // Okay, we found a user that we cannot reduce. Analyze the instruction |
| 380 | // and decide what to do with it. |
| 381 | IVUsesByStride[Step].addUser(Start, User, I); |
| 382 | } |
| 383 | } |
| 384 | } |
| 385 | return true; |
| 386 | } |
| 387 | |
| 388 | namespace { |
| 389 | /// BasedUser - For a particular base value, keep information about how we've |
| 390 | /// partitioned the expression so far. |
| 391 | struct BasedUser { |
| 392 | /// Inst - The instruction using the induction variable. |
| 393 | Instruction *Inst; |
| 394 | |
| 395 | /// Op - The value to replace with the EmittedBase. |
| 396 | Value *Op; |
| 397 | |
| 398 | /// Imm - The immediate value that should be added to the base immediately |
| 399 | /// before Inst, because it will be folded into the imm field of the |
| 400 | /// instruction. |
| 401 | SCEVHandle Imm; |
| 402 | |
| 403 | /// EmittedBase - The actual value* to use for the base value of this |
| 404 | /// operation. This is null if we should just use zero so far. |
| 405 | Value *EmittedBase; |
| 406 | |
| 407 | BasedUser(Instruction *I, Value *V, const SCEVHandle &IMM) |
| 408 | : Inst(I), Op(V), Imm(IMM), EmittedBase(0) {} |
| 409 | |
| 410 | |
| 411 | // No need to compare these. |
| 412 | bool operator<(const BasedUser &BU) const { return 0; } |
| 413 | |
| 414 | void dump() const; |
| 415 | }; |
| 416 | } |
| 417 | |
| 418 | void BasedUser::dump() const { |
| 419 | std::cerr << " Imm=" << *Imm; |
| 420 | if (EmittedBase) |
| 421 | std::cerr << " EB=" << *EmittedBase; |
| 422 | |
| 423 | std::cerr << " Inst: " << *Inst; |
| 424 | } |
| 425 | |
| 426 | /// isTargetConstant - Return true if the following can be referenced by the |
| 427 | /// immediate field of a target instruction. |
| 428 | static bool isTargetConstant(const SCEVHandle &V) { |
| 429 | |
| 430 | // FIXME: Look at the target to decide if &GV is a legal constant immediate. |
| 431 | if (isa<SCEVConstant>(V)) return true; |
| 432 | |
| 433 | return false; // ENABLE this for x86 |
| 434 | |
| 435 | if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) |
| 436 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue())) |
| 437 | if (CE->getOpcode() == Instruction::Cast) |
| 438 | if (isa<GlobalValue>(CE->getOperand(0))) |
| 439 | // FIXME: should check to see that the dest is uintptr_t! |
| 440 | return true; |
| 441 | return false; |
| 442 | } |
| 443 | |
| 444 | /// GetImmediateValues - Look at Val, and pull out any additions of constants |
| 445 | /// that can fit into the immediate field of instructions in the target. |
| 446 | static SCEVHandle GetImmediateValues(SCEVHandle Val, bool isAddress) { |
| 447 | if (!isAddress) |
| 448 | return SCEVUnknown::getIntegerSCEV(0, Val->getType()); |
| 449 | if (isTargetConstant(Val)) |
| 450 | return Val; |
| 451 | |
| 452 | SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val); |
| 453 | if (SAE) { |
| 454 | unsigned i = 0; |
| 455 | for (; i != SAE->getNumOperands(); ++i) |
| 456 | if (isTargetConstant(SAE->getOperand(i))) { |
| 457 | SCEVHandle ImmVal = SAE->getOperand(i); |
| 458 | |
| 459 | // If there are any other immediates that we can handle here, pull them |
| 460 | // out too. |
| 461 | for (++i; i != SAE->getNumOperands(); ++i) |
| 462 | if (isTargetConstant(SAE->getOperand(i))) |
| 463 | ImmVal = SCEVAddExpr::get(ImmVal, SAE->getOperand(i)); |
| 464 | return ImmVal; |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | return SCEVUnknown::getIntegerSCEV(0, Val->getType()); |
| 469 | } |
| 470 | |
| 471 | /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single |
| 472 | /// stride of IV. All of the users may have different starting values, and this |
| 473 | /// may not be the only stride (we know it is if isOnlyStride is true). |
| 474 | void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride, |
| 475 | IVUse &Uses, Loop *L, |
| 476 | bool isOnlyStride) { |
| 477 | // Transform our list of users and offsets to a bit more complex table. In |
| 478 | // this new vector, the first entry for each element is the base of the |
| 479 | // strided access, and the second is the BasedUser object for the use. We |
| 480 | // progressively move information from the first to the second entry, until we |
| 481 | // eventually emit the object. |
| 482 | std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess; |
| 483 | UsersToProcess.reserve(Uses.Users.size()); |
| 484 | |
| 485 | SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0, |
| 486 | Uses.Users[0].first->getType()); |
| 487 | |
| 488 | for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) |
| 489 | UsersToProcess.push_back(std::make_pair(Uses.Users[i].first, |
| 490 | BasedUser(Uses.Users[i].second, |
| 491 | Uses.UserOperands[i], |
| 492 | ZeroBase))); |
| 493 | |
| 494 | // First pass, figure out what we can represent in the immediate fields of |
| 495 | // instructions. If we can represent anything there, move it to the imm |
| 496 | // fields of the BasedUsers. |
| 497 | for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) { |
| 498 | bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst) || |
| 499 | isa<StoreInst>(UsersToProcess[i].second.Inst); |
| 500 | UsersToProcess[i].second.Imm = GetImmediateValues(UsersToProcess[i].first, |
| 501 | isAddress); |
| 502 | UsersToProcess[i].first = SCEV::getMinusSCEV(UsersToProcess[i].first, |
| 503 | UsersToProcess[i].second.Imm); |
| 504 | |
| 505 | DEBUG(std::cerr << "BASE: " << *UsersToProcess[i].first); |
| 506 | DEBUG(UsersToProcess[i].second.dump()); |
| 507 | } |
| 508 | |
| 509 | SCEVExpander Rewriter(*SE, *LI); |
| 510 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 511 | Instruction *PreInsertPt = Preheader->getTerminator(); |
| 512 | Instruction *PhiInsertBefore = L->getHeader()->begin(); |
| 513 | |
| 514 | assert(isa<PHINode>(PhiInsertBefore) && |
| 515 | "How could this loop have IV's without any phis?"); |
| 516 | PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore); |
| 517 | assert(SomeLoopPHI->getNumIncomingValues() == 2 && |
| 518 | "This loop isn't canonicalized right"); |
| 519 | BasicBlock *LatchBlock = |
| 520 | SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader); |
| 521 | |
| 522 | // FIXME: This loop needs increasing levels of intelligence. |
| 523 | // STAGE 0: just emit everything as its own base. <-- We are here |
| 524 | // STAGE 1: factor out common vars from bases, and try and push resulting |
| 525 | // constants into Imm field. |
| 526 | // STAGE 2: factor out large constants to try and make more constants |
| 527 | // acceptable for target loads and stores. |
| 528 | std::sort(UsersToProcess.begin(), UsersToProcess.end()); |
| 529 | |
| 530 | while (!UsersToProcess.empty()) { |
| 531 | // Create a new Phi for this base, and stick it in the loop header. |
| 532 | Value *Replaced = UsersToProcess.front().second.Op; |
| 533 | const Type *ReplacedTy = Replaced->getType(); |
| 534 | PHINode *NewPHI = new PHINode(ReplacedTy, Replaced->getName()+".str", |
| 535 | PhiInsertBefore); |
| 536 | |
| 537 | // Emit the initial base value into the loop preheader, and add it to the |
| 538 | // Phi node. |
| 539 | Value *BaseV = Rewriter.expandCodeFor(UsersToProcess.front().first, |
| 540 | PreInsertPt, ReplacedTy); |
| 541 | NewPHI->addIncoming(BaseV, Preheader); |
| 542 | |
| 543 | // Emit the increment of the base value before the terminator of the loop |
| 544 | // latch block, and add it to the Phi node. |
| 545 | SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI), |
| 546 | SCEVUnknown::get(Stride)); |
| 547 | |
| 548 | Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(), |
| 549 | ReplacedTy); |
| 550 | IncV->setName(NewPHI->getName()+".inc"); |
| 551 | NewPHI->addIncoming(IncV, LatchBlock); |
| 552 | |
| 553 | // Emit the code to add the immediate offset to the Phi value, just before |
| 554 | // the instruction that we identified as using this stride and base. |
| 555 | // First, empty the SCEVExpander's expression map so that we are guaranteed |
| 556 | // to have the code emitted where we expect it. |
| 557 | Rewriter.clear(); |
| 558 | SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewPHI), |
| 559 | UsersToProcess.front().second.Imm); |
| 560 | Value *newVal = Rewriter.expandCodeFor(NewValSCEV, |
| 561 | UsersToProcess.front().second.Inst, |
| 562 | ReplacedTy); |
| 563 | |
| 564 | // Replace the use of the operand Value with the new Phi we just created. |
| 565 | DEBUG(std::cerr << "REPLACING: " << *Replaced << "IN: " << |
| 566 | *UsersToProcess.front().second.Inst << "WITH: "<< *newVal << '\n'); |
| 567 | UsersToProcess.front().second.Inst->replaceUsesOfWith(Replaced, newVal); |
| 568 | |
| 569 | // Mark old value we replaced as possibly dead, so that it is elminated |
| 570 | // if we just replaced the last use of that value. |
| 571 | DeadInsts.insert(cast<Instruction>(Replaced)); |
| 572 | |
| 573 | UsersToProcess.erase(UsersToProcess.begin()); |
| 574 | ++NumReduced; |
| 575 | |
| 576 | // TODO: Next, find out which base index is the most common, pull it out. |
| 577 | } |
| 578 | |
| 579 | // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but |
| 580 | // different starting values, into different PHIs. |
| 581 | |
| 582 | // BEFORE writing this, it's probably useful to handle GEP's. |
| 583 | |
| 584 | // NOTE: pull all constants together, for REG+IMM addressing, include &GV in |
| 585 | // 'IMM' if the target supports it. |
| 586 | } |
| 587 | |
| 588 | |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 589 | void LoopStrengthReduce::runOnLoop(Loop *L) { |
| 590 | // First step, transform all loops nesting inside of this loop. |
| 591 | for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 592 | runOnLoop(*I); |
| 593 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 594 | // Next, find all uses of induction variables in this loop, and catagorize |
| 595 | // them by stride. Start by finding all of the PHI nodes in the header for |
| 596 | // this loop. If they are induction variables, inspect their uses. |
| 597 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) |
| 598 | AddUsersIfInteresting(I, L); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 599 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 600 | // If we have nothing to do, return. |
| 601 | //if (IVUsesByStride.empty()) return; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 602 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 603 | // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of |
| 604 | // doing computation in byte values, promote to 32-bit values if safe. |
| 605 | |
| 606 | // FIXME: Attempt to reuse values across multiple IV's. In particular, we |
| 607 | // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be |
| 608 | // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need |
| 609 | // to be careful that IV's are all the same type. Only works for intptr_t |
| 610 | // indvars. |
| 611 | |
| 612 | // If we only have one stride, we can more aggressively eliminate some things. |
| 613 | bool HasOneStride = IVUsesByStride.size() == 1; |
| 614 | |
| 615 | for (std::map<Value*, IVUse>::iterator SI = IVUsesByStride.begin(), |
| 616 | E = IVUsesByStride.end(); SI != E; ++SI) |
| 617 | StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 618 | |
| 619 | // Clean up after ourselves |
| 620 | if (!DeadInsts.empty()) { |
| 621 | DeleteTriviallyDeadInstructions(DeadInsts); |
| 622 | |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 623 | BasicBlock::iterator I = L->getHeader()->begin(); |
| 624 | PHINode *PN; |
| 625 | for (; (PN = dyn_cast<PHINode>(I)); ++I) { |
| 626 | // At this point, we know that we have killed one or more GEP instructions. |
| 627 | // It is worth checking to see if the cann indvar is also dead, so that we |
| 628 | // can remove it as well. The requirements for the cann indvar to be |
| 629 | // considered dead are: |
| 630 | // 1. the cann indvar has one use |
| 631 | // 2. the use is an add instruction |
| 632 | // 3. the add has one use |
| 633 | // 4. the add is used by the cann indvar |
| 634 | // If all four cases above are true, then we can remove both the add and |
| 635 | // the cann indvar. |
| 636 | // FIXME: this needs to eliminate an induction variable even if it's being |
| 637 | // compared against some value to decide loop termination. |
| 638 | if (PN->hasOneUse()) { |
| 639 | BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin())); |
| 640 | if (BO && BO->getOpcode() == Instruction::Add) |
| 641 | if (BO->hasOneUse()) { |
| 642 | if (PN == dyn_cast<PHINode>(*(BO->use_begin()))) { |
| 643 | DeadInsts.insert(BO); |
| 644 | // Break the cycle, then delete the PHI. |
| 645 | PN->replaceAllUsesWith(UndefValue::get(PN->getType())); |
| 646 | PN->eraseFromParent(); |
| 647 | } |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 648 | } |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 649 | } |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 650 | } |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 651 | DeleteTriviallyDeadInstructions(DeadInsts); |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 652 | } |
Nate Begeman | e68bcd1 | 2005-07-30 00:15:07 +0000 | [diff] [blame] | 653 | |
| 654 | IVUsesByStride.clear(); |
| 655 | return; |
Nate Begeman | b18121e | 2004-10-18 21:08:22 +0000 | [diff] [blame] | 656 | } |