1 //===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "loop-reduce"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Type.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/ScalarEvolutionExpander.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/GetElementPtrTypeIterator.h"
29 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Debug.h"
39 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
40 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
41 Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
43 /// IVStrideUse - Keep track of one use of a strided induction variable, where
44 /// the stride is stored externally. The Offset member keeps track of the
45 /// offset from the IV, User is the actual user of the operand, and 'Operand'
46 /// is the operand # of the User that is the use.
50 Value *OperandValToReplace;
52 // isUseOfPostIncrementedValue - True if this should use the
53 // post-incremented version of this IV, not the preincremented version.
54 // This can only be set in special cases, such as the terminating setcc
55 // instruction for a loop or uses dominated by the loop.
56 bool isUseOfPostIncrementedValue;
58 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
59 : Offset(Offs), User(U), OperandValToReplace(O),
60 isUseOfPostIncrementedValue(false) {}
63 /// IVUsersOfOneStride - This structure keeps track of all instructions that
64 /// have an operand that is based on the trip count multiplied by some stride.
65 /// The stride for all of these users is common and kept external to this
67 struct IVUsersOfOneStride {
68 /// Users - Keep track of all of the users of this stride as well as the
69 /// initial value and the operand that uses the IV.
70 std::vector<IVStrideUse> Users;
72 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
73 Users.push_back(IVStrideUse(Offset, User, Operand));
78 class LoopStrengthReduce : public FunctionPass {
83 const Type *UIntPtrTy;
86 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
87 /// target can handle for free with its addressing modes.
88 unsigned MaxTargetAMSize;
90 /// IVUsesByStride - Keep track of all uses of induction variables that we
91 /// are interested in. The key of the map is the stride of the access.
92 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
94 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
95 /// of the casted version of each value. This is accessed by
96 /// getCastedVersionOf.
97 std::map<Value*, Value*> CastedPointers;
99 /// DeadInsts - Keep track of instructions we may have made dead, so that
100 /// we can remove them after we are done working.
101 std::set<Instruction*> DeadInsts;
103 LoopStrengthReduce(unsigned MTAMS = 1)
104 : MaxTargetAMSize(MTAMS) {
107 virtual bool runOnFunction(Function &) {
108 LI = &getAnalysis<LoopInfo>();
109 DS = &getAnalysis<DominatorSet>();
110 SE = &getAnalysis<ScalarEvolution>();
111 TD = &getAnalysis<TargetData>();
112 UIntPtrTy = TD->getIntPtrType();
115 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
121 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
122 // We split critical edges, so we change the CFG. However, we do update
123 // many analyses if they are around.
124 AU.addPreservedID(LoopSimplifyID);
125 AU.addPreserved<LoopInfo>();
126 AU.addPreserved<DominatorSet>();
127 AU.addPreserved<ImmediateDominators>();
128 AU.addPreserved<DominanceFrontier>();
129 AU.addPreserved<DominatorTree>();
131 AU.addRequiredID(LoopSimplifyID);
132 AU.addRequired<LoopInfo>();
133 AU.addRequired<DominatorSet>();
134 AU.addRequired<TargetData>();
135 AU.addRequired<ScalarEvolution>();
138 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
140 Value *getCastedVersionOf(Value *V);
142 void runOnLoop(Loop *L);
143 bool AddUsersIfInteresting(Instruction *I, Loop *L,
144 std::set<Instruction*> &Processed);
145 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
147 void OptimizeIndvars(Loop *L);
149 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
150 IVUsersOfOneStride &Uses,
151 Loop *L, bool isOnlyStride);
152 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
154 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
155 "Loop Strength Reduction");
158 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
159 return new LoopStrengthReduce(MaxTargetAMSize);
162 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
164 Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
165 if (V->getType() == UIntPtrTy) return V;
166 if (Constant *CB = dyn_cast<Constant>(V))
167 return ConstantExpr::getCast(CB, UIntPtrTy);
169 Value *&New = CastedPointers[V];
172 BasicBlock::iterator InsertPt;
173 if (Argument *Arg = dyn_cast<Argument>(V)) {
174 // Insert into the entry of the function, after any allocas.
175 InsertPt = Arg->getParent()->begin()->begin();
176 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
178 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
179 InsertPt = II->getNormalDest()->begin();
181 InsertPt = cast<Instruction>(V);
185 // Do not insert casts into the middle of PHI node blocks.
186 while (isa<PHINode>(InsertPt)) ++InsertPt;
189 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
190 DeadInsts.insert(cast<Instruction>(New));
195 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
196 /// specified set are trivially dead, delete them and see if this makes any of
197 /// their operands subsequently dead.
198 void LoopStrengthReduce::
199 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
200 while (!Insts.empty()) {
201 Instruction *I = *Insts.begin();
202 Insts.erase(Insts.begin());
203 if (isInstructionTriviallyDead(I)) {
204 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
205 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
207 SE->deleteInstructionFromRecords(I);
208 I->eraseFromParent();
215 /// GetExpressionSCEV - Compute and return the SCEV for the specified
217 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
218 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
219 // If this is a GEP that SE doesn't know about, compute it now and insert it.
220 // If this is not a GEP, or if we have already done this computation, just let
222 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
223 if (!GEP || SE->hasSCEV(GEP))
224 return SE->getSCEV(Exp);
226 // Analyze all of the subscripts of this getelementptr instruction, looking
227 // for uses that are determined by the trip count of L. First, skip all
228 // operands the are not dependent on the IV.
230 // Build up the base expression. Insert an LLVM cast of the pointer to
232 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
234 gep_type_iterator GTI = gep_type_begin(GEP);
236 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
237 // If this is a use of a recurrence that we can analyze, and it comes before
238 // Op does in the GEP operand list, we will handle this when we process this
240 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
241 const StructLayout *SL = TD->getStructLayout(STy);
242 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
243 uint64_t Offset = SL->MemberOffsets[Idx];
244 GEPVal = SCEVAddExpr::get(GEPVal,
245 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
247 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
248 SCEVHandle Idx = SE->getSCEV(OpVal);
250 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
252 Idx = SCEVMulExpr::get(Idx,
253 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
255 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
259 SE->setSCEV(GEP, GEPVal);
263 /// getSCEVStartAndStride - Compute the start and stride of this expression,
264 /// returning false if the expression is not a start/stride pair, or true if it
265 /// is. The stride must be a loop invariant expression, but the start may be
266 /// a mix of loop invariant and loop variant expressions.
267 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
268 SCEVHandle &Start, SCEVHandle &Stride) {
269 SCEVHandle TheAddRec = Start; // Initialize to zero.
271 // If the outer level is an AddExpr, the operands are all start values except
272 // for a nested AddRecExpr.
273 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
274 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
275 if (SCEVAddRecExpr *AddRec =
276 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
277 if (AddRec->getLoop() == L)
278 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
280 return false; // Nested IV of some sort?
282 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
285 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
288 return false; // not analyzable.
291 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
292 if (!AddRec || AddRec->getLoop() != L) return false;
294 // FIXME: Generalize to non-affine IV's.
295 if (!AddRec->isAffine()) return false;
297 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
299 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
300 DEBUG(std::cerr << "[" << L->getHeader()->getName()
301 << "] Variable stride: " << *AddRec << "\n");
303 Stride = AddRec->getOperand(1);
304 // Check that all constant strides are the unsigned type, we don't want to
305 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
307 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
308 "Constants should be canonicalized to unsigned!");
313 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
314 /// and now we need to decide whether the user should use the preinc or post-inc
315 /// value. If this user should use the post-inc version of the IV, return true.
317 /// Choosing wrong here can break dominance properties (if we choose to use the
318 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
319 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
320 /// should use the post-inc value).
321 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
322 Loop *L, DominatorSet *DS) {
323 // If the user is in the loop, use the preinc value.
324 if (L->contains(User->getParent())) return false;
326 // Ok, the user is outside of the loop. If it is not dominated by the latch
327 // block, we have to use the preincremented value.
328 return DS->dominates(L->getLoopLatch(), User->getParent());
333 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
334 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
335 /// return true. Otherwise, return false.
336 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
337 std::set<Instruction*> &Processed) {
338 if (I->getType() == Type::VoidTy) return false;
339 if (!Processed.insert(I).second)
340 return true; // Instruction already handled.
342 // Get the symbolic expression for this instruction.
343 SCEVHandle ISE = GetExpressionSCEV(I, L);
344 if (isa<SCEVCouldNotCompute>(ISE)) return false;
346 // Get the start and stride for this expression.
347 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
348 SCEVHandle Stride = Start;
349 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
350 return false; // Non-reducible symbolic expression, bail out.
352 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
353 Instruction *User = cast<Instruction>(*UI);
355 // Do not infinitely recurse on PHI nodes.
356 if (isa<PHINode>(User) && Processed.count(User))
359 // If this is an instruction defined in a nested loop, or outside this loop,
360 // don't recurse into it.
361 bool AddUserToIVUsers = false;
362 if (LI->getLoopFor(User->getParent()) != L) {
363 DEBUG(std::cerr << "FOUND USER in other loop: " << *User
364 << " OF SCEV: " << *ISE << "\n");
365 AddUserToIVUsers = true;
366 } else if (!AddUsersIfInteresting(User, L, Processed)) {
367 DEBUG(std::cerr << "FOUND USER: " << *User
368 << " OF SCEV: " << *ISE << "\n");
369 AddUserToIVUsers = true;
372 if (AddUserToIVUsers) {
373 // Okay, we found a user that we cannot reduce. Analyze the instruction
374 // and decide what to do with it. If we are a use inside of the loop, use
375 // the value before incrementation, otherwise use it after incrementation.
376 if (IVUseShouldUsePostIncValue(User, I, L, DS)) {
377 // The value used will be incremented by the stride more than we are
378 // expecting, so subtract this off.
379 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
380 IVUsesByStride[Stride].addUser(NewStart, User, I);
381 IVUsesByStride[Stride].Users.back().isUseOfPostIncrementedValue = true;
383 IVUsesByStride[Stride].addUser(Start, User, I);
391 /// BasedUser - For a particular base value, keep information about how we've
392 /// partitioned the expression so far.
394 /// Base - The Base value for the PHI node that needs to be inserted for
395 /// this use. As the use is processed, information gets moved from this
396 /// field to the Imm field (below). BasedUser values are sorted by this
400 /// Inst - The instruction using the induction variable.
403 /// OperandValToReplace - The operand value of Inst to replace with the
405 Value *OperandValToReplace;
407 /// Imm - The immediate value that should be added to the base immediately
408 /// before Inst, because it will be folded into the imm field of the
412 /// EmittedBase - The actual value* to use for the base value of this
413 /// operation. This is null if we should just use zero so far.
416 // isUseOfPostIncrementedValue - True if this should use the
417 // post-incremented version of this IV, not the preincremented version.
418 // This can only be set in special cases, such as the terminating setcc
419 // instruction for a loop and uses outside the loop that are dominated by
421 bool isUseOfPostIncrementedValue;
423 BasedUser(IVStrideUse &IVSU)
424 : Base(IVSU.Offset), Inst(IVSU.User),
425 OperandValToReplace(IVSU.OperandValToReplace),
426 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
427 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
429 // Once we rewrite the code to insert the new IVs we want, update the
430 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
432 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
433 SCEVExpander &Rewriter, Loop *L,
436 // Sort by the Base field.
437 bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
443 void BasedUser::dump() const {
444 std::cerr << " Base=" << *Base;
445 std::cerr << " Imm=" << *Imm;
447 std::cerr << " EB=" << *EmittedBase;
449 std::cerr << " Inst: " << *Inst;
452 // Once we rewrite the code to insert the new IVs we want, update the
453 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
455 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
456 SCEVExpander &Rewriter,
458 if (!isa<PHINode>(Inst)) {
459 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
460 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
461 OperandValToReplace->getType());
462 // Replace the use of the operand Value with the new Phi we just created.
463 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
464 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
468 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
469 // expression into each operand block that uses it. Note that PHI nodes can
470 // have multiple entries for the same predecessor. We use a map to make sure
471 // that a PHI node only has a single Value* for each predecessor (which also
472 // prevents us from inserting duplicate code in some blocks).
473 std::map<BasicBlock*, Value*> InsertedCode;
474 PHINode *PN = cast<PHINode>(Inst);
475 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
476 if (PN->getIncomingValue(i) == OperandValToReplace) {
477 // If this is a critical edge, split the edge so that we do not insert the
478 // code on all predecessor/successor paths. We do this unless this is the
479 // canonical backedge for this loop, as this can make some inserted code
480 // be in an illegal position.
481 BasicBlock *PHIPred = PN->getIncomingBlock(i);
482 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
483 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
486 // First step, split the critical edge.
487 SplitCriticalEdge(PHIPred, PN->getParent(), P);
489 // Next step: move the basic block. In particular, if the PHI node
490 // is outside of the loop, and PredTI is in the loop, we want to
491 // move the block to be immediately before the PHI block, not
492 // immediately after PredTI.
493 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
494 BasicBlock *NewBB = PN->getIncomingBlock(i);
495 NewBB->moveBefore(PN->getParent());
499 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
501 // Insert the code into the end of the predecessor block.
502 BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
504 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
505 Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
506 OperandValToReplace->getType());
509 // Replace the use of the operand Value with the new Phi we just created.
510 PN->setIncomingValue(i, Code);
514 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
518 /// isTargetConstant - Return true if the following can be referenced by the
519 /// immediate field of a target instruction.
520 static bool isTargetConstant(const SCEVHandle &V) {
522 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
523 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
524 // PPC allows a sign-extended 16-bit immediate field.
525 if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
526 (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
531 return false; // ENABLE this for x86
533 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
534 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
535 if (CE->getOpcode() == Instruction::Cast)
536 if (isa<GlobalValue>(CE->getOperand(0)))
537 // FIXME: should check to see that the dest is uintptr_t!
542 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
543 /// loop varying to the Imm operand.
544 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
546 if (Val->isLoopInvariant(L)) return; // Nothing to do.
548 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
549 std::vector<SCEVHandle> NewOps;
550 NewOps.reserve(SAE->getNumOperands());
552 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
553 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
554 // If this is a loop-variant expression, it must stay in the immediate
555 // field of the expression.
556 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
558 NewOps.push_back(SAE->getOperand(i));
562 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
564 Val = SCEVAddExpr::get(NewOps);
565 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
566 // Try to pull immediates out of the start value of nested addrec's.
567 SCEVHandle Start = SARE->getStart();
568 MoveLoopVariantsToImediateField(Start, Imm, L);
570 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
572 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
574 // Otherwise, all of Val is variant, move the whole thing over.
575 Imm = SCEVAddExpr::get(Imm, Val);
576 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
581 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
582 /// that can fit into the immediate field of instructions in the target.
583 /// Accumulate these immediate values into the Imm value.
584 static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
585 bool isAddress, Loop *L) {
586 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
587 std::vector<SCEVHandle> NewOps;
588 NewOps.reserve(SAE->getNumOperands());
590 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
591 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
592 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
593 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
594 // If this is a loop-variant expression, it must stay in the immediate
595 // field of the expression.
596 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
598 NewOps.push_back(SAE->getOperand(i));
602 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
604 Val = SCEVAddExpr::get(NewOps);
606 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
607 // Try to pull immediates out of the start value of nested addrec's.
608 SCEVHandle Start = SARE->getStart();
609 MoveImmediateValues(Start, Imm, isAddress, L);
611 if (Start != SARE->getStart()) {
612 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
614 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
619 // Loop-variant expressions must stay in the immediate field of the
621 if ((isAddress && isTargetConstant(Val)) ||
622 !Val->isLoopInvariant(L)) {
623 Imm = SCEVAddExpr::get(Imm, Val);
624 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
628 // Otherwise, no immediates to move.
632 /// IncrementAddExprUses - Decompose the specified expression into its added
633 /// subexpressions, and increment SubExpressionUseCounts for each of these
634 /// decomposed parts.
635 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
637 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
638 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
639 SeparateSubExprs(SubExprs, AE->getOperand(j));
640 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
641 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
642 if (SARE->getOperand(0) == Zero) {
643 SubExprs.push_back(Expr);
645 // Compute the addrec with zero as its base.
646 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
647 Ops[0] = Zero; // Start with zero base.
648 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
651 SeparateSubExprs(SubExprs, SARE->getOperand(0));
653 } else if (!isa<SCEVConstant>(Expr) ||
654 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
656 SubExprs.push_back(Expr);
661 /// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
662 /// removing any common subexpressions from it. Anything truly common is
663 /// removed, accumulated, and returned. This looks for things like (a+b+c) and
664 /// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
666 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
667 unsigned NumUses = Uses.size();
669 // Only one use? Use its base, regardless of what it is!
670 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
671 SCEVHandle Result = Zero;
673 std::swap(Result, Uses[0].Base);
677 // To find common subexpressions, count how many of Uses use each expression.
678 // If any subexpressions are used Uses.size() times, they are common.
679 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
681 std::vector<SCEVHandle> SubExprs;
682 for (unsigned i = 0; i != NumUses; ++i) {
683 // If the base is zero (which is common), return zero now, there are no
685 if (Uses[i].Base == Zero) return Zero;
687 // Split the expression into subexprs.
688 SeparateSubExprs(SubExprs, Uses[i].Base);
689 // Add one to SubExpressionUseCounts for each subexpr present.
690 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
691 SubExpressionUseCounts[SubExprs[j]]++;
696 // Now that we know how many times each is used, build Result.
697 for (std::map<SCEVHandle, unsigned>::iterator I =
698 SubExpressionUseCounts.begin(), E = SubExpressionUseCounts.end();
700 if (I->second == NumUses) { // Found CSE!
701 Result = SCEVAddExpr::get(Result, I->first);
704 // Remove non-cse's from SubExpressionUseCounts.
705 SubExpressionUseCounts.erase(I++);
708 // If we found no CSE's, return now.
709 if (Result == Zero) return Result;
711 // Otherwise, remove all of the CSE's we found from each of the base values.
712 for (unsigned i = 0; i != NumUses; ++i) {
713 // Split the expression into subexprs.
714 SeparateSubExprs(SubExprs, Uses[i].Base);
716 // Remove any common subexpressions.
717 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
718 if (SubExpressionUseCounts.count(SubExprs[j])) {
719 SubExprs.erase(SubExprs.begin()+j);
723 // Finally, the non-shared expressions together.
724 if (SubExprs.empty())
727 Uses[i].Base = SCEVAddExpr::get(SubExprs);
735 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
736 /// stride of IV. All of the users may have different starting values, and this
737 /// may not be the only stride (we know it is if isOnlyStride is true).
738 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
739 IVUsersOfOneStride &Uses,
742 // Transform our list of users and offsets to a bit more complex table. In
743 // this new vector, each 'BasedUser' contains 'Base' the base of the
744 // strided accessas well as the old information from Uses. We progressively
745 // move information from the Base field to the Imm field, until we eventually
746 // have the full access expression to rewrite the use.
747 std::vector<BasedUser> UsersToProcess;
748 UsersToProcess.reserve(Uses.Users.size());
749 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
750 UsersToProcess.push_back(Uses.Users[i]);
752 // Move any loop invariant operands from the offset field to the immediate
753 // field of the use, so that we don't try to use something before it is
755 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
756 UsersToProcess.back().Imm, L);
757 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
758 "Base value is not loop invariant!");
761 // We now have a whole bunch of uses of like-strided induction variables, but
762 // they might all have different bases. We want to emit one PHI node for this
763 // stride which we fold as many common expressions (between the IVs) into as
764 // possible. Start by identifying the common expressions in the base values
765 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
766 // "A+B"), emit it to the preheader, then remove the expression from the
767 // UsersToProcess base values.
768 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
770 // Next, figure out what we can represent in the immediate fields of
771 // instructions. If we can represent anything there, move it to the imm
772 // fields of the BasedUsers. We do this so that it increases the commonality
773 // of the remaining uses.
774 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
775 // If the user is not in the current loop, this means it is using the exit
776 // value of the IV. Do not put anything in the base, make sure it's all in
777 // the immediate field to allow as much factoring as possible.
778 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
779 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
780 UsersToProcess[i].Base);
781 UsersToProcess[i].Base =
782 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
785 // Addressing modes can be folded into loads and stores. Be careful that
786 // the store is through the expression, not of the expression though.
787 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
788 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
789 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
792 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
797 // Now that we know what we need to do, insert the PHI node itself.
799 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
800 << *CommonExprs << " :\n");
802 SCEVExpander Rewriter(*SE, *LI);
803 SCEVExpander PreheaderRewriter(*SE, *LI);
805 BasicBlock *Preheader = L->getLoopPreheader();
806 Instruction *PreInsertPt = Preheader->getTerminator();
807 Instruction *PhiInsertBefore = L->getHeader()->begin();
809 BasicBlock *LatchBlock = L->getLoopLatch();
811 // Create a new Phi for this base, and stick it in the loop header.
812 const Type *ReplacedTy = CommonExprs->getType();
813 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
816 // Insert the stride into the preheader.
817 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
819 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
822 // Emit the initial base value into the loop preheader, and add it to the
824 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
826 NewPHI->addIncoming(PHIBaseV, Preheader);
828 // Emit the increment of the base value before the terminator of the loop
829 // latch block, and add it to the Phi node.
830 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
831 SCEVUnknown::get(StrideV));
833 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
835 IncV->setName(NewPHI->getName()+".inc");
836 NewPHI->addIncoming(IncV, LatchBlock);
838 // Sort by the base value, so that all IVs with identical bases are next to
840 std::sort(UsersToProcess.begin(), UsersToProcess.end());
841 while (!UsersToProcess.empty()) {
842 SCEVHandle Base = UsersToProcess.front().Base;
844 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
846 // Emit the code for Base into the preheader.
847 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
850 // If BaseV is a constant other than 0, make sure that it gets inserted into
851 // the preheader, instead of being forward substituted into the uses. We do
852 // this by forcing a noop cast to be inserted into the preheader in this
854 if (Constant *C = dyn_cast<Constant>(BaseV))
855 if (!C->isNullValue() && !isTargetConstant(Base)) {
856 // We want this constant emitted into the preheader!
857 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
861 // Emit the code to add the immediate offset to the Phi value, just before
862 // the instructions that we identified as using this stride and base.
863 while (!UsersToProcess.empty() && UsersToProcess.front().Base == Base) {
864 BasedUser &User = UsersToProcess.front();
866 // If this instruction wants to use the post-incremented value, move it
867 // after the post-inc and use its value instead of the PHI.
868 Value *RewriteOp = NewPHI;
869 if (User.isUseOfPostIncrementedValue) {
872 // If this user is in the loop, make sure it is the last thing in the
873 // loop to ensure it is dominated by the increment.
874 if (L->contains(User.Inst->getParent()))
875 User.Inst->moveBefore(LatchBlock->getTerminator());
877 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
879 // Clear the SCEVExpander's expression map so that we are guaranteed
880 // to have the code emitted where we expect it.
883 // Now that we know what we need to do, insert code before User for the
884 // immediate and any loop-variant expressions.
885 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
886 // Add BaseV to the PHI value if needed.
887 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
889 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
891 // Mark old value we replaced as possibly dead, so that it is elminated
892 // if we just replaced the last use of that value.
893 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
895 UsersToProcess.erase(UsersToProcess.begin());
898 // TODO: Next, find out which base index is the most common, pull it out.
901 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
902 // different starting values, into different PHIs.
905 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
906 // uses in the loop, look to see if we can eliminate some, in favor of using
907 // common indvars for the different uses.
908 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
909 // TODO: implement optzns here.
914 // Finally, get the terminating condition for the loop if possible. If we
915 // can, we want to change it to use a post-incremented version of its
916 // induction variable, to allow coallescing the live ranges for the IV into
917 // one register value.
918 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
919 BasicBlock *Preheader = L->getLoopPreheader();
920 BasicBlock *LatchBlock =
921 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
922 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
923 if (!TermBr || TermBr->isUnconditional() ||
924 !isa<SetCondInst>(TermBr->getCondition()))
926 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
928 // Search IVUsesByStride to find Cond's IVUse if there is one.
929 IVStrideUse *CondUse = 0;
930 const SCEVHandle *CondStride = 0;
932 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator
933 I = IVUsesByStride.begin(), E = IVUsesByStride.end();
934 I != E && !CondUse; ++I)
935 for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
936 E = I->second.Users.end(); UI != E; ++UI)
937 if (UI->User == Cond) {
939 CondStride = &I->first;
940 // NOTE: we could handle setcc instructions with multiple uses here, but
941 // InstCombine does it as well for simple uses, it's not clear that it
942 // occurs enough in real life to handle.
945 if (!CondUse) return; // setcc doesn't use the IV.
947 // setcc stride is complex, don't mess with users.
948 // FIXME: Evaluate whether this is a good idea or not.
949 if (!isa<SCEVConstant>(*CondStride)) return;
951 // It's possible for the setcc instruction to be anywhere in the loop, and
952 // possible for it to have multiple users. If it is not immediately before
953 // the latch block branch, move it.
954 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
955 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
956 Cond->moveBefore(TermBr);
958 // Otherwise, clone the terminating condition and insert into the loopend.
959 Cond = cast<SetCondInst>(Cond->clone());
960 Cond->setName(L->getHeader()->getName() + ".termcond");
961 LatchBlock->getInstList().insert(TermBr, Cond);
963 // Clone the IVUse, as the old use still exists!
964 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
965 CondUse->OperandValToReplace);
966 CondUse = &IVUsesByStride[*CondStride].Users.back();
970 // If we get to here, we know that we can transform the setcc instruction to
971 // use the post-incremented version of the IV, allowing us to coallesce the
972 // live ranges for the IV correctly.
973 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
974 CondUse->isUseOfPostIncrementedValue = true;
977 void LoopStrengthReduce::runOnLoop(Loop *L) {
978 // First step, transform all loops nesting inside of this loop.
979 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
982 // Next, find all uses of induction variables in this loop, and catagorize
983 // them by stride. Start by finding all of the PHI nodes in the header for
984 // this loop. If they are induction variables, inspect their uses.
985 std::set<Instruction*> Processed; // Don't reprocess instructions.
986 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
987 AddUsersIfInteresting(I, L, Processed);
989 // If we have nothing to do, return.
990 if (IVUsesByStride.empty()) return;
992 // Optimize induction variables. Some indvar uses can be transformed to use
993 // strides that will be needed for other purposes. A common example of this
994 // is the exit test for the loop, which can often be rewritten to use the
995 // computation of some other indvar to decide when to terminate the loop.
999 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1000 // doing computation in byte values, promote to 32-bit values if safe.
1002 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1003 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1004 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1005 // to be careful that IV's are all the same type. Only works for intptr_t
1008 // If we only have one stride, we can more aggressively eliminate some things.
1009 bool HasOneStride = IVUsesByStride.size() == 1;
1011 // Note: this processes each stride/type pair individually. All users passed
1012 // into StrengthReduceStridedIVUsers have the same type AND stride.
1013 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI
1014 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
1015 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1017 // Clean up after ourselves
1018 if (!DeadInsts.empty()) {
1019 DeleteTriviallyDeadInstructions(DeadInsts);
1021 BasicBlock::iterator I = L->getHeader()->begin();
1023 while ((PN = dyn_cast<PHINode>(I))) {
1024 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1026 // At this point, we know that we have killed one or more GEP
1027 // instructions. It is worth checking to see if the cann indvar is also
1028 // dead, so that we can remove it as well. The requirements for the cann
1029 // indvar to be considered dead are:
1030 // 1. the cann indvar has one use
1031 // 2. the use is an add instruction
1032 // 3. the add has one use
1033 // 4. the add is used by the cann indvar
1034 // If all four cases above are true, then we can remove both the add and
1036 // FIXME: this needs to eliminate an induction variable even if it's being
1037 // compared against some value to decide loop termination.
1038 if (PN->hasOneUse()) {
1039 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
1040 if (BO && BO->hasOneUse()) {
1041 if (PN == *(BO->use_begin())) {
1042 DeadInsts.insert(BO);
1043 // Break the cycle, then delete the PHI.
1044 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1045 SE->deleteInstructionFromRecords(PN);
1046 PN->eraseFromParent();
1051 DeleteTriviallyDeadInstructions(DeadInsts);
1054 CastedPointers.clear();
1055 IVUsesByStride.clear();