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 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Type.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/ScalarEvolutionExpander.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Support/Debug.h"
37 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
41 GEPCache() : CachedPHINode(0), Map() {}
43 GEPCache *get(Value *v) {
44 std::map<Value *, GEPCache>::iterator I = Map.find(v);
46 I = Map.insert(std::pair<Value *, GEPCache>(v, GEPCache())).first;
50 PHINode *CachedPHINode;
51 std::map<Value *, GEPCache> Map;
55 /// Users - Keep track of all of the users of this stride as well as the
57 std::vector<std::pair<SCEVHandle, Instruction*> > Users;
58 std::vector<Instruction *> UserOperands;
60 void addUser(SCEVHandle &SH, Instruction *U, Instruction *V) {
61 Users.push_back(std::make_pair(SH, U));
62 UserOperands.push_back(V);
67 class LoopStrengthReduce : public FunctionPass {
72 const Type *UIntPtrTy;
75 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
76 /// target can handle for free with its addressing modes.
77 unsigned MaxTargetAMSize;
79 /// IVUsesByStride - Keep track of all uses of induction variables that we
80 /// are interested in. The key of the map is the stride of the access.
81 std::map<Value*, IVUse> IVUsesByStride;
83 /// CastedBasePointers - As we need to lower getelementptr instructions, we
84 /// cast the pointer input to uintptr_t. This keeps track of the casted
85 /// values for the pointers we have processed so far.
86 std::map<Value*, Value*> CastedBasePointers;
88 /// DeadInsts - Keep track of instructions we may have made dead, so that
89 /// we can remove them after we are done working.
90 std::set<Instruction*> DeadInsts;
92 LoopStrengthReduce(unsigned MTAMS = 1)
93 : MaxTargetAMSize(MTAMS) {
96 virtual bool runOnFunction(Function &) {
97 LI = &getAnalysis<LoopInfo>();
98 DS = &getAnalysis<DominatorSet>();
99 SE = &getAnalysis<ScalarEvolution>();
100 TD = &getAnalysis<TargetData>();
101 UIntPtrTy = TD->getIntPtrType();
104 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110 AU.setPreservesCFG();
111 AU.addRequiredID(LoopSimplifyID);
112 AU.addRequired<LoopInfo>();
113 AU.addRequired<DominatorSet>();
114 AU.addRequired<TargetData>();
115 AU.addRequired<ScalarEvolution>();
118 void runOnLoop(Loop *L);
119 bool AddUsersIfInteresting(Instruction *I, Loop *L);
120 void AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP, Instruction *I,
123 void StrengthReduceStridedIVUsers(Value *Stride, IVUse &Uses, Loop *L,
126 void strengthReduceGEP(GetElementPtrInst *GEPI, Loop *L,
128 Instruction *InsertBefore,
129 std::set<Instruction*> &DeadInsts);
130 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
132 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
133 "Strength Reduce GEP Uses of Ind. Vars");
136 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
137 return new LoopStrengthReduce(MaxTargetAMSize);
140 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
141 /// specified set are trivially dead, delete them and see if this makes any of
142 /// their operands subsequently dead.
143 void LoopStrengthReduce::
144 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
145 while (!Insts.empty()) {
146 Instruction *I = *Insts.begin();
147 Insts.erase(Insts.begin());
148 if (isInstructionTriviallyDead(I)) {
149 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
150 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
152 SE->deleteInstructionFromRecords(I);
153 I->eraseFromParent();
160 /// CanReduceSCEV - Return true if we can strength reduce this scalar evolution
161 /// in the specified loop.
162 static bool CanReduceSCEV(const SCEVHandle &SH, Loop *L) {
163 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH);
164 if (!AddRec || AddRec->getLoop() != L) return false;
166 // FIXME: Generalize to non-affine IV's.
167 if (!AddRec->isAffine()) return false;
169 // FIXME: generalize to IV's with more complex strides (must emit stride
170 // expression outside of loop!)
171 if (isa<SCEVConstant>(AddRec->getOperand(1)))
174 // We handle steps by unsigned values, because we know we won't have to insert
176 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(AddRec->getOperand(1)))
177 if (SU->getValue()->getType()->isUnsigned())
180 // Otherwise, no, we can't handle it yet.
185 /// GetAdjustedIndex - Adjust the specified GEP sequential type index to match
186 /// the size of the pointer type, and scale it by the type size.
187 static SCEVHandle GetAdjustedIndex(const SCEVHandle &Idx, uint64_t TySize,
188 const Type *UIntPtrTy) {
189 SCEVHandle Result = Idx;
190 if (Result->getType()->getUnsignedVersion() != UIntPtrTy) {
191 if (UIntPtrTy->getPrimitiveSize() < Result->getType()->getPrimitiveSize())
192 Result = SCEVTruncateExpr::get(Result, UIntPtrTy);
194 Result = SCEVZeroExtendExpr::get(Result, UIntPtrTy);
197 // This index is scaled by the type size being indexed.
199 Result = SCEVMulExpr::get(Result,
200 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
205 /// AnalyzeGetElementPtrUsers - Analyze all of the users of the specified
206 /// getelementptr instruction, adding them to the IVUsesByStride table. Note
207 /// that we only want to analyze a getelementptr instruction once, and it can
208 /// have multiple operands that are uses of the indvar (e.g. A[i][i]). Because
209 /// of this, we only process a GEP instruction if its first recurrent operand is
210 /// "op", otherwise we will either have already processed it or we will sometime
212 void LoopStrengthReduce::AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP,
213 Instruction *Op, Loop *L) {
214 // Analyze all of the subscripts of this getelementptr instruction, looking
215 // for uses that are determined by the trip count of L. First, skip all
216 // operands the are not dependent on the IV.
218 // Build up the base expression. Insert an LLVM cast of the pointer to
221 if (Constant *CB = dyn_cast<Constant>(GEP->getOperand(0)))
222 BasePtr = ConstantExpr::getCast(CB, UIntPtrTy);
224 Value *&BP = CastedBasePointers[GEP->getOperand(0)];
226 BasicBlock::iterator InsertPt;
227 if (isa<Argument>(GEP->getOperand(0))) {
228 InsertPt = GEP->getParent()->getParent()->begin()->begin();
230 InsertPt = cast<Instruction>(GEP->getOperand(0));
231 if (InvokeInst *II = dyn_cast<InvokeInst>(GEP->getOperand(0)))
232 InsertPt = II->getNormalDest()->begin();
237 // Do not insert casts into the middle of PHI node blocks.
238 while (isa<PHINode>(InsertPt)) ++InsertPt;
240 BP = new CastInst(GEP->getOperand(0), UIntPtrTy,
241 GEP->getOperand(0)->getName(), InsertPt);
246 SCEVHandle Base = SCEVUnknown::get(BasePtr);
248 gep_type_iterator GTI = gep_type_begin(GEP);
250 for (; GEP->getOperand(i) != Op; ++i, ++GTI) {
251 // If this is a use of a recurrence that we can analyze, and it comes before
252 // Op does in the GEP operand list, we will handle this when we process this
254 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
255 const StructLayout *SL = TD->getStructLayout(STy);
256 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
257 uint64_t Offset = SL->MemberOffsets[Idx];
258 Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset,
261 SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i));
263 // If this operand is reducible, and it's not the one we are looking at
264 // currently, do not process the GEP at this time.
265 if (CanReduceSCEV(Idx, L))
267 Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx,
268 TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy));
272 // Get the index, convert it to intptr_t.
273 SCEVHandle GEPIndexExpr =
274 GetAdjustedIndex(SE->getSCEV(Op), TD->getTypeSize(GTI.getIndexedType()),
277 // Process all remaining subscripts in the GEP instruction.
278 for (++i, ++GTI; i != GEP->getNumOperands(); ++i, ++GTI)
279 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
280 const StructLayout *SL = TD->getStructLayout(STy);
281 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
282 uint64_t Offset = SL->MemberOffsets[Idx];
283 Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset,
286 SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i));
287 if (CanReduceSCEV(Idx, L)) { // Another IV subscript
288 GEPIndexExpr = SCEVAddExpr::get(GEPIndexExpr,
289 GetAdjustedIndex(Idx, TD->getTypeSize(GTI.getIndexedType()),
291 assert(CanReduceSCEV(GEPIndexExpr, L) &&
292 "Cannot reduce the sum of two reducible SCEV's??");
294 Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx,
295 TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy));
299 assert(CanReduceSCEV(GEPIndexExpr, L) && "Non reducible idx??");
301 // FIXME: If the base is not loop invariant, we currently cannot emit this.
302 if (!Base->isLoopInvariant(L)) {
303 DEBUG(std::cerr << "IGNORING GEP due to non-invaiant base: "
308 Base = SCEVAddExpr::get(Base, cast<SCEVAddRecExpr>(GEPIndexExpr)->getStart());
309 SCEVHandle Stride = cast<SCEVAddRecExpr>(GEPIndexExpr)->getOperand(1);
311 DEBUG(std::cerr << "GEP BASE : " << *Base << "\n");
312 DEBUG(std::cerr << "GEP STRIDE: " << *Stride << "\n");
314 Value *Step = 0; // Step of ISE.
315 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride))
316 /// Always get the step value as an unsigned value.
317 Step = ConstantExpr::getCast(SC->getValue(),
318 SC->getValue()->getType()->getUnsignedVersion());
320 Step = cast<SCEVUnknown>(Stride)->getValue();
321 assert(Step->getType()->isUnsigned() && "Bad step value!");
324 // Now that we know the base and stride contributed by the GEP instruction,
325 // process all users.
326 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
328 Instruction *User = cast<Instruction>(*UI);
330 // Do not infinitely recurse on PHI nodes.
331 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
334 // If this is an instruction defined in a nested loop, or outside this loop,
335 // don't mess with it.
336 if (LI->getLoopFor(User->getParent()) != L)
339 DEBUG(std::cerr << "FOUND USER: " << *User
340 << " OF STRIDE: " << *Step << " BASE = " << *Base << "\n");
343 // Okay, we found a user that we cannot reduce. Analyze the instruction
344 // and decide what to do with it.
345 IVUsesByStride[Step].addUser(Base, User, GEP);
349 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
350 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
351 /// return true. Otherwise, return false.
352 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L) {
353 if (I->getType() == Type::VoidTy) return false;
354 SCEVHandle ISE = SE->getSCEV(I);
355 if (!CanReduceSCEV(ISE, L)) return false;
357 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(ISE);
358 SCEVHandle Start = AR->getStart();
360 // Get the step value, canonicalizing to an unsigned integer type so that
361 // lookups in the map will match.
362 Value *Step = 0; // Step of ISE.
363 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(AR->getOperand(1)))
364 /// Always get the step value as an unsigned value.
365 Step = ConstantExpr::getCast(SC->getValue(),
366 SC->getValue()->getType()->getUnsignedVersion());
368 Step = cast<SCEVUnknown>(AR->getOperand(1))->getValue();
369 assert(Step->getType()->isUnsigned() && "Bad step value!");
371 std::set<GetElementPtrInst*> AnalyzedGEPs;
373 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
374 Instruction *User = cast<Instruction>(*UI);
376 // Do not infinitely recurse on PHI nodes.
377 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
380 // If this is an instruction defined in a nested loop, or outside this loop,
381 // don't mess with it.
382 if (LI->getLoopFor(User->getParent()) != L)
385 // Next, see if this user is analyzable itself!
386 if (!AddUsersIfInteresting(User, L)) {
387 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
388 // If this is a getelementptr instruction, figure out what linear
389 // expression of induction variable is actually being used.
391 if (AnalyzedGEPs.insert(GEP).second) // Not already analyzed?
392 AnalyzeGetElementPtrUsers(GEP, I, L);
394 DEBUG(std::cerr << "FOUND USER: " << *User
395 << " OF SCEV: " << *ISE << "\n");
397 // Okay, we found a user that we cannot reduce. Analyze the instruction
398 // and decide what to do with it.
399 IVUsesByStride[Step].addUser(Start, User, I);
407 /// BasedUser - For a particular base value, keep information about how we've
408 /// partitioned the expression so far.
410 /// Inst - The instruction using the induction variable.
413 /// Op - The value to replace with the EmittedBase.
416 /// Imm - The immediate value that should be added to the base immediately
417 /// before Inst, because it will be folded into the imm field of the
421 /// EmittedBase - The actual value* to use for the base value of this
422 /// operation. This is null if we should just use zero so far.
425 BasedUser(Instruction *I, Value *V, const SCEVHandle &IMM)
426 : Inst(I), Op(V), Imm(IMM), EmittedBase(0) {}
429 // No need to compare these.
430 bool operator<(const BasedUser &BU) const { return 0; }
436 void BasedUser::dump() const {
437 std::cerr << " Imm=" << *Imm;
439 std::cerr << " EB=" << *EmittedBase;
441 std::cerr << " Inst: " << *Inst;
444 /// isTargetConstant - Return true if the following can be referenced by the
445 /// immediate field of a target instruction.
446 static bool isTargetConstant(const SCEVHandle &V) {
448 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
449 if (isa<SCEVConstant>(V)) return true;
451 return false; // ENABLE this for x86
453 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
454 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
455 if (CE->getOpcode() == Instruction::Cast)
456 if (isa<GlobalValue>(CE->getOperand(0)))
457 // FIXME: should check to see that the dest is uintptr_t!
462 /// GetImmediateValues - Look at Val, and pull out any additions of constants
463 /// that can fit into the immediate field of instructions in the target.
464 static SCEVHandle GetImmediateValues(SCEVHandle Val, bool isAddress) {
466 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
467 if (isTargetConstant(Val))
470 SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val);
473 for (; i != SAE->getNumOperands(); ++i)
474 if (isTargetConstant(SAE->getOperand(i))) {
475 SCEVHandle ImmVal = SAE->getOperand(i);
477 // If there are any other immediates that we can handle here, pull them
479 for (++i; i != SAE->getNumOperands(); ++i)
480 if (isTargetConstant(SAE->getOperand(i)))
481 ImmVal = SCEVAddExpr::get(ImmVal, SAE->getOperand(i));
486 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
489 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
490 /// stride of IV. All of the users may have different starting values, and this
491 /// may not be the only stride (we know it is if isOnlyStride is true).
492 void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
493 IVUse &Uses, Loop *L,
495 // Transform our list of users and offsets to a bit more complex table. In
496 // this new vector, the first entry for each element is the base of the
497 // strided access, and the second is the BasedUser object for the use. We
498 // progressively move information from the first to the second entry, until we
499 // eventually emit the object.
500 std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess;
501 UsersToProcess.reserve(Uses.Users.size());
503 SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0,
504 Uses.Users[0].first->getType());
506 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i)
507 UsersToProcess.push_back(std::make_pair(Uses.Users[i].first,
508 BasedUser(Uses.Users[i].second,
509 Uses.UserOperands[i],
512 // First pass, figure out what we can represent in the immediate fields of
513 // instructions. If we can represent anything there, move it to the imm
514 // fields of the BasedUsers.
515 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
516 bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst) ||
517 isa<StoreInst>(UsersToProcess[i].second.Inst);
518 UsersToProcess[i].second.Imm = GetImmediateValues(UsersToProcess[i].first,
520 UsersToProcess[i].first = SCEV::getMinusSCEV(UsersToProcess[i].first,
521 UsersToProcess[i].second.Imm);
523 DEBUG(std::cerr << "BASE: " << *UsersToProcess[i].first);
524 DEBUG(UsersToProcess[i].second.dump());
527 SCEVExpander Rewriter(*SE, *LI);
528 BasicBlock *Preheader = L->getLoopPreheader();
529 Instruction *PreInsertPt = Preheader->getTerminator();
530 Instruction *PhiInsertBefore = L->getHeader()->begin();
532 assert(isa<PHINode>(PhiInsertBefore) &&
533 "How could this loop have IV's without any phis?");
534 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
535 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
536 "This loop isn't canonicalized right");
537 BasicBlock *LatchBlock =
538 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
540 // FIXME: This loop needs increasing levels of intelligence.
541 // STAGE 0: just emit everything as its own base. <-- We are here
542 // STAGE 1: factor out common vars from bases, and try and push resulting
543 // constants into Imm field.
544 // STAGE 2: factor out large constants to try and make more constants
545 // acceptable for target loads and stores.
546 std::sort(UsersToProcess.begin(), UsersToProcess.end());
548 while (!UsersToProcess.empty()) {
549 // Create a new Phi for this base, and stick it in the loop header.
550 Value *Replaced = UsersToProcess.front().second.Op;
551 const Type *ReplacedTy = Replaced->getType();
552 PHINode *NewPHI = new PHINode(ReplacedTy, Replaced->getName()+".str",
555 // Emit the initial base value into the loop preheader, and add it to the
557 Value *BaseV = Rewriter.expandCodeFor(UsersToProcess.front().first,
558 PreInsertPt, ReplacedTy);
559 NewPHI->addIncoming(BaseV, Preheader);
561 // Emit the increment of the base value before the terminator of the loop
562 // latch block, and add it to the Phi node.
563 SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
564 SCEVUnknown::get(Stride));
566 Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(),
568 IncV->setName(NewPHI->getName()+".inc");
569 NewPHI->addIncoming(IncV, LatchBlock);
571 // Emit the code to add the immediate offset to the Phi value, just before
572 // the instruction that we identified as using this stride and base.
573 // First, empty the SCEVExpander's expression map so that we are guaranteed
574 // to have the code emitted where we expect it.
576 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
577 UsersToProcess.front().second.Imm);
578 Value *newVal = Rewriter.expandCodeFor(NewValSCEV,
579 UsersToProcess.front().second.Inst,
582 // Replace the use of the operand Value with the new Phi we just created.
583 DEBUG(std::cerr << "REPLACING: " << *Replaced << "IN: " <<
584 *UsersToProcess.front().second.Inst << "WITH: "<< *newVal << '\n');
585 UsersToProcess.front().second.Inst->replaceUsesOfWith(Replaced, newVal);
587 // Mark old value we replaced as possibly dead, so that it is elminated
588 // if we just replaced the last use of that value.
589 DeadInsts.insert(cast<Instruction>(Replaced));
591 UsersToProcess.erase(UsersToProcess.begin());
594 // TODO: Next, find out which base index is the most common, pull it out.
597 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
598 // different starting values, into different PHIs.
600 // BEFORE writing this, it's probably useful to handle GEP's.
602 // NOTE: pull all constants together, for REG+IMM addressing, include &GV in
603 // 'IMM' if the target supports it.
607 void LoopStrengthReduce::runOnLoop(Loop *L) {
608 // First step, transform all loops nesting inside of this loop.
609 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
612 // Next, find all uses of induction variables in this loop, and catagorize
613 // them by stride. Start by finding all of the PHI nodes in the header for
614 // this loop. If they are induction variables, inspect their uses.
615 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
616 AddUsersIfInteresting(I, L);
618 // If we have nothing to do, return.
619 //if (IVUsesByStride.empty()) return;
621 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
622 // doing computation in byte values, promote to 32-bit values if safe.
624 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
625 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
626 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
627 // to be careful that IV's are all the same type. Only works for intptr_t
630 // If we only have one stride, we can more aggressively eliminate some things.
631 bool HasOneStride = IVUsesByStride.size() == 1;
633 for (std::map<Value*, IVUse>::iterator SI = IVUsesByStride.begin(),
634 E = IVUsesByStride.end(); SI != E; ++SI)
635 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
637 // Clean up after ourselves
638 if (!DeadInsts.empty()) {
639 DeleteTriviallyDeadInstructions(DeadInsts);
641 BasicBlock::iterator I = L->getHeader()->begin();
643 while ((PN = dyn_cast<PHINode>(I))) {
644 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
646 // At this point, we know that we have killed one or more GEP instructions.
647 // It is worth checking to see if the cann indvar is also dead, so that we
648 // can remove it as well. The requirements for the cann indvar to be
649 // considered dead are:
650 // 1. the cann indvar has one use
651 // 2. the use is an add instruction
652 // 3. the add has one use
653 // 4. the add is used by the cann indvar
654 // If all four cases above are true, then we can remove both the add and
656 // FIXME: this needs to eliminate an induction variable even if it's being
657 // compared against some value to decide loop termination.
658 if (PN->hasOneUse()) {
659 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
660 if (BO && BO->hasOneUse()) {
661 if (PN == *(BO->use_begin())) {
662 DeadInsts.insert(BO);
663 // Break the cycle, then delete the PHI.
664 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
665 SE->deleteInstructionFromRecords(PN);
666 PN->eraseFromParent();
671 DeleteTriviallyDeadInstructions(DeadInsts);
674 IVUsesByStride.clear();
675 CastedBasePointers.clear();