blob: 3714d7b08f4b4b1a7fdd7ed489cb6b0cdb724657 [file] [log] [blame]
Chris Lattner6ec05f52002-05-10 22:44:58 +00001//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2//
3// This pass is a simple loop invariant code motion pass.
4//
5// Note that this pass does NOT require pre-headers to exist on loops in the
6// CFG, but if there is not distinct preheader for a loop, the hoisted code will
7// be *DUPLICATED* in every basic block, outside of the loop, that preceeds the
8// loop header. Additionally, any use of one of these hoisted expressions
9// cannot be loop invariant itself, because the expression hoisted gets a PHI
10// node that is loop variant.
11//
12// For these reasons, and many more, it makes sense to run a pass before this
13// that ensures that there are preheaders on all loops. That said, we don't
14// REQUIRE it. :)
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Transforms/Scalar.h"
19#include "llvm/Transforms/Utils/Local.h"
20#include "llvm/Analysis/LoopInfo.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000021#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000022#include "llvm/iOperators.h"
23#include "llvm/iPHINode.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000024#include "llvm/iMemory.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000025#include "llvm/Support/InstVisitor.h"
26#include "llvm/Support/CFG.h"
27#include "Support/STLExtras.h"
28#include "Support/StatisticReporter.h"
29#include <algorithm>
Anand Shukla2bc64192002-06-25 21:07:58 +000030using std::string;
Chris Lattner6ec05f52002-05-10 22:44:58 +000031
32static Statistic<> NumHoistedNPH("licm\t\t- Number of insts hoisted to multiple"
33 " loop preds (bad, no loop pre-header)");
34static Statistic<> NumHoistedPH("licm\t\t- Number of insts hoisted to a loop "
35 "pre-header");
Chris Lattnera51fa882002-08-22 21:39:55 +000036static Statistic<> NumHoistedLoads("licm\t\t- Number of load insts hoisted");
Chris Lattner6ec05f52002-05-10 22:44:58 +000037
38namespace {
39 struct LICM : public FunctionPass, public InstVisitor<LICM> {
Chris Lattner113f4f42002-06-25 16:13:24 +000040 virtual bool runOnFunction(Function &F);
Chris Lattner6ec05f52002-05-10 22:44:58 +000041
42 // This transformation requires natural loop information...
43 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
44 AU.preservesCFG();
Chris Lattnerf0ed55d2002-08-08 19:01:30 +000045 AU.addRequired<LoopInfo>();
Chris Lattnera51fa882002-08-22 21:39:55 +000046 AU.addRequired<AliasAnalysis>();
Chris Lattner6ec05f52002-05-10 22:44:58 +000047 }
48
49 private:
50 // List of predecessor blocks for the current loop - These blocks are where
51 // we hoist loop invariants to for the current loop.
52 //
53 std::vector<BasicBlock*> LoopPreds, LoopBackEdges;
54
Chris Lattnera51fa882002-08-22 21:39:55 +000055 Loop *CurLoop; // The current loop we are working on...
56 bool Changed; // Set to true when we change anything.
57 AliasAnalysis *AA; // Currently AliasAnalysis information
Chris Lattner6ec05f52002-05-10 22:44:58 +000058
59 // visitLoop - Hoist expressions out of the specified loop...
60 void visitLoop(Loop *L);
61
62 // notInCurrentLoop - Little predicate that returns true if the specified
63 // basic block is in a subloop of the current one, not the current one
64 // itself.
65 //
66 bool notInCurrentLoop(BasicBlock *BB) {
67 for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
68 if (CurLoop->getSubLoops()[i]->contains(BB))
69 return true; // A subloop actually contains this block!
70 return false;
71 }
72
73 // hoist - When an instruction is found to only use loop invariant operands
74 // that is safe to hoist, this instruction is called to do the dirty work.
75 //
Chris Lattner113f4f42002-06-25 16:13:24 +000076 void hoist(Instruction &I);
Chris Lattner6ec05f52002-05-10 22:44:58 +000077
Chris Lattnera51fa882002-08-22 21:39:55 +000078 // pointerInvalidatedByLoop - Return true if the body of this loop may store
79 // into the memory location pointed to by V.
80 //
81 bool pointerInvalidatedByLoop(Value *V);
82
Chris Lattner6ec05f52002-05-10 22:44:58 +000083 // isLoopInvariant - Return true if the specified value is loop invariant
84 inline bool isLoopInvariant(Value *V) {
85 if (Instruction *I = dyn_cast<Instruction>(V))
86 return !CurLoop->contains(I->getParent());
87 return true; // All non-instructions are loop invariant
88 }
89
90 // visitBasicBlock - Run LICM on a particular block.
91 void visitBasicBlock(BasicBlock *BB);
92
93 // Instruction visitation handlers... these basically control whether or not
94 // the specified instruction types are hoisted.
95 //
96 friend class InstVisitor<LICM>;
Chris Lattner113f4f42002-06-25 16:13:24 +000097 void visitBinaryOperator(Instruction &I) {
98 if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
Chris Lattner6ec05f52002-05-10 22:44:58 +000099 hoist(I);
100 }
Chris Lattnerb80b69c2002-08-14 18:22:19 +0000101 void visitCastInst(CastInst &CI) {
102 Instruction &I = (Instruction&)CI;
103 if (isLoopInvariant(I.getOperand(0))) hoist(I);
Chris Lattnerb193ff82002-08-14 18:18:02 +0000104 }
Chris Lattner113f4f42002-06-25 16:13:24 +0000105 void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000106
Chris Lattnera51fa882002-08-22 21:39:55 +0000107 void visitLoadInst(LoadInst &LI) {
108 assert(!LI.hasIndices());
109 if (isLoopInvariant(LI.getOperand(0)) &&
110 !pointerInvalidatedByLoop(LI.getOperand(0)))
111 hoist(LI);
112 }
113
Chris Lattner113f4f42002-06-25 16:13:24 +0000114 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
115 Instruction &I = (Instruction&)GEPI;
116 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
117 if (!isLoopInvariant(I.getOperand(i))) return;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000118 hoist(I);
119 }
120 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000121
Chris Lattnerc8b70922002-07-26 21:12:46 +0000122 RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
Chris Lattner6ec05f52002-05-10 22:44:58 +0000123}
124
125Pass *createLICMPass() { return new LICM(); }
126
Chris Lattner113f4f42002-06-25 16:13:24 +0000127bool LICM::runOnFunction(Function &) {
Chris Lattner6ec05f52002-05-10 22:44:58 +0000128 // get our loop information...
129 const std::vector<Loop*> &TopLevelLoops =
130 getAnalysis<LoopInfo>().getTopLevelLoops();
131
Chris Lattnera51fa882002-08-22 21:39:55 +0000132 // Get our alias analysis information...
133 AA = &getAnalysis<AliasAnalysis>();
134
Chris Lattner6ec05f52002-05-10 22:44:58 +0000135 // Traverse loops in postorder, hoisting expressions out of the deepest loops
136 // first.
137 //
138 Changed = false;
139 std::for_each(TopLevelLoops.begin(), TopLevelLoops.end(),
140 bind_obj(this, &LICM::visitLoop));
141 return Changed;
142}
143
144void LICM::visitLoop(Loop *L) {
145 // Recurse through all subloops before we process this loop...
146 std::for_each(L->getSubLoops().begin(), L->getSubLoops().end(),
147 bind_obj(this, &LICM::visitLoop));
148 CurLoop = L;
149
150 // Calculate the set of predecessors for this loop. The predecessors for this
151 // loop are equal to the predecessors for the header node of the loop that are
152 // not themselves in the loop.
153 //
154 BasicBlock *Header = L->getHeader();
155
156 // Calculate the sets of predecessors and backedges of the loop...
157 LoopBackEdges.insert(LoopBackEdges.end(),pred_begin(Header),pred_end(Header));
158
159 std::vector<BasicBlock*>::iterator LPI =
160 std::partition(LoopBackEdges.begin(), LoopBackEdges.end(),
161 bind_obj(CurLoop, &Loop::contains));
162
163 // Move all predecessors to the LoopPreds vector...
164 LoopPreds.insert(LoopPreds.end(), LPI, LoopBackEdges.end());
165
166 // Remove predecessors from backedges list...
167 LoopBackEdges.erase(LPI, LoopBackEdges.end());
168
169
170 // The only way that there could be no predecessors to a loop is if the loop
171 // is not reachable. Since we don't care about optimizing dead loops,
172 // summarily ignore them.
173 //
174 if (LoopPreds.empty()) return;
175
176 // We want to visit all of the instructions in this loop... that are not parts
177 // of our subloops (they have already had their invariants hoisted out of
178 // their loop, into this loop, so there is no need to process the BODIES of
179 // the subloops).
180 //
181 std::vector<BasicBlock*> BBs(L->getBlocks().begin(), L->getBlocks().end());
182
183 // Remove blocks that are actually in subloops...
184 BBs.erase(std::remove_if(BBs.begin(), BBs.end(),
185 bind_obj(this, &LICM::notInCurrentLoop)), BBs.end());
186
187 // Visit all of the basic blocks we have chosen, hoisting out the instructions
188 // as neccesary. This leaves dead copies of the instruction in the loop
189 // unfortunately...
190 //
191 for_each(BBs.begin(), BBs.end(), bind_obj(this, &LICM::visitBasicBlock));
192
193 // Clear out loops state information for the next iteration
194 CurLoop = 0;
195 LoopPreds.clear();
196 LoopBackEdges.clear();
197}
198
199void LICM::visitBasicBlock(BasicBlock *BB) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000200 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
201 visit(*I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000202
Chris Lattner113f4f42002-06-25 16:13:24 +0000203 if (dceInstruction(I))
Chris Lattner6ec05f52002-05-10 22:44:58 +0000204 Changed = true;
205 else
Chris Lattner113f4f42002-06-25 16:13:24 +0000206 ++I;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000207 }
208}
209
210
Chris Lattner113f4f42002-06-25 16:13:24 +0000211void LICM::hoist(Instruction &Inst) {
212 if (Inst.use_empty()) return; // Don't (re) hoist dead instructions!
Chris Lattner6ec05f52002-05-10 22:44:58 +0000213 //cerr << "Hoisting " << Inst;
214
215 BasicBlock *Header = CurLoop->getHeader();
216
217 // Old instruction will be removed, so take it's name...
Chris Lattner113f4f42002-06-25 16:13:24 +0000218 string InstName = Inst.getName();
219 Inst.setName("");
Chris Lattner6ec05f52002-05-10 22:44:58 +0000220
Chris Lattnera51fa882002-08-22 21:39:55 +0000221 if (isa<LoadInst>(Inst))
222 ++NumHoistedLoads;
223
Chris Lattner6ec05f52002-05-10 22:44:58 +0000224 // The common case is that we have a pre-header. Generate special case code
225 // that is faster if that is the case.
226 //
227 if (LoopPreds.size() == 1) {
228 BasicBlock *Pred = LoopPreds[0];
229
230 // Create a new copy of the instruction, for insertion into Pred.
Chris Lattner113f4f42002-06-25 16:13:24 +0000231 Instruction *New = Inst.clone();
Chris Lattner6ec05f52002-05-10 22:44:58 +0000232 New->setName(InstName);
233
234 // Insert the new node in Pred, before the terminator.
Chris Lattner113f4f42002-06-25 16:13:24 +0000235 Pred->getInstList().insert(--Pred->end(), New);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000236
Chris Lattner113f4f42002-06-25 16:13:24 +0000237 // Kill the old instruction...
238 Inst.replaceAllUsesWith(New);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000239 ++NumHoistedPH;
240
241 } else {
242 // No loop pre-header, insert a PHI node into header to capture all of the
243 // incoming versions of the value.
244 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000245 PHINode *LoopVal = new PHINode(Inst.getType(), InstName+".phi");
Chris Lattner6ec05f52002-05-10 22:44:58 +0000246
247 // Insert the new PHI node into the loop header...
248 Header->getInstList().push_front(LoopVal);
249
250 // Insert cloned versions of the instruction into all of the loop preds.
251 for (unsigned i = 0, e = LoopPreds.size(); i != e; ++i) {
252 BasicBlock *Pred = LoopPreds[i];
253
254 // Create a new copy of the instruction, for insertion into Pred.
Chris Lattner113f4f42002-06-25 16:13:24 +0000255 Instruction *New = Inst.clone();
Chris Lattner6ec05f52002-05-10 22:44:58 +0000256 New->setName(InstName);
257
258 // Insert the new node in Pred, before the terminator.
Chris Lattner113f4f42002-06-25 16:13:24 +0000259 Pred->getInstList().insert(--Pred->end(), New);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000260
261 // Add the incoming value to the PHI node.
262 LoopVal->addIncoming(New, Pred);
263 }
264
265 // Add incoming values to the PHI node for all backedges in the loop...
266 for (unsigned i = 0, e = LoopBackEdges.size(); i != e; ++i)
267 LoopVal->addIncoming(LoopVal, LoopBackEdges[i]);
268
269 // Replace all uses of the old version of the instruction in the loop with
270 // the new version that is out of the loop. We know that this is ok,
271 // because the new definition is in the loop header, which dominates the
272 // entire loop body. The old definition was defined _inside_ of the loop,
273 // so the scope cannot extend outside of the loop, so we're ok.
274 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000275 Inst.replaceAllUsesWith(LoopVal);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000276 ++NumHoistedNPH;
277 }
278
279 Changed = true;
280}
281
Chris Lattnera51fa882002-08-22 21:39:55 +0000282// pointerInvalidatedByLoop - Return true if the body of this loop may store
283// into the memory location pointed to by V.
284//
285bool LICM::pointerInvalidatedByLoop(Value *V) {
286 // Check to see if any of the basic blocks in CurLoop invalidate V.
287 for (unsigned i = 0, e = CurLoop->getBlocks().size(); i != e; ++i)
288 if (AA->canBasicBlockModify(*CurLoop->getBlocks()[i], V))
289 return true;
290 return false;
291}