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/iOperators.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/Support/InstVisitor.h"
14 #include "Support/STLExtras.h"
15 #include "Support/StatisticReporter.h"
20 Statistic<>NumHoisted("licm\t\t- Number of instructions hoisted out of loop");
21 Statistic<> NumHoistedLoads("licm\t\t- Number of load insts hoisted");
23 struct LICM : public FunctionPass, public InstVisitor<LICM> {
24 virtual bool runOnFunction(Function &F);
26 /// This transformation requires natural loop information & requires that
27 /// loop preheaders be inserted into the CFG...
29 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
31 AU.addRequiredID(LoopPreheadersID);
32 AU.addRequired<LoopInfo>();
33 AU.addRequired<AliasAnalysis>();
37 Loop *CurLoop; // The current loop we are working on...
38 BasicBlock *Preheader; // The preheader block of the current loop...
39 bool Changed; // Set to true when we change anything.
40 AliasAnalysis *AA; // Currently AliasAnalysis information
42 /// visitLoop - Hoist expressions out of the specified loop...
44 void visitLoop(Loop *L);
46 /// inCurrentLoop - Little predicate that returns false if the specified
47 /// basic block is in a subloop of the current one, not the current one
50 bool inCurrentLoop(BasicBlock *BB) {
51 for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
52 if (CurLoop->getSubLoops()[i]->contains(BB))
53 return false; // A subloop actually contains this block!
57 /// hoist - When an instruction is found to only use loop invariant operands
58 /// that is safe to hoist, this instruction is called to do the dirty work.
60 void hoist(Instruction &I);
62 /// pointerInvalidatedByLoop - Return true if the body of this loop may
63 /// store into the memory location pointed to by V.
65 bool pointerInvalidatedByLoop(Value *V);
67 /// isLoopInvariant - Return true if the specified value is loop invariant
69 inline bool isLoopInvariant(Value *V) {
70 if (Instruction *I = dyn_cast<Instruction>(V))
71 return !CurLoop->contains(I->getParent());
72 return true; // All non-instructions are loop invariant
75 /// Instruction visitation handlers... these basically control whether or
76 /// not the specified instruction types are hoisted.
78 friend class InstVisitor<LICM>;
79 void visitBinaryOperator(Instruction &I) {
80 if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
83 void visitCastInst(CastInst &CI) {
84 Instruction &I = (Instruction&)CI;
85 if (isLoopInvariant(I.getOperand(0))) hoist(I);
87 void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
89 void visitLoadInst(LoadInst &LI);
91 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
92 Instruction &I = (Instruction&)GEPI;
93 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
94 if (!isLoopInvariant(I.getOperand(i))) return;
99 RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
102 Pass *createLICMPass() { return new LICM(); }
104 /// runOnFunction - For LICM, this simply traverses the loop structure of the
105 /// function, hoisting expressions out of loops if possible.
107 bool LICM::runOnFunction(Function &) {
108 // Get information about the top level loops in the function...
109 const std::vector<Loop*> &TopLevelLoops =
110 getAnalysis<LoopInfo>().getTopLevelLoops();
112 // Get our alias analysis information...
113 AA = &getAnalysis<AliasAnalysis>();
115 // Traverse loops in postorder, hoisting expressions out of the deepest loops
119 std::for_each(TopLevelLoops.begin(), TopLevelLoops.end(),
120 bind_obj(this, &LICM::visitLoop));
125 /// visitLoop - Hoist expressions out of the specified loop...
127 void LICM::visitLoop(Loop *L) {
128 // Recurse through all subloops before we process this loop...
129 std::for_each(L->getSubLoops().begin(), L->getSubLoops().end(),
130 bind_obj(this, &LICM::visitLoop));
133 // Get the preheader block to move instructions into...
134 Preheader = L->getLoopPreheader();
135 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
137 // We want to visit all of the instructions in this loop... that are not parts
138 // of our subloops (they have already had their invariants hoisted out of
139 // their loop, into this loop, so there is no need to process the BODIES of
142 for (std::vector<BasicBlock*>::const_iterator
143 I = L->getBlocks().begin(), E = L->getBlocks().end(); I != E; ++I)
144 if (inCurrentLoop(*I))
147 // Clear out loops state information for the next iteration
152 /// hoist - When an instruction is found to only use loop invariant operands
153 /// that is safe to hoist, this instruction is called to do the dirty work.
155 void LICM::hoist(Instruction &Inst) {
156 if (Inst.use_empty()) return; // Don't (re) hoist dead instructions!
157 //cerr << "Hoisting " << Inst;
159 BasicBlock *Header = CurLoop->getHeader();
161 // Remove the instruction from its current basic block... but don't delete the
163 Inst.getParent()->getInstList().remove(&Inst);
165 // Insert the new node in Preheader, before the terminator.
166 Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
173 void LICM::visitLoadInst(LoadInst &LI) {
174 if (isLoopInvariant(LI.getOperand(0)) &&
175 !pointerInvalidatedByLoop(LI.getOperand(0))) {
181 /// pointerInvalidatedByLoop - Return true if the body of this loop may store
182 /// into the memory location pointed to by V.
184 bool LICM::pointerInvalidatedByLoop(Value *V) {
185 // Check to see if any of the basic blocks in CurLoop invalidate V.
186 for (unsigned i = 0, e = CurLoop->getBlocks().size(); i != e; ++i)
187 if (AA->canBasicBlockModify(*CurLoop->getBlocks()[i], V))