1 //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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:
14 // for (...) for (...)
19 // X3 = phi(X1, X2) X3 = phi(X1, X2)
20 // ... = X3 + 4 X4 = phi(X3)
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.
28 //===----------------------------------------------------------------------===//
30 #define DEBUG_TYPE "lcssa"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Constants.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Function.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/Analysis/Dominators.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Analysis/ScalarEvolution.h"
39 #include "llvm/Transforms/Utils/SSAUpdater.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/Support/PredIteratorCache.h"
45 STATISTIC(NumLCSSA, "Number of live out of a loop variables");
48 struct LCSSA : public LoopPass {
49 static char ID; // Pass identification, replacement for typeid
50 LCSSA() : LoopPass(ID) {
51 initializeLCSSAPass(*PassRegistry::getPassRegistry());
54 // Cached analysis information for the current function.
58 std::vector<BasicBlock*> LoopBlocks;
59 PredIteratorCache PredCache;
62 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
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.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequired<DominatorTree>();
72 AU.addRequired<LoopInfo>();
73 AU.addPreservedID(LoopSimplifyID);
74 AU.addPreserved<ScalarEvolution>();
77 bool ProcessInstruction(Instruction *Inst,
78 const SmallVectorImpl<BasicBlock*> &ExitBlocks);
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!");
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);
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)
99 Pass *llvm::createLCSSAPass() { return new LCSSA(); }
100 char &llvm::LCSSAID = LCSSA::ID;
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,
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])))
117 /// runOnFunction - Process all loops in the function, inner-most out.
118 bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {
121 DT = &getAnalysis<DominatorTree>();
122 LI = &getAnalysis<LoopInfo>();
123 SE = getAnalysisIfAvailable<ScalarEvolution>();
125 // Get the set of exiting blocks.
126 SmallVector<BasicBlock*, 8> ExitBlocks;
127 L->getExitBlocks(ExitBlocks);
129 if (ExitBlocks.empty())
132 // Speed up queries by creating a sorted vector of blocks.
134 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
135 array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());
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;
141 for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();
143 BasicBlock *BB = *BBI;
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))
151 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
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())))
160 MadeChange |= ProcessInstruction(I, ExitBlocks);
164 assert(L->isLCSSAForm(*DT));
170 /// isExitBlock - Return true if the specified block is in the list.
171 static bool isExitBlock(BasicBlock *BB,
172 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
173 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
174 if (ExitBlocks[i] == BB)
179 /// ProcessInstruction - Given an instruction in the loop, check to see if it
180 /// has any uses that are outside the current loop. If so, insert LCSSA PHI
181 /// nodes and rewrite the uses.
182 bool LCSSA::ProcessInstruction(Instruction *Inst,
183 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
184 SmallVector<Use*, 16> UsesToRewrite;
186 BasicBlock *InstBB = Inst->getParent();
188 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
191 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
192 if (PHINode *PN = dyn_cast<PHINode>(U))
193 UserBB = PN->getIncomingBlock(UI);
195 if (InstBB != UserBB && !inLoop(UserBB))
196 UsesToRewrite.push_back(&UI.getUse());
199 // If there are no uses outside the loop, exit with no change.
200 if (UsesToRewrite.empty()) return false;
202 ++NumLCSSA; // We are applying the transformation
204 // Invoke instructions are special in that their result value is not available
205 // along their unwind edge. The code below tests to see whether DomBB dominates
206 // the value, so adjust DomBB to the normal destination block, which is
207 // effectively where the value is first usable.
208 BasicBlock *DomBB = Inst->getParent();
209 if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))
210 DomBB = Inv->getNormalDest();
212 DomTreeNode *DomNode = DT->getNode(DomBB);
214 SmallVector<PHINode*, 16> AddedPHIs;
216 SSAUpdater SSAUpdate;
217 SSAUpdate.Initialize(Inst->getType(), Inst->getName());
219 // Insert the LCSSA phi's into all of the exit blocks dominated by the
220 // value, and add them to the Phi's map.
221 for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),
222 BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {
223 BasicBlock *ExitBB = *BBI;
224 if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;
226 // If we already inserted something for this BB, don't reprocess it.
227 if (SSAUpdate.HasValueForBlock(ExitBB)) continue;
229 PHINode *PN = PHINode::Create(Inst->getType(),
230 PredCache.GetNumPreds(ExitBB),
231 Inst->getName()+".lcssa",
234 // Add inputs from inside the loop for this PHI.
235 for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
236 PN->addIncoming(Inst, *PI);
238 // If the exit block has a predecessor not within the loop, arrange for
239 // the incoming value use corresponding to that predecessor to be
240 // rewritten in terms of a different LCSSA PHI.
242 UsesToRewrite.push_back(
244 PN->getOperandNumForIncomingValue(PN->getNumIncomingValues()-1)));
247 AddedPHIs.push_back(PN);
249 // Remember that this phi makes the value alive in this block.
250 SSAUpdate.AddAvailableValue(ExitBB, PN);
252 // If the exiting block is part of a loop inserting a PHI may change its
253 // SCEV analysis. Conservatively drop any caches from it.
255 if (Loop *L = LI->getLoopFor(ExitBB))
259 // If we added a PHI, drop the cache to avoid invalidating SCEV caches.
260 // FIXME: This is a big hammer, can we clear the cache more selectively?
261 if (SE && !AddedPHIs.empty())
264 // Rewrite all uses outside the loop in terms of the new PHIs we just
266 for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {
267 // If this use is in an exit block, rewrite to use the newly inserted PHI.
268 // This is required for correctness because SSAUpdate doesn't handle uses in
269 // the same block. It assumes the PHI we inserted is at the end of the
271 Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());
272 BasicBlock *UserBB = User->getParent();
273 if (PHINode *PN = dyn_cast<PHINode>(User))
274 UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);
276 // Tell SCEV to reanalyze the value that's about to change.
278 SE->forgetValue(*UsesToRewrite[i]);
280 if (isa<PHINode>(UserBB->begin()) &&
281 isExitBlock(UserBB, ExitBlocks)) {
282 UsesToRewrite[i]->set(UserBB->begin());
286 // Otherwise, do full PHI insertion.
287 SSAUpdate.RewriteUse(*UsesToRewrite[i]);
290 // Remove PHI nodes that did not have any uses rewritten.
291 for (unsigned i = 0, e = AddedPHIs.size(); i != e; ++i) {
292 if (AddedPHIs[i]->use_empty())
293 AddedPHIs[i]->eraseFromParent();