Move all of the header files which are involved in modelling the LLVM IR
[oota-llvm.git] / lib / Transforms / Utils / LCSSA.cpp
1 //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass transforms loops by placing phi nodes at the end of the loops for
11 // all values that are live across the loop boundary.  For example, it turns
12 // the left into the right code:
13 // 
14 // for (...)                for (...)
15 //   if (c)                   if (c)
16 //     X1 = ...                 X1 = ...
17 //   else                     else
18 //     X2 = ...                 X2 = ...
19 //   X3 = phi(X1, X2)         X3 = phi(X1, X2)
20 // ... = X3 + 4             X4 = phi(X3)
21 //                          ... = X4 + 4
22 //
23 // This is still valid LLVM; the extra phi nodes are purely redundant, and will
24 // be trivially eliminated by InstCombine.  The major benefit of this 
25 // transformation is that it makes many other loop optimizations, such as 
26 // LoopUnswitching, simpler.
27 //
28 //===----------------------------------------------------------------------===//
29
30 #define DEBUG_TYPE "lcssa"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Analysis/Dominators.h"
35 #include "llvm/Analysis/LoopPass.h"
36 #include "llvm/Analysis/ScalarEvolution.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/PredIteratorCache.h"
42 #include "llvm/Transforms/Utils/SSAUpdater.h"
43 using namespace llvm;
44
45 STATISTIC(NumLCSSA, "Number of live out of a loop variables");
46
47 namespace {
48   struct LCSSA : public LoopPass {
49     static char ID; // Pass identification, replacement for typeid
50     LCSSA() : LoopPass(ID) {
51       initializeLCSSAPass(*PassRegistry::getPassRegistry());
52     }
53
54     // Cached analysis information for the current function.
55     DominatorTree *DT;
56     LoopInfo *LI;
57     ScalarEvolution *SE;
58     std::vector<BasicBlock*> LoopBlocks;
59     PredIteratorCache PredCache;
60     Loop *L;
61     
62     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
63
64     /// This transformation requires natural loop information & requires that
65     /// loop preheaders be inserted into the CFG.  It maintains both of these,
66     /// as well as the CFG.  It also requires dominator information.
67     ///
68     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69       AU.setPreservesCFG();
70
71       AU.addRequired<DominatorTree>();
72       AU.addRequired<LoopInfo>();
73       AU.addPreservedID(LoopSimplifyID);
74       AU.addPreserved<ScalarEvolution>();
75     }
76   private:
77     bool ProcessInstruction(Instruction *Inst,
78                             const SmallVectorImpl<BasicBlock*> &ExitBlocks);
79     
80     /// verifyAnalysis() - Verify loop nest.
81     virtual void verifyAnalysis() const {
82       // Check the special guarantees that LCSSA makes.
83       assert(L->isLCSSAForm(*DT) && "LCSSA form not preserved!");
84     }
85
86     /// inLoop - returns true if the given block is within the current loop
87     bool inLoop(BasicBlock *B) const {
88       return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
89     }
90   };
91 }
92   
93 char LCSSA::ID = 0;
94 INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
95 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
96 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
97 INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
98
99 Pass *llvm::createLCSSAPass() { return new LCSSA(); }
100 char &llvm::LCSSAID = LCSSA::ID;
101
102
103 /// BlockDominatesAnExit - Return true if the specified block dominates at least
104 /// one of the blocks in the specified list.
105 static bool BlockDominatesAnExit(BasicBlock *BB,
106                                  const SmallVectorImpl<BasicBlock*> &ExitBlocks,
107                                  DominatorTree *DT) {
108   DomTreeNode *DomNode = DT->getNode(BB);
109   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
110     if (DT->dominates(DomNode, DT->getNode(ExitBlocks[i])))
111       return true;
112
113   return false;
114 }
115
116
117 /// runOnFunction - Process all loops in the function, inner-most out.
118 bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {
119   L = TheLoop;
120   
121   DT = &getAnalysis<DominatorTree>();
122   LI = &getAnalysis<LoopInfo>();
123   SE = getAnalysisIfAvailable<ScalarEvolution>();
124
125   // Get the set of exiting blocks.
126   SmallVector<BasicBlock*, 8> ExitBlocks;
127   L->getExitBlocks(ExitBlocks);
128   
129   if (ExitBlocks.empty())
130     return false;
131   
132   // Speed up queries by creating a sorted vector of blocks.
133   LoopBlocks.clear();
134   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
135   array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());
136   
137   // Look at all the instructions in the loop, checking to see if they have uses
138   // outside the loop.  If so, rewrite those uses.
139   bool MadeChange = false;
140   
141   for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();
142        BBI != E; ++BBI) {
143     BasicBlock *BB = *BBI;
144     
145     // For large loops, avoid use-scanning by using dominance information:  In
146     // particular, if a block does not dominate any of the loop exits, then none
147     // of the values defined in the block could be used outside the loop.
148     if (!BlockDominatesAnExit(BB, ExitBlocks, DT))
149       continue;
150     
151     for (BasicBlock::iterator I = BB->begin(), E = BB->end();
152          I != E; ++I) {
153       // Reject two common cases fast: instructions with no uses (like stores)
154       // and instructions with one use that is in the same block as this.
155       if (I->use_empty() ||
156           (I->hasOneUse() && I->use_back()->getParent() == BB &&
157            !isa<PHINode>(I->use_back())))
158         continue;
159       
160       MadeChange |= ProcessInstruction(I, ExitBlocks);
161     }
162   }
163
164   // If we modified the code, remove any caches about the loop from SCEV to
165   // avoid dangling entries.
166   // FIXME: This is a big hammer, can we clear the cache more selectively?
167   if (SE && MadeChange)
168     SE->forgetLoop(L);
169   
170   assert(L->isLCSSAForm(*DT));
171   PredCache.clear();
172
173   return MadeChange;
174 }
175
176 /// isExitBlock - Return true if the specified block is in the list.
177 static bool isExitBlock(BasicBlock *BB,
178                         const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
179   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
180     if (ExitBlocks[i] == BB)
181       return true;
182   return false;
183 }
184
185 /// ProcessInstruction - Given an instruction in the loop, check to see if it
186 /// has any uses that are outside the current loop.  If so, insert LCSSA PHI
187 /// nodes and rewrite the uses.
188 bool LCSSA::ProcessInstruction(Instruction *Inst,
189                                const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
190   SmallVector<Use*, 16> UsesToRewrite;
191   
192   BasicBlock *InstBB = Inst->getParent();
193   
194   for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
195        UI != E; ++UI) {
196     User *U = *UI;
197     BasicBlock *UserBB = cast<Instruction>(U)->getParent();
198     if (PHINode *PN = dyn_cast<PHINode>(U))
199       UserBB = PN->getIncomingBlock(UI);
200     
201     if (InstBB != UserBB && !inLoop(UserBB))
202       UsesToRewrite.push_back(&UI.getUse());
203   }
204
205   // If there are no uses outside the loop, exit with no change.
206   if (UsesToRewrite.empty()) return false;
207   
208   ++NumLCSSA; // We are applying the transformation
209
210   // Invoke instructions are special in that their result value is not available
211   // along their unwind edge. The code below tests to see whether DomBB dominates
212   // the value, so adjust DomBB to the normal destination block, which is
213   // effectively where the value is first usable.
214   BasicBlock *DomBB = Inst->getParent();
215   if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))
216     DomBB = Inv->getNormalDest();
217
218   DomTreeNode *DomNode = DT->getNode(DomBB);
219
220   SmallVector<PHINode*, 16> AddedPHIs;
221
222   SSAUpdater SSAUpdate;
223   SSAUpdate.Initialize(Inst->getType(), Inst->getName());
224   
225   // Insert the LCSSA phi's into all of the exit blocks dominated by the
226   // value, and add them to the Phi's map.
227   for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),
228       BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {
229     BasicBlock *ExitBB = *BBI;
230     if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;
231     
232     // If we already inserted something for this BB, don't reprocess it.
233     if (SSAUpdate.HasValueForBlock(ExitBB)) continue;
234     
235     PHINode *PN = PHINode::Create(Inst->getType(),
236                                   PredCache.GetNumPreds(ExitBB),
237                                   Inst->getName()+".lcssa",
238                                   ExitBB->begin());
239
240     // Add inputs from inside the loop for this PHI.
241     for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
242       PN->addIncoming(Inst, *PI);
243
244       // If the exit block has a predecessor not within the loop, arrange for
245       // the incoming value use corresponding to that predecessor to be
246       // rewritten in terms of a different LCSSA PHI.
247       if (!inLoop(*PI))
248         UsesToRewrite.push_back(
249           &PN->getOperandUse(
250             PN->getOperandNumForIncomingValue(PN->getNumIncomingValues()-1)));
251     }
252
253     AddedPHIs.push_back(PN);
254     
255     // Remember that this phi makes the value alive in this block.
256     SSAUpdate.AddAvailableValue(ExitBB, PN);
257   }
258
259   // Rewrite all uses outside the loop in terms of the new PHIs we just
260   // inserted.
261   for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {
262     // If this use is in an exit block, rewrite to use the newly inserted PHI.
263     // This is required for correctness because SSAUpdate doesn't handle uses in
264     // the same block.  It assumes the PHI we inserted is at the end of the
265     // block.
266     Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());
267     BasicBlock *UserBB = User->getParent();
268     if (PHINode *PN = dyn_cast<PHINode>(User))
269       UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);
270
271     if (isa<PHINode>(UserBB->begin()) &&
272         isExitBlock(UserBB, ExitBlocks)) {
273       // Tell the VHs that the uses changed. This updates SCEV's caches.
274       if (UsesToRewrite[i]->get()->hasValueHandle())
275         ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i], UserBB->begin());
276       UsesToRewrite[i]->set(UserBB->begin());
277       continue;
278     }
279     
280     // Otherwise, do full PHI insertion.
281     SSAUpdate.RewriteUse(*UsesToRewrite[i]);
282   }
283
284   // Remove PHI nodes that did not have any uses rewritten.
285   for (unsigned i = 0, e = AddedPHIs.size(); i != e; ++i) {
286     if (AddedPHIs[i]->use_empty())
287       AddedPHIs[i]->eraseFromParent();
288   }
289   
290   return true;
291 }
292