1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
3 // This pass is a simple loop invariant code motion pass.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Transforms/Scalar.h"
8 #include "llvm/Transforms/Utils/Local.h"
9 #include "llvm/Analysis/LoopInfo.h"
10 #include "llvm/Analysis/AliasAnalysis.h"
11 #include "llvm/Analysis/Dominators.h"
12 #include "llvm/iOperators.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/Support/InstVisitor.h"
15 #include "Support/STLExtras.h"
16 #include "Support/Statistic.h"
17 #include "llvm/Assembly/Writer.h"
22 Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
23 Statistic<> NumHoistedLoads("licm", "Number of load insts hoisted");
25 struct LICM : public FunctionPass, public InstVisitor<LICM> {
26 virtual bool runOnFunction(Function &F);
28 /// This transformation requires natural loop information & requires that
29 /// loop preheaders be inserted into the CFG...
31 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
33 AU.addRequiredID(LoopPreheadersID);
34 AU.addRequired<LoopInfo>();
35 AU.addRequired<DominatorTree>();
36 AU.addRequired<AliasAnalysis>();
40 Loop *CurLoop; // The current loop we are working on...
41 BasicBlock *Preheader; // The preheader block of the current loop...
42 bool Changed; // Set to true when we change anything.
43 AliasAnalysis *AA; // Currently AliasAnalysis information
45 /// visitLoop - Hoist expressions out of the specified loop...
47 void visitLoop(Loop *L);
49 /// HoistRegion - Walk the specified region of the CFG (defined by all
50 /// blocks dominated by the specified block, and that are in the current
51 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
52 /// visit defintions before uses, allowing us to hoist a loop body in one
53 /// pass without iteration.
55 void HoistRegion(DominatorTree::Node *N);
57 /// inSubLoop - Little predicate that returns true if the specified basic
58 /// block is in a subloop of the current one, not the current one itself.
60 bool inSubLoop(BasicBlock *BB) {
61 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
62 for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
63 if (CurLoop->getSubLoops()[i]->contains(BB))
64 return true; // A subloop actually contains this block!
68 /// hoist - When an instruction is found to only use loop invariant operands
69 /// that is safe to hoist, this instruction is called to do the dirty work.
71 void hoist(Instruction &I);
73 /// pointerInvalidatedByLoop - Return true if the body of this loop may
74 /// store into the memory location pointed to by V.
76 bool pointerInvalidatedByLoop(Value *V);
78 /// isLoopInvariant - Return true if the specified value is loop invariant
80 inline bool isLoopInvariant(Value *V) {
81 if (Instruction *I = dyn_cast<Instruction>(V))
82 return !CurLoop->contains(I->getParent());
83 return true; // All non-instructions are loop invariant
86 /// Instruction visitation handlers... these basically control whether or
87 /// not the specified instruction types are hoisted.
89 friend class InstVisitor<LICM>;
90 void visitBinaryOperator(Instruction &I) {
91 if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
94 void visitCastInst(CastInst &CI) {
95 Instruction &I = (Instruction&)CI;
96 if (isLoopInvariant(I.getOperand(0))) hoist(I);
98 void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
100 void visitLoadInst(LoadInst &LI);
102 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
103 Instruction &I = (Instruction&)GEPI;
104 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
105 if (!isLoopInvariant(I.getOperand(i))) return;
110 RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
113 Pass *createLICMPass() { return new LICM(); }
115 /// runOnFunction - For LICM, this simply traverses the loop structure of the
116 /// function, hoisting expressions out of loops if possible.
118 bool LICM::runOnFunction(Function &) {
119 // Get information about the top level loops in the function...
120 const std::vector<Loop*> &TopLevelLoops =
121 getAnalysis<LoopInfo>().getTopLevelLoops();
123 // Get our alias analysis information...
124 AA = &getAnalysis<AliasAnalysis>();
126 // Traverse loops in postorder, hoisting expressions out of the deepest loops
130 std::for_each(TopLevelLoops.begin(), TopLevelLoops.end(),
131 bind_obj(this, &LICM::visitLoop));
136 /// visitLoop - Hoist expressions out of the specified loop...
138 void LICM::visitLoop(Loop *L) {
139 // Recurse through all subloops before we process this loop...
140 std::for_each(L->getSubLoops().begin(), L->getSubLoops().end(),
141 bind_obj(this, &LICM::visitLoop));
144 // Get the preheader block to move instructions into...
145 Preheader = L->getLoopPreheader();
146 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
148 // We want to visit all of the instructions in this loop... that are not parts
149 // of our subloops (they have already had their invariants hoisted out of
150 // their loop, into this loop, so there is no need to process the BODIES of
153 // Traverse the body of the loop in depth first order on the dominator tree so
154 // that we are guaranteed to see definitions before we see uses. This allows
155 // us to perform the LICM transformation in one pass, without iteration.
157 HoistRegion(getAnalysis<DominatorTree>()[L->getHeader()]);
159 // Clear out loops state information for the next iteration
164 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
165 /// dominated by the specified block, and that are in the current loop) in depth
166 /// first order w.r.t the DominatorTree. This allows us to visit defintions
167 /// before uses, allowing us to hoist a loop body in one pass without iteration.
169 void LICM::HoistRegion(DominatorTree::Node *N) {
170 assert(N != 0 && "Null dominator tree node?");
172 // If this subregion is not in the top level loop at all, exit.
173 if (!CurLoop->contains(N->getNode())) return;
175 // Only need to hoist the contents of this block if it is not part of a
176 // subloop (which would already have been hoisted)
177 if (!inSubLoop(N->getNode()))
178 visit(*N->getNode());
180 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
181 for (unsigned i = 0, e = Children.size(); i != e; ++i)
182 HoistRegion(Children[i]);
186 /// hoist - When an instruction is found to only use loop invariant operands
187 /// that is safe to hoist, this instruction is called to do the dirty work.
189 void LICM::hoist(Instruction &Inst) {
190 DEBUG(std::cerr << "LICM hoisting to";
191 WriteAsOperand(std::cerr, Preheader, false);
192 std::cerr << ": " << Inst);
194 // Remove the instruction from its current basic block... but don't delete the
196 Inst.getParent()->getInstList().remove(&Inst);
198 // Insert the new node in Preheader, before the terminator.
199 Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
206 void LICM::visitLoadInst(LoadInst &LI) {
207 if (isLoopInvariant(LI.getOperand(0)) &&
208 !pointerInvalidatedByLoop(LI.getOperand(0))) {
214 /// pointerInvalidatedByLoop - Return true if the body of this loop may store
215 /// into the memory location pointed to by V.
217 bool LICM::pointerInvalidatedByLoop(Value *V) {
218 // Check to see if any of the basic blocks in CurLoop invalidate V.
219 for (unsigned i = 0, e = CurLoop->getBlocks().size(); i != e; ++i)
220 if (AA->canBasicBlockModify(*CurLoop->getBlocks()[i], V))