blob: 2d1b166c21011ae3cf836e712ce50a1831a9b34e [file] [log] [blame]
Owen Anderson24807372006-05-26 21:11:53 +00001//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
Owen Anderson11f510b2006-05-26 13:58:26 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Anderson11f510b2006-05-26 13:58:26 +00007//
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 (...)
Dan Gohman23d9d272007-05-11 21:10:54 +000015// if (c) if (c)
Owen Anderson11f510b2006-05-26 13:58:26 +000016// X1 = ... X1 = ...
17// else else
18// X2 = ... X2 = ...
19// X3 = phi(X1, X2) X3 = phi(X1, X2)
Dan Gohmanc702a9e2008-06-03 00:57:21 +000020// ... = X3 + 4 X4 = phi(X3)
21// ... = X4 + 4
Owen Anderson11f510b2006-05-26 13:58:26 +000022//
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
Chris Lattnerd216e8b2006-12-19 22:17:40 +000030#define DEBUG_TYPE "lcssa"
Owen Anderson24807372006-05-26 21:11:53 +000031#include "llvm/Transforms/Scalar.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Owen Anderson24807372006-05-26 21:11:53 +000034#include "llvm/Analysis/Dominators.h"
Devang Patelb4559a22007-07-13 23:57:11 +000035#include "llvm/Analysis/LoopPass.h"
36#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000037#include "llvm/IR/Constants.h"
38#include "llvm/IR/Function.h"
39#include "llvm/IR/Instructions.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000040#include "llvm/Pass.h"
Owen Anderson68fbd732009-04-22 08:09:13 +000041#include "llvm/Support/PredIteratorCache.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000042#include "llvm/Transforms/Utils/SSAUpdater.h"
Owen Anderson11f510b2006-05-26 13:58:26 +000043using namespace llvm;
44
Chris Lattnerd216e8b2006-12-19 22:17:40 +000045STATISTIC(NumLCSSA, "Number of live out of a loop variables");
46
Owen Anderson11f510b2006-05-26 13:58:26 +000047namespace {
Chris Lattner8c1db672009-10-11 02:53:37 +000048 struct LCSSA : public LoopPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000049 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000050 LCSSA() : LoopPass(ID) {
51 initializeLCSSAPass(*PassRegistry::getPassRegistry());
52 }
Devang Patel794fd752007-05-01 21:15:47 +000053
Chris Lattnerd41ae8b2006-08-02 00:06:09 +000054 // Cached analysis information for the current function.
Evan Chengcc045d52007-04-18 22:39:00 +000055 DominatorTree *DT;
Benjamin Kramerb2b22732012-10-26 17:31:43 +000056 LoopInfo *LI;
57 ScalarEvolution *SE;
Owen Anderson92deacf2006-06-06 04:28:30 +000058 std::vector<BasicBlock*> LoopBlocks;
Owen Anderson68fbd732009-04-22 08:09:13 +000059 PredIteratorCache PredCache;
Dan Gohman5c89b522009-09-08 15:45:00 +000060 Loop *L;
Owen Anderson11f510b2006-05-26 13:58:26 +000061
Devang Patelb4559a22007-07-13 23:57:11 +000062 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
63
Owen Anderson11f510b2006-05-26 13:58:26 +000064 /// This transformation requires natural loop information & requires that
Owen Andersona90b2c72006-05-27 00:31:37 +000065 /// loop preheaders be inserted into the CFG. It maintains both of these,
66 /// as well as the CFG. It also requires dominator information.
Owen Anderson11f510b2006-05-26 13:58:26 +000067 ///
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Anderson24807372006-05-26 21:11:53 +000069 AU.setPreservesCFG();
Dan Gohmanf6572d02009-11-09 18:28:24 +000070
Dan Gohman052f0002010-07-26 18:11:16 +000071 AU.addRequired<DominatorTree>();
Dan Gohman052f0002010-07-26 18:11:16 +000072 AU.addRequired<LoopInfo>();
Owen Anderson11f510b2006-05-26 13:58:26 +000073 AU.addPreservedID(LoopSimplifyID);
Dan Gohman1e381fc2010-07-16 17:58:45 +000074 AU.addPreserved<ScalarEvolution>();
Owen Anderson11f510b2006-05-26 13:58:26 +000075 }
76 private:
Chris Lattner8c1db672009-10-11 02:53:37 +000077 bool ProcessInstruction(Instruction *Inst,
78 const SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattner39b0c3d2009-10-11 01:07:15 +000079
Dan Gohman5c89b522009-09-08 15:45:00 +000080 /// verifyAnalysis() - Verify loop nest.
81 virtual void verifyAnalysis() const {
Dan Gohman5c89b522009-09-08 15:45:00 +000082 // Check the special guarantees that LCSSA makes.
Dan Gohmanbbf81d82010-03-10 19:38:49 +000083 assert(L->isLCSSAForm(*DT) && "LCSSA form not preserved!");
Dan Gohman5c89b522009-09-08 15:45:00 +000084 }
85
Owen Anderson92deacf2006-06-06 04:28:30 +000086 /// inLoop - returns true if the given block is within the current loop
Chris Lattner39b0c3d2009-10-11 01:07:15 +000087 bool inLoop(BasicBlock *B) const {
Owen Andersone9d93d52006-06-06 04:36:36 +000088 return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
89 }
Owen Anderson11f510b2006-05-26 13:58:26 +000090 };
Owen Anderson11f510b2006-05-26 13:58:26 +000091}
Dan Gohman844731a2008-05-13 00:00:25 +000092
93char LCSSA::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000094INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
95INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Owen Anderson2ab36d32010-10-12 19:48:12 +000096INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +000097INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
Owen Anderson11f510b2006-05-26 13:58:26 +000098
Daniel Dunbar394f0442008-10-22 23:32:42 +000099Pass *llvm::createLCSSAPass() { return new LCSSA(); }
Owen Anderson90c579d2010-08-06 18:33:48 +0000100char &llvm::LCSSAID = LCSSA::ID;
Owen Anderson11f510b2006-05-26 13:58:26 +0000101
Chris Lattner8c1db672009-10-11 02:53:37 +0000102
103/// BlockDominatesAnExit - Return true if the specified block dominates at least
104/// one of the blocks in the specified list.
105static 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
Owen Andersona4529322006-06-08 20:02:53 +0000117/// runOnFunction - Process all loops in the function, inner-most out.
Chris Lattner8c1db672009-10-11 02:53:37 +0000118bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {
119 L = TheLoop;
Owen Anderson7be3f1e2006-06-13 19:37:18 +0000120
Evan Chengcc045d52007-04-18 22:39:00 +0000121 DT = &getAnalysis<DominatorTree>();
Benjamin Kramerb2b22732012-10-26 17:31:43 +0000122 LI = &getAnalysis<LoopInfo>();
123 SE = getAnalysisIfAvailable<ScalarEvolution>();
Devang Patel96bf5242007-08-17 21:59:16 +0000124
Chris Lattner8c1db672009-10-11 02:53:37 +0000125 // Get the set of exiting blocks.
126 SmallVector<BasicBlock*, 8> ExitBlocks;
127 L->getExitBlocks(ExitBlocks);
128
129 if (ExitBlocks.empty())
130 return false;
131
Chris Lattner39b0c3d2009-10-11 01:07:15 +0000132 // Speed up queries by creating a sorted vector of blocks.
Owen Anderson92deacf2006-06-06 04:28:30 +0000133 LoopBlocks.clear();
134 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
Chris Lattner39b0c3d2009-10-11 01:07:15 +0000135 array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());
Owen Anderson24807372006-05-26 21:11:53 +0000136
Chris Lattner8c1db672009-10-11 02:53:37 +0000137 // 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;
Owen Anderson11f510b2006-05-26 13:58:26 +0000140
Chris Lattner8c1db672009-10-11 02:53:37 +0000141 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 }
Benjamin Kramerccd492c2012-10-31 16:30:03 +0000163
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);
Owen Anderson00ea74c2006-05-29 01:00:00 +0000169
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000170 assert(L->isLCSSAForm(*DT));
Chris Lattner8c1db672009-10-11 02:53:37 +0000171 PredCache.clear();
172
173 return MadeChange;
Owen Anderson11f510b2006-05-26 13:58:26 +0000174}
175
Chris Lattner8c1db672009-10-11 02:53:37 +0000176/// isExitBlock - Return true if the specified block is in the list.
177static 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.
188bool 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) {
Gabor Greifa29742d2010-07-09 14:29:14 +0000196 User *U = *UI;
197 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
198 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner8c1db672009-10-11 02:53:37 +0000199 UserBB = PN->getIncomingBlock(UI);
200
201 if (InstBB != UserBB && !inLoop(UserBB))
202 UsesToRewrite.push_back(&UI.getUse());
203 }
Gabor Greifa29742d2010-07-09 14:29:14 +0000204
Chris Lattner8c1db672009-10-11 02:53:37 +0000205 // If there are no uses outside the loop, exit with no change.
206 if (UsesToRewrite.empty()) return false;
207
Owen Anderson408a4062006-05-31 20:55:06 +0000208 ++NumLCSSA; // We are applying the transformation
Chris Lattnerd41ae8b2006-08-02 00:06:09 +0000209
Dan Gohman6b9c9592009-06-26 00:31:13 +0000210 // 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.
Chris Lattner8c1db672009-10-11 02:53:37 +0000214 BasicBlock *DomBB = Inst->getParent();
215 if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))
Dan Gohman6b9c9592009-06-26 00:31:13 +0000216 DomBB = Inv->getNormalDest();
217
218 DomTreeNode *DomNode = DT->getNode(DomBB);
Chris Lattnerd41ae8b2006-08-02 00:06:09 +0000219
Cameron Zwarich838b97e2011-03-15 07:41:25 +0000220 SmallVector<PHINode*, 16> AddedPHIs;
221
Chris Lattner8c1db672009-10-11 02:53:37 +0000222 SSAUpdater SSAUpdate;
Duncan Sandsfc6e29d2010-09-02 08:14:03 +0000223 SSAUpdate.Initialize(Inst->getType(), Inst->getName());
Chris Lattner8c1db672009-10-11 02:53:37 +0000224
225 // Insert the LCSSA phi's into all of the exit blocks dominated by the
Dan Gohmanf6572d02009-11-09 18:28:24 +0000226 // value, and add them to the Phi's map.
Chris Lattner8c1db672009-10-11 02:53:37 +0000227 for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),
Chris Lattner39b0c3d2009-10-11 01:07:15 +0000228 BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {
Chris Lattner8c1db672009-10-11 02:53:37 +0000229 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
Jay Foad3ecfc862011-03-30 11:28:46 +0000235 PHINode *PN = PHINode::Create(Inst->getType(),
236 PredCache.GetNumPreds(ExitBB),
237 Inst->getName()+".lcssa",
Chris Lattner8c1db672009-10-11 02:53:37 +0000238 ExitBB->begin());
Chris Lattnercbea67f2006-10-31 18:56:48 +0000239
Chris Lattner8c1db672009-10-11 02:53:37 +0000240 // Add inputs from inside the loop for this PHI.
Dan Gohmanf6572d02009-11-09 18:28:24 +0000241 for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
Chris Lattner8c1db672009-10-11 02:53:37 +0000242 PN->addIncoming(Inst, *PI);
Dan Gohmanf6572d02009-11-09 18:28:24 +0000243
244 // If the exit block has a predecessor not within the loop, arrange for
Dan Gohmaneaa181c2009-11-09 18:59:22 +0000245 // the incoming value use corresponding to that predecessor to be
Dan Gohmanf6572d02009-11-09 18:28:24 +0000246 // 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 }
Cameron Zwarich838b97e2011-03-15 07:41:25 +0000252
253 AddedPHIs.push_back(PN);
Chris Lattner8c1db672009-10-11 02:53:37 +0000254
255 // Remember that this phi makes the value alive in this block.
256 SSAUpdate.AddAvailableValue(ExitBB, PN);
Owen Anderson3d2aa472006-06-12 07:10:16 +0000257 }
Benjamin Kramer4ad3d982012-10-31 10:01:29 +0000258
Chris Lattner8c1db672009-10-11 02:53:37 +0000259 // 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)) {
Benjamin Kramerccd492c2012-10-31 16:30:03 +0000273 // 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());
Chris Lattner8c1db672009-10-11 02:53:37 +0000276 UsesToRewrite[i]->set(UserBB->begin());
Chris Lattnerd41ae8b2006-08-02 00:06:09 +0000277 continue;
Owen Anderson2824da42006-06-01 06:05:47 +0000278 }
Chris Lattnerd41ae8b2006-08-02 00:06:09 +0000279
Chris Lattner8c1db672009-10-11 02:53:37 +0000280 // Otherwise, do full PHI insertion.
281 SSAUpdate.RewriteUse(*UsesToRewrite[i]);
Chris Lattnerd41ae8b2006-08-02 00:06:09 +0000282 }
Cameron Zwarich838b97e2011-03-15 07:41:25 +0000283
284 // Remove PHI nodes that did not have any uses rewritten.
285 for (unsigned i = 0, e = AddedPHIs.size(); i != e; ++i) {
Cameron Zwarich6e51c6a2011-03-15 18:42:33 +0000286 if (AddedPHIs[i]->use_empty())
Cameron Zwarich838b97e2011-03-15 07:41:25 +0000287 AddedPHIs[i]->eraseFromParent();
288 }
Owen Andersone4e1ecd2006-07-09 08:14:06 +0000289
Chris Lattner8c1db672009-10-11 02:53:37 +0000290 return true;
Owen Anderson408a4062006-05-31 20:55:06 +0000291}
Chris Lattnerd41ae8b2006-08-02 00:06:09 +0000292