1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
3 // InductionVariableSimplify - Transform induction variables in a program
4 // to all use a single cannonical induction variable per loop.
6 //===----------------------------------------------------------------------===//
8 #include "llvm/Transforms/Scalar.h"
9 #include "llvm/Analysis/InductionVariable.h"
10 #include "llvm/Analysis/LoopInfo.h"
11 #include "llvm/iPHINode.h"
12 #include "llvm/iOther.h"
13 #include "llvm/Type.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Support/CFG.h"
16 #include "Support/STLExtras.h"
17 #include "Support/Statistic.h"
20 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
21 Statistic<> NumInserted("indvars", "Number of cannonical indvars added");
24 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
27 static Instruction *InsertCast(Value *Val, const Type *Ty,
28 Instruction *InsertBefore) {
29 return new CastInst(Val, Ty, Val->getName()+"-casted", InsertBefore);
32 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
33 // Transform all subloops before this loop...
34 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
35 Loop->getSubLoops().end(),
36 std::bind1st(std::ptr_fun(TransformLoop), Loops));
37 // Get the header node for this loop. All of the phi nodes that could be
38 // induction variables must live in this basic block.
40 BasicBlock *Header = Loop->getBlocks().front();
42 // Loop over all of the PHI nodes in the basic block, calculating the
43 // induction variables that they represent... stuffing the induction variable
44 // info into a vector...
46 std::vector<InductionVariable> IndVars; // Induction variables for block
47 BasicBlock::iterator AfterPHIIt = Header->begin();
48 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
49 IndVars.push_back(InductionVariable(PN, Loops));
50 // AfterPHIIt now points to first nonphi instruction...
52 // If there are no phi nodes in this basic block, there can't be indvars...
53 if (IndVars.empty()) return Changed;
55 // Loop over the induction variables, looking for a cannonical induction
56 // variable, and checking to make sure they are not all unknown induction
59 bool FoundIndVars = false;
60 InductionVariable *Cannonical = 0;
61 for (unsigned i = 0; i < IndVars.size(); ++i) {
62 if (IndVars[i].InductionType == InductionVariable::Cannonical &&
63 !isa<PointerType>(IndVars[i].Phi->getType()))
64 Cannonical = &IndVars[i];
65 if (IndVars[i].InductionType != InductionVariable::Unknown)
69 // No induction variables, bail early... don't add a cannonnical indvar
70 if (!FoundIndVars) return Changed;
72 // Okay, we want to convert other induction variables to use a cannonical
73 // indvar. If we don't have one, add one now...
75 // Create the PHI node for the new induction variable, and insert the phi
76 // node at the end of the other phi nodes...
77 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", AfterPHIIt);
79 // Create the increment instruction to add one to the counter...
80 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
81 ConstantUInt::get(Type::UIntTy,1),
82 "add1-indvar", AfterPHIIt);
84 // Figure out which block is incoming and which is the backedge for the loop
85 BasicBlock *Incoming, *BackEdgeBlock;
86 pred_iterator PI = pred_begin(Header);
87 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
88 if (Loop->contains(*PI)) { // First pred is back edge...
89 BackEdgeBlock = *PI++;
93 BackEdgeBlock = *PI++;
95 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
97 // Add incoming values for the PHI node...
98 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
99 PN->addIncoming(Add, BackEdgeBlock);
101 // Analyze the new induction variable...
102 IndVars.push_back(InductionVariable(PN, Loops));
103 assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
104 "Just inserted cannonical indvar that is not cannonical!");
105 Cannonical = &IndVars.back();
110 DEBUG(std::cerr << "Induction variables:\n");
112 // Get the current loop iteration count, which is always the value of the
113 // cannonical phi node...
115 PHINode *IterCount = Cannonical->Phi;
117 // Loop through and replace all of the auxillary induction variables with
118 // references to the primary induction variable...
120 for (unsigned i = 0; i < IndVars.size(); ++i) {
121 InductionVariable *IV = &IndVars[i];
123 DEBUG(IV->print(std::cerr));
125 // Don't do math with pointers...
126 const Type *IVTy = IV->Phi->getType();
127 if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy;
129 // Don't modify the cannonical indvar or unrecognized indvars...
130 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
131 Instruction *Val = IterCount;
132 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
133 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
135 // If the types are not compatible, insert a cast now...
136 if (Val->getType() != IVTy)
137 Val = InsertCast(Val, IVTy, AfterPHIIt);
138 if (IV->Step->getType() != IVTy)
139 IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt);
141 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
142 IV->Phi->getName()+"-scale", AfterPHIIt);
146 if (IV->Start != Constant::getNullValue(IV->Start->getType())) {
147 // If the types are not compatible, insert a cast now...
148 if (Val->getType() != IVTy)
149 Val = InsertCast(Val, IVTy, AfterPHIIt);
150 if (IV->Start->getType() != IVTy)
151 IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt);
153 // Insert the instruction after the phi nodes...
154 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
155 IV->Phi->getName()+"-offset", AfterPHIIt);
158 // If the PHI node has a different type than val is, insert a cast now...
159 if (Val->getType() != IV->Phi->getType())
160 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
162 // Replace all uses of the old PHI node with the new computed value...
163 IV->Phi->replaceAllUsesWith(Val);
165 // Move the PHI name to it's new equivalent value...
166 std::string OldName = IV->Phi->getName();
167 IV->Phi->setName("");
168 Val->setName(OldName);
170 // Delete the old, now unused, phi node...
171 Header->getInstList().erase(IV->Phi);
181 struct InductionVariableSimplify : public FunctionPass {
182 virtual bool runOnFunction(Function &) {
183 LoopInfo &LI = getAnalysis<LoopInfo>();
185 // Induction Variables live in the header nodes of loops
186 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
187 LI.getTopLevelLoops().end(),
188 std::bind1st(std::ptr_fun(TransformLoop), &LI));
191 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
192 AU.addRequired<LoopInfo>();
193 AU.setPreservesCFG();
196 RegisterOpt<InductionVariableSimplify> X("indvars",
197 "Cannonicalize Induction Variables");
200 Pass *createIndVarSimplifyPass() {
201 return new InductionVariableSimplify();