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 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
95 /// We use this to iterate over the IVUsesByStride collection without being
96 /// dependent on random ordering of pointers in the process.
97 std::vector<SCEVHandle> StrideOrder;
99 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
100 /// of the casted version of each value. This is accessed by
101 /// getCastedVersionOf.
102 std::map<Value*, Value*> CastedPointers;
104 /// DeadInsts - Keep track of instructions we may have made dead, so that
105 /// we can remove them after we are done working.
106 std::set<Instruction*> DeadInsts;
108 LoopStrengthReduce(unsigned MTAMS = 1)
109 : MaxTargetAMSize(MTAMS) {
112 virtual bool runOnFunction(Function &) {
113 LI = &getAnalysis<LoopInfo>();
114 DS = &getAnalysis<DominatorSet>();
115 SE = &getAnalysis<ScalarEvolution>();
116 TD = &getAnalysis<TargetData>();
117 UIntPtrTy = TD->getIntPtrType();
120 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
126 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
127 // We split critical edges, so we change the CFG. However, we do update
128 // many analyses if they are around.
129 AU.addPreservedID(LoopSimplifyID);
130 AU.addPreserved<LoopInfo>();
131 AU.addPreserved<DominatorSet>();
132 AU.addPreserved<ImmediateDominators>();
133 AU.addPreserved<DominanceFrontier>();
134 AU.addPreserved<DominatorTree>();
136 AU.addRequiredID(LoopSimplifyID);
137 AU.addRequired<LoopInfo>();
138 AU.addRequired<DominatorSet>();
139 AU.addRequired<TargetData>();
140 AU.addRequired<ScalarEvolution>();
143 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
145 Value *getCastedVersionOf(Value *V);
147 void runOnLoop(Loop *L);
148 bool AddUsersIfInteresting(Instruction *I, Loop *L,
149 std::set<Instruction*> &Processed);
150 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
152 void OptimizeIndvars(Loop *L);
154 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
155 IVUsersOfOneStride &Uses,
156 Loop *L, bool isOnlyStride);
157 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
159 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
160 "Loop Strength Reduction");
163 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
164 return new LoopStrengthReduce(MaxTargetAMSize);
167 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
169 Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
170 if (V->getType() == UIntPtrTy) return V;
171 if (Constant *CB = dyn_cast<Constant>(V))
172 return ConstantExpr::getCast(CB, UIntPtrTy);
174 Value *&New = CastedPointers[V];
177 BasicBlock::iterator InsertPt;
178 if (Argument *Arg = dyn_cast<Argument>(V)) {
179 // Insert into the entry of the function, after any allocas.
180 InsertPt = Arg->getParent()->begin()->begin();
181 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
183 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
184 InsertPt = II->getNormalDest()->begin();
186 InsertPt = cast<Instruction>(V);
190 // Do not insert casts into the middle of PHI node blocks.
191 while (isa<PHINode>(InsertPt)) ++InsertPt;
194 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
195 DeadInsts.insert(cast<Instruction>(New));
200 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
201 /// specified set are trivially dead, delete them and see if this makes any of
202 /// their operands subsequently dead.
203 void LoopStrengthReduce::
204 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
205 while (!Insts.empty()) {
206 Instruction *I = *Insts.begin();
207 Insts.erase(Insts.begin());
208 if (isInstructionTriviallyDead(I)) {
209 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
210 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
212 SE->deleteInstructionFromRecords(I);
213 I->eraseFromParent();
220 /// GetExpressionSCEV - Compute and return the SCEV for the specified
222 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
223 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
224 // If this is a GEP that SE doesn't know about, compute it now and insert it.
225 // If this is not a GEP, or if we have already done this computation, just let
227 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
228 if (!GEP || SE->hasSCEV(GEP))
229 return SE->getSCEV(Exp);
231 // Analyze all of the subscripts of this getelementptr instruction, looking
232 // for uses that are determined by the trip count of L. First, skip all
233 // operands the are not dependent on the IV.
235 // Build up the base expression. Insert an LLVM cast of the pointer to
237 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
239 gep_type_iterator GTI = gep_type_begin(GEP);
241 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
242 // If this is a use of a recurrence that we can analyze, and it comes before
243 // Op does in the GEP operand list, we will handle this when we process this
245 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
246 const StructLayout *SL = TD->getStructLayout(STy);
247 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
248 uint64_t Offset = SL->MemberOffsets[Idx];
249 GEPVal = SCEVAddExpr::get(GEPVal,
250 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
252 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
253 SCEVHandle Idx = SE->getSCEV(OpVal);
255 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
257 Idx = SCEVMulExpr::get(Idx,
258 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
260 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
264 SE->setSCEV(GEP, GEPVal);
268 /// getSCEVStartAndStride - Compute the start and stride of this expression,
269 /// returning false if the expression is not a start/stride pair, or true if it
270 /// is. The stride must be a loop invariant expression, but the start may be
271 /// a mix of loop invariant and loop variant expressions.
272 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
273 SCEVHandle &Start, SCEVHandle &Stride) {
274 SCEVHandle TheAddRec = Start; // Initialize to zero.
276 // If the outer level is an AddExpr, the operands are all start values except
277 // for a nested AddRecExpr.
278 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
279 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
280 if (SCEVAddRecExpr *AddRec =
281 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
282 if (AddRec->getLoop() == L)
283 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
285 return false; // Nested IV of some sort?
287 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
290 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
293 return false; // not analyzable.
296 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
297 if (!AddRec || AddRec->getLoop() != L) return false;
299 // FIXME: Generalize to non-affine IV's.
300 if (!AddRec->isAffine()) return false;
302 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
304 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
305 DEBUG(std::cerr << "[" << L->getHeader()->getName()
306 << "] Variable stride: " << *AddRec << "\n");
308 Stride = AddRec->getOperand(1);
309 // Check that all constant strides are the unsigned type, we don't want to
310 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
312 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
313 "Constants should be canonicalized to unsigned!");
318 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
319 /// and now we need to decide whether the user should use the preinc or post-inc
320 /// value. If this user should use the post-inc version of the IV, return true.
322 /// Choosing wrong here can break dominance properties (if we choose to use the
323 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
324 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
325 /// should use the post-inc value).
326 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
327 Loop *L, DominatorSet *DS, Pass *P) {
328 // If the user is in the loop, use the preinc value.
329 if (L->contains(User->getParent())) return false;
331 BasicBlock *LatchBlock = L->getLoopLatch();
333 // Ok, the user is outside of the loop. If it is dominated by the latch
334 // block, use the post-inc value.
335 if (DS->dominates(LatchBlock, User->getParent()))
338 // There is one case we have to be careful of: PHI nodes. These little guys
339 // can live in blocks that do not dominate the latch block, but (since their
340 // uses occur in the predecessor block, not the block the PHI lives in) should
341 // still use the post-inc value. Check for this case now.
342 PHINode *PN = dyn_cast<PHINode>(User);
343 if (!PN) return false; // not a phi, not dominated by latch block.
345 // Look at all of the uses of IV by the PHI node. If any use corresponds to
346 // a block that is not dominated by the latch block, give up and use the
347 // preincremented value.
348 unsigned NumUses = 0;
349 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
350 if (PN->getIncomingValue(i) == IV) {
352 if (!DS->dominates(LatchBlock, PN->getIncomingBlock(i)))
356 // Okay, all uses of IV by PN are in predecessor blocks that really are
357 // dominated by the latch block. Split the critical edges and use the
358 // post-incremented value.
359 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
360 if (PN->getIncomingValue(i) == IV) {
361 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
362 if (--NumUses == 0) break;
370 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
371 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
372 /// return true. Otherwise, return false.
373 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
374 std::set<Instruction*> &Processed) {
375 if (I->getType() == Type::VoidTy) return false;
376 if (!Processed.insert(I).second)
377 return true; // Instruction already handled.
379 // Get the symbolic expression for this instruction.
380 SCEVHandle ISE = GetExpressionSCEV(I, L);
381 if (isa<SCEVCouldNotCompute>(ISE)) return false;
383 // Get the start and stride for this expression.
384 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
385 SCEVHandle Stride = Start;
386 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
387 return false; // Non-reducible symbolic expression, bail out.
389 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
390 Instruction *User = cast<Instruction>(*UI);
392 // Do not infinitely recurse on PHI nodes.
393 if (isa<PHINode>(User) && Processed.count(User))
396 // If this is an instruction defined in a nested loop, or outside this loop,
397 // don't recurse into it.
398 bool AddUserToIVUsers = false;
399 if (LI->getLoopFor(User->getParent()) != L) {
400 DEBUG(std::cerr << "FOUND USER in other loop: " << *User
401 << " OF SCEV: " << *ISE << "\n");
402 AddUserToIVUsers = true;
403 } else if (!AddUsersIfInteresting(User, L, Processed)) {
404 DEBUG(std::cerr << "FOUND USER: " << *User
405 << " OF SCEV: " << *ISE << "\n");
406 AddUserToIVUsers = true;
409 if (AddUserToIVUsers) {
410 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
411 if (StrideUses.Users.empty()) // First occurance of this stride?
412 StrideOrder.push_back(Stride);
414 // Okay, we found a user that we cannot reduce. Analyze the instruction
415 // and decide what to do with it. If we are a use inside of the loop, use
416 // the value before incrementation, otherwise use it after incrementation.
417 if (IVUseShouldUsePostIncValue(User, I, L, DS, this)) {
418 // The value used will be incremented by the stride more than we are
419 // expecting, so subtract this off.
420 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
421 StrideUses.addUser(NewStart, User, I);
422 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
423 DEBUG(std::cerr << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
425 StrideUses.addUser(Start, User, I);
433 /// BasedUser - For a particular base value, keep information about how we've
434 /// partitioned the expression so far.
436 /// Base - The Base value for the PHI node that needs to be inserted for
437 /// this use. As the use is processed, information gets moved from this
438 /// field to the Imm field (below). BasedUser values are sorted by this
442 /// Inst - The instruction using the induction variable.
445 /// OperandValToReplace - The operand value of Inst to replace with the
447 Value *OperandValToReplace;
449 /// Imm - The immediate value that should be added to the base immediately
450 /// before Inst, because it will be folded into the imm field of the
454 /// EmittedBase - The actual value* to use for the base value of this
455 /// operation. This is null if we should just use zero so far.
458 // isUseOfPostIncrementedValue - True if this should use the
459 // post-incremented version of this IV, not the preincremented version.
460 // This can only be set in special cases, such as the terminating setcc
461 // instruction for a loop and uses outside the loop that are dominated by
463 bool isUseOfPostIncrementedValue;
465 BasedUser(IVStrideUse &IVSU)
466 : Base(IVSU.Offset), Inst(IVSU.User),
467 OperandValToReplace(IVSU.OperandValToReplace),
468 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
469 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
471 // Once we rewrite the code to insert the new IVs we want, update the
472 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
474 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
475 SCEVExpander &Rewriter, Loop *L,
481 void BasedUser::dump() const {
482 std::cerr << " Base=" << *Base;
483 std::cerr << " Imm=" << *Imm;
485 std::cerr << " EB=" << *EmittedBase;
487 std::cerr << " Inst: " << *Inst;
490 // Once we rewrite the code to insert the new IVs we want, update the
491 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
493 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
494 SCEVExpander &Rewriter,
496 if (!isa<PHINode>(Inst)) {
497 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
498 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
499 OperandValToReplace->getType());
500 // Replace the use of the operand Value with the new Phi we just created.
501 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
502 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
506 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
507 // expression into each operand block that uses it. Note that PHI nodes can
508 // have multiple entries for the same predecessor. We use a map to make sure
509 // that a PHI node only has a single Value* for each predecessor (which also
510 // prevents us from inserting duplicate code in some blocks).
511 std::map<BasicBlock*, Value*> InsertedCode;
512 PHINode *PN = cast<PHINode>(Inst);
513 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
514 if (PN->getIncomingValue(i) == OperandValToReplace) {
515 // If this is a critical edge, split the edge so that we do not insert the
516 // code on all predecessor/successor paths. We do this unless this is the
517 // canonical backedge for this loop, as this can make some inserted code
518 // be in an illegal position.
519 BasicBlock *PHIPred = PN->getIncomingBlock(i);
520 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
521 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
523 // First step, split the critical edge.
524 SplitCriticalEdge(PHIPred, PN->getParent(), P);
526 // Next step: move the basic block. In particular, if the PHI node
527 // is outside of the loop, and PredTI is in the loop, we want to
528 // move the block to be immediately before the PHI block, not
529 // immediately after PredTI.
530 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
531 BasicBlock *NewBB = PN->getIncomingBlock(i);
532 NewBB->moveBefore(PN->getParent());
536 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
538 // Insert the code into the end of the predecessor block.
539 BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
541 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
542 Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
543 OperandValToReplace->getType());
546 // Replace the use of the operand Value with the new Phi we just created.
547 PN->setIncomingValue(i, Code);
551 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
555 /// isTargetConstant - Return true if the following can be referenced by the
556 /// immediate field of a target instruction.
557 static bool isTargetConstant(const SCEVHandle &V) {
559 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
560 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
561 // PPC allows a sign-extended 16-bit immediate field.
562 if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
563 (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
568 return false; // ENABLE this for x86
570 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
571 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
572 if (CE->getOpcode() == Instruction::Cast)
573 if (isa<GlobalValue>(CE->getOperand(0)))
574 // FIXME: should check to see that the dest is uintptr_t!
579 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
580 /// loop varying to the Imm operand.
581 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
583 if (Val->isLoopInvariant(L)) return; // Nothing to do.
585 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
586 std::vector<SCEVHandle> NewOps;
587 NewOps.reserve(SAE->getNumOperands());
589 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
590 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
591 // If this is a loop-variant expression, it must stay in the immediate
592 // field of the expression.
593 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
595 NewOps.push_back(SAE->getOperand(i));
599 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
601 Val = SCEVAddExpr::get(NewOps);
602 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
603 // Try to pull immediates out of the start value of nested addrec's.
604 SCEVHandle Start = SARE->getStart();
605 MoveLoopVariantsToImediateField(Start, Imm, L);
607 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
609 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
611 // Otherwise, all of Val is variant, move the whole thing over.
612 Imm = SCEVAddExpr::get(Imm, Val);
613 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
618 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
619 /// that can fit into the immediate field of instructions in the target.
620 /// Accumulate these immediate values into the Imm value.
621 static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
622 bool isAddress, Loop *L) {
623 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
624 std::vector<SCEVHandle> NewOps;
625 NewOps.reserve(SAE->getNumOperands());
627 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
628 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
629 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
630 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
631 // If this is a loop-variant expression, it must stay in the immediate
632 // field of the expression.
633 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
635 NewOps.push_back(SAE->getOperand(i));
639 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
641 Val = SCEVAddExpr::get(NewOps);
643 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
644 // Try to pull immediates out of the start value of nested addrec's.
645 SCEVHandle Start = SARE->getStart();
646 MoveImmediateValues(Start, Imm, isAddress, L);
648 if (Start != SARE->getStart()) {
649 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
651 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
656 // Loop-variant expressions must stay in the immediate field of the
658 if ((isAddress && isTargetConstant(Val)) ||
659 !Val->isLoopInvariant(L)) {
660 Imm = SCEVAddExpr::get(Imm, Val);
661 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
665 // Otherwise, no immediates to move.
669 /// IncrementAddExprUses - Decompose the specified expression into its added
670 /// subexpressions, and increment SubExpressionUseCounts for each of these
671 /// decomposed parts.
672 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
674 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
675 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
676 SeparateSubExprs(SubExprs, AE->getOperand(j));
677 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
678 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
679 if (SARE->getOperand(0) == Zero) {
680 SubExprs.push_back(Expr);
682 // Compute the addrec with zero as its base.
683 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
684 Ops[0] = Zero; // Start with zero base.
685 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
688 SeparateSubExprs(SubExprs, SARE->getOperand(0));
690 } else if (!isa<SCEVConstant>(Expr) ||
691 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
693 SubExprs.push_back(Expr);
698 /// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
699 /// removing any common subexpressions from it. Anything truly common is
700 /// removed, accumulated, and returned. This looks for things like (a+b+c) and
701 /// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
703 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
704 unsigned NumUses = Uses.size();
706 // Only one use? Use its base, regardless of what it is!
707 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
708 SCEVHandle Result = Zero;
710 std::swap(Result, Uses[0].Base);
714 // To find common subexpressions, count how many of Uses use each expression.
715 // If any subexpressions are used Uses.size() times, they are common.
716 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
718 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
719 // order we see them.
720 std::vector<SCEVHandle> UniqueSubExprs;
722 std::vector<SCEVHandle> SubExprs;
723 for (unsigned i = 0; i != NumUses; ++i) {
724 // If the base is zero (which is common), return zero now, there are no
726 if (Uses[i].Base == Zero) return Zero;
728 // Split the expression into subexprs.
729 SeparateSubExprs(SubExprs, Uses[i].Base);
730 // Add one to SubExpressionUseCounts for each subexpr present.
731 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
732 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
733 UniqueSubExprs.push_back(SubExprs[j]);
737 // Now that we know how many times each is used, build Result. Iterate over
738 // UniqueSubexprs so that we have a stable ordering.
739 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
740 std::map<SCEVHandle, unsigned>::iterator I =
741 SubExpressionUseCounts.find(UniqueSubExprs[i]);
742 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
743 if (I->second == NumUses) { // Found CSE!
744 Result = SCEVAddExpr::get(Result, I->first);
746 // Remove non-cse's from SubExpressionUseCounts.
747 SubExpressionUseCounts.erase(I);
751 // If we found no CSE's, return now.
752 if (Result == Zero) return Result;
754 // Otherwise, remove all of the CSE's we found from each of the base values.
755 for (unsigned i = 0; i != NumUses; ++i) {
756 // Split the expression into subexprs.
757 SeparateSubExprs(SubExprs, Uses[i].Base);
759 // Remove any common subexpressions.
760 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
761 if (SubExpressionUseCounts.count(SubExprs[j])) {
762 SubExprs.erase(SubExprs.begin()+j);
766 // Finally, the non-shared expressions together.
767 if (SubExprs.empty())
770 Uses[i].Base = SCEVAddExpr::get(SubExprs);
778 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
779 /// stride of IV. All of the users may have different starting values, and this
780 /// may not be the only stride (we know it is if isOnlyStride is true).
781 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
782 IVUsersOfOneStride &Uses,
785 // Transform our list of users and offsets to a bit more complex table. In
786 // this new vector, each 'BasedUser' contains 'Base' the base of the
787 // strided accessas well as the old information from Uses. We progressively
788 // move information from the Base field to the Imm field, until we eventually
789 // have the full access expression to rewrite the use.
790 std::vector<BasedUser> UsersToProcess;
791 UsersToProcess.reserve(Uses.Users.size());
792 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
793 UsersToProcess.push_back(Uses.Users[i]);
795 // Move any loop invariant operands from the offset field to the immediate
796 // field of the use, so that we don't try to use something before it is
798 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
799 UsersToProcess.back().Imm, L);
800 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
801 "Base value is not loop invariant!");
804 // We now have a whole bunch of uses of like-strided induction variables, but
805 // they might all have different bases. We want to emit one PHI node for this
806 // stride which we fold as many common expressions (between the IVs) into as
807 // possible. Start by identifying the common expressions in the base values
808 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
809 // "A+B"), emit it to the preheader, then remove the expression from the
810 // UsersToProcess base values.
811 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
813 // Next, figure out what we can represent in the immediate fields of
814 // instructions. If we can represent anything there, move it to the imm
815 // fields of the BasedUsers. We do this so that it increases the commonality
816 // of the remaining uses.
817 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
818 // If the user is not in the current loop, this means it is using the exit
819 // value of the IV. Do not put anything in the base, make sure it's all in
820 // the immediate field to allow as much factoring as possible.
821 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
822 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
823 UsersToProcess[i].Base);
824 UsersToProcess[i].Base =
825 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
828 // Addressing modes can be folded into loads and stores. Be careful that
829 // the store is through the expression, not of the expression though.
830 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
831 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
832 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
835 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
840 // Now that we know what we need to do, insert the PHI node itself.
842 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
843 << *CommonExprs << " :\n");
845 SCEVExpander Rewriter(*SE, *LI);
846 SCEVExpander PreheaderRewriter(*SE, *LI);
848 BasicBlock *Preheader = L->getLoopPreheader();
849 Instruction *PreInsertPt = Preheader->getTerminator();
850 Instruction *PhiInsertBefore = L->getHeader()->begin();
852 BasicBlock *LatchBlock = L->getLoopLatch();
854 // Create a new Phi for this base, and stick it in the loop header.
855 const Type *ReplacedTy = CommonExprs->getType();
856 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
859 // Insert the stride into the preheader.
860 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
862 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
865 // Emit the initial base value into the loop preheader, and add it to the
867 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
869 NewPHI->addIncoming(PHIBaseV, Preheader);
871 // Emit the increment of the base value before the terminator of the loop
872 // latch block, and add it to the Phi node.
873 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
874 SCEVUnknown::get(StrideV));
876 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
878 IncV->setName(NewPHI->getName()+".inc");
879 NewPHI->addIncoming(IncV, LatchBlock);
881 // Sort by the base value, so that all IVs with identical bases are next to
883 while (!UsersToProcess.empty()) {
884 SCEVHandle Base = UsersToProcess.back().Base;
886 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
888 // Emit the code for Base into the preheader.
889 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
892 // If BaseV is a constant other than 0, make sure that it gets inserted into
893 // the preheader, instead of being forward substituted into the uses. We do
894 // this by forcing a noop cast to be inserted into the preheader in this
896 if (Constant *C = dyn_cast<Constant>(BaseV))
897 if (!C->isNullValue() && !isTargetConstant(Base)) {
898 // We want this constant emitted into the preheader!
899 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
903 // Emit the code to add the immediate offset to the Phi value, just before
904 // the instructions that we identified as using this stride and base.
905 unsigned ScanPos = 0;
907 BasedUser &User = UsersToProcess.back();
909 // If this instruction wants to use the post-incremented value, move it
910 // after the post-inc and use its value instead of the PHI.
911 Value *RewriteOp = NewPHI;
912 if (User.isUseOfPostIncrementedValue) {
915 // If this user is in the loop, make sure it is the last thing in the
916 // loop to ensure it is dominated by the increment.
917 if (L->contains(User.Inst->getParent()))
918 User.Inst->moveBefore(LatchBlock->getTerminator());
920 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
922 // Clear the SCEVExpander's expression map so that we are guaranteed
923 // to have the code emitted where we expect it.
926 // Now that we know what we need to do, insert code before User for the
927 // immediate and any loop-variant expressions.
928 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
929 // Add BaseV to the PHI value if needed.
930 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
932 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
934 // Mark old value we replaced as possibly dead, so that it is elminated
935 // if we just replaced the last use of that value.
936 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
938 UsersToProcess.pop_back();
941 // If there are any more users to process with the same base, move one of
942 // them to the end of the list so that we will process it.
943 if (!UsersToProcess.empty()) {
944 for (unsigned e = UsersToProcess.size(); ScanPos != e; ++ScanPos)
945 if (UsersToProcess[ScanPos].Base == Base) {
946 std::swap(UsersToProcess[ScanPos], UsersToProcess.back());
950 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
951 // TODO: Next, find out which base index is the most common, pull it out.
954 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
955 // different starting values, into different PHIs.
958 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
959 // uses in the loop, look to see if we can eliminate some, in favor of using
960 // common indvars for the different uses.
961 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
962 // TODO: implement optzns here.
967 // Finally, get the terminating condition for the loop if possible. If we
968 // can, we want to change it to use a post-incremented version of its
969 // induction variable, to allow coallescing the live ranges for the IV into
970 // one register value.
971 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
972 BasicBlock *Preheader = L->getLoopPreheader();
973 BasicBlock *LatchBlock =
974 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
975 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
976 if (!TermBr || TermBr->isUnconditional() ||
977 !isa<SetCondInst>(TermBr->getCondition()))
979 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
981 // Search IVUsesByStride to find Cond's IVUse if there is one.
982 IVStrideUse *CondUse = 0;
983 const SCEVHandle *CondStride = 0;
985 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
987 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
988 IVUsesByStride.find(StrideOrder[Stride]);
989 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
991 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
992 E = SI->second.Users.end(); UI != E; ++UI)
993 if (UI->User == Cond) {
995 CondStride = &SI->first;
996 // NOTE: we could handle setcc instructions with multiple uses here, but
997 // InstCombine does it as well for simple uses, it's not clear that it
998 // occurs enough in real life to handle.
1002 if (!CondUse) return; // setcc doesn't use the IV.
1004 // setcc stride is complex, don't mess with users.
1005 // FIXME: Evaluate whether this is a good idea or not.
1006 if (!isa<SCEVConstant>(*CondStride)) return;
1008 // It's possible for the setcc instruction to be anywhere in the loop, and
1009 // possible for it to have multiple users. If it is not immediately before
1010 // the latch block branch, move it.
1011 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1012 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1013 Cond->moveBefore(TermBr);
1015 // Otherwise, clone the terminating condition and insert into the loopend.
1016 Cond = cast<SetCondInst>(Cond->clone());
1017 Cond->setName(L->getHeader()->getName() + ".termcond");
1018 LatchBlock->getInstList().insert(TermBr, Cond);
1020 // Clone the IVUse, as the old use still exists!
1021 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
1022 CondUse->OperandValToReplace);
1023 CondUse = &IVUsesByStride[*CondStride].Users.back();
1027 // If we get to here, we know that we can transform the setcc instruction to
1028 // use the post-incremented version of the IV, allowing us to coallesce the
1029 // live ranges for the IV correctly.
1030 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
1031 CondUse->isUseOfPostIncrementedValue = true;
1034 void LoopStrengthReduce::runOnLoop(Loop *L) {
1035 // First step, transform all loops nesting inside of this loop.
1036 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1039 // Next, find all uses of induction variables in this loop, and catagorize
1040 // them by stride. Start by finding all of the PHI nodes in the header for
1041 // this loop. If they are induction variables, inspect their uses.
1042 std::set<Instruction*> Processed; // Don't reprocess instructions.
1043 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
1044 AddUsersIfInteresting(I, L, Processed);
1046 // If we have nothing to do, return.
1047 if (IVUsesByStride.empty()) return;
1049 // Optimize induction variables. Some indvar uses can be transformed to use
1050 // strides that will be needed for other purposes. A common example of this
1051 // is the exit test for the loop, which can often be rewritten to use the
1052 // computation of some other indvar to decide when to terminate the loop.
1056 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1057 // doing computation in byte values, promote to 32-bit values if safe.
1059 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1060 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1061 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1062 // to be careful that IV's are all the same type. Only works for intptr_t
1065 // If we only have one stride, we can more aggressively eliminate some things.
1066 bool HasOneStride = IVUsesByStride.size() == 1;
1068 // Note: this processes each stride/type pair individually. All users passed
1069 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1070 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1071 // This extra layer of indirection makes the ordering of strides deterministic
1072 // - not dependent on map order.
1073 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1074 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1075 IVUsesByStride.find(StrideOrder[Stride]);
1076 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1077 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1080 // Clean up after ourselves
1081 if (!DeadInsts.empty()) {
1082 DeleteTriviallyDeadInstructions(DeadInsts);
1084 BasicBlock::iterator I = L->getHeader()->begin();
1086 while ((PN = dyn_cast<PHINode>(I))) {
1087 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1089 // At this point, we know that we have killed one or more GEP
1090 // instructions. It is worth checking to see if the cann indvar is also
1091 // dead, so that we can remove it as well. The requirements for the cann
1092 // indvar to be considered dead are:
1093 // 1. the cann indvar has one use
1094 // 2. the use is an add instruction
1095 // 3. the add has one use
1096 // 4. the add is used by the cann indvar
1097 // If all four cases above are true, then we can remove both the add and
1099 // FIXME: this needs to eliminate an induction variable even if it's being
1100 // compared against some value to decide loop termination.
1101 if (PN->hasOneUse()) {
1102 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
1103 if (BO && BO->hasOneUse()) {
1104 if (PN == *(BO->use_begin())) {
1105 DeadInsts.insert(BO);
1106 // Break the cycle, then delete the PHI.
1107 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1108 SE->deleteInstructionFromRecords(PN);
1109 PN->eraseFromParent();
1114 DeleteTriviallyDeadInstructions(DeadInsts);
1117 CastedPointers.clear();
1118 IVUsesByStride.clear();
1119 StrideOrder.clear();