1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
3 // Guarantees that all loops with identifiable, linear, induction variables will
4 // be transformed to have a single, canonical, induction variable. After this
5 // pass runs, it guarantees the the first PHI node of the header block in the
6 // loop is the canonical induction variable if there is one.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Transforms/Scalar.h"
11 #include "llvm/Analysis/InductionVariable.h"
12 #include "llvm/Analysis/LoopInfo.h"
13 #include "llvm/iPHINode.h"
14 #include "llvm/iOther.h"
15 #include "llvm/Type.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Support/CFG.h"
18 #include "Support/Debug.h"
19 #include "Support/Statistic.h"
20 #include "Support/STLExtras.h"
23 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
24 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
27 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
30 static Instruction *InsertCast(Value *Val, const Type *Ty,
31 Instruction *InsertBefore) {
32 return new CastInst(Val, Ty, Val->getName()+"-casted", InsertBefore);
35 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
36 // Transform all subloops before this loop...
37 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
38 Loop->getSubLoops().end(),
39 std::bind1st(std::ptr_fun(TransformLoop), Loops));
40 // Get the header node for this loop. All of the phi nodes that could be
41 // induction variables must live in this basic block.
43 BasicBlock *Header = Loop->getHeader();
45 // Loop over all of the PHI nodes in the basic block, calculating the
46 // induction variables that they represent... stuffing the induction variable
47 // info into a vector...
49 std::vector<InductionVariable> IndVars; // Induction variables for block
50 BasicBlock::iterator AfterPHIIt = Header->begin();
51 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
52 IndVars.push_back(InductionVariable(PN, Loops));
53 // AfterPHIIt now points to first nonphi instruction...
55 // If there are no phi nodes in this basic block, there can't be indvars...
56 if (IndVars.empty()) return Changed;
58 // Loop over the induction variables, looking for a canonical induction
59 // variable, and checking to make sure they are not all unknown induction
62 bool FoundIndVars = false;
63 InductionVariable *Canonical = 0;
64 for (unsigned i = 0; i < IndVars.size(); ++i) {
65 if (IndVars[i].InductionType == InductionVariable::Canonical &&
66 !isa<PointerType>(IndVars[i].Phi->getType()))
67 Canonical = &IndVars[i];
68 if (IndVars[i].InductionType != InductionVariable::Unknown)
72 // No induction variables, bail early... don't add a canonical indvar
73 if (!FoundIndVars) return Changed;
75 // Okay, we want to convert other induction variables to use a canonical
76 // indvar. If we don't have one, add one now...
78 // Create the PHI node for the new induction variable, and insert the phi
79 // node at the end of the other phi nodes...
80 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", AfterPHIIt);
82 // Create the increment instruction to add one to the counter...
83 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
84 ConstantUInt::get(Type::UIntTy,1),
85 "add1-indvar", AfterPHIIt);
87 // Figure out which block is incoming and which is the backedge for the loop
88 BasicBlock *Incoming, *BackEdgeBlock;
89 pred_iterator PI = pred_begin(Header);
90 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
91 if (Loop->contains(*PI)) { // First pred is back edge...
92 BackEdgeBlock = *PI++;
96 BackEdgeBlock = *PI++;
98 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
100 // Add incoming values for the PHI node...
101 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
102 PN->addIncoming(Add, BackEdgeBlock);
104 // Analyze the new induction variable...
105 IndVars.push_back(InductionVariable(PN, Loops));
106 assert(IndVars.back().InductionType == InductionVariable::Canonical &&
107 "Just inserted canonical indvar that is not canonical!");
108 Canonical = &IndVars.back();
113 DEBUG(std::cerr << "Induction variables:\n");
115 // Get the current loop iteration count, which is always the value of the
116 // canonical phi node...
118 PHINode *IterCount = Canonical->Phi;
120 // Loop through and replace all of the auxiliary induction variables with
121 // references to the canonical induction variable...
123 for (unsigned i = 0; i < IndVars.size(); ++i) {
124 InductionVariable *IV = &IndVars[i];
126 DEBUG(IV->print(std::cerr));
128 // Don't do math with pointers...
129 const Type *IVTy = IV->Phi->getType();
130 if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy;
132 // Don't modify the canonical indvar or unrecognized indvars...
133 if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) {
134 Instruction *Val = IterCount;
135 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
136 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
138 // If the types are not compatible, insert a cast now...
139 if (Val->getType() != IVTy)
140 Val = InsertCast(Val, IVTy, AfterPHIIt);
141 if (IV->Step->getType() != IVTy)
142 IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt);
144 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
145 IV->Phi->getName()+"-scale", AfterPHIIt);
149 if (IV->Start != Constant::getNullValue(IV->Start->getType())) {
150 // If the types are not compatible, insert a cast now...
151 if (Val->getType() != IVTy)
152 Val = InsertCast(Val, IVTy, AfterPHIIt);
153 if (IV->Start->getType() != IVTy)
154 IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt);
156 // Insert the instruction after the phi nodes...
157 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
158 IV->Phi->getName()+"-offset", AfterPHIIt);
161 // If the PHI node has a different type than val is, insert a cast now...
162 if (Val->getType() != IV->Phi->getType())
163 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
165 // Replace all uses of the old PHI node with the new computed value...
166 IV->Phi->replaceAllUsesWith(Val);
168 // Move the PHI name to it's new equivalent value...
169 std::string OldName = IV->Phi->getName();
170 IV->Phi->setName("");
171 Val->setName(OldName);
173 // Delete the old, now unused, phi node...
174 Header->getInstList().erase(IV->Phi);
184 struct InductionVariableSimplify : public FunctionPass {
185 virtual bool runOnFunction(Function &) {
186 LoopInfo &LI = getAnalysis<LoopInfo>();
188 // Induction Variables live in the header nodes of loops
189 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
190 LI.getTopLevelLoops().end(),
191 std::bind1st(std::ptr_fun(TransformLoop), &LI));
194 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
195 AU.addRequired<LoopInfo>();
196 AU.setPreservesCFG();
199 RegisterOpt<InductionVariableSimplify> X("indvars",
200 "Canonicalize Induction Variables");
203 Pass *createIndVarSimplifyPass() {
204 return new InductionVariableSimplify();