blob: 03d273d25d791591bcab11f608e41c81bd6cc647 [file] [log] [blame]
Chris Lattner67a98012003-10-12 21:44:18 +00001//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner38acf9e2002-09-26 16:17:31 +00009//
Chris Lattneree2c50c2003-10-12 21:43:28 +000010// This pass performs several transformations to transform natural loops into a
11// simpler form, which makes subsequent analyses and transformations simpler and
12// more effective.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000013//
14// Loop pre-header insertion guarantees that there is a single, non-critical
15// entry edge from outside of the loop to the loop header. This simplifies a
16// number of analyses and transformations, such as LICM.
17//
18// Loop exit-block insertion guarantees that all exit blocks from the loop
19// (blocks which are outside of the loop that have predecessors inside of the
Chris Lattner66ea98e2003-12-10 17:20:35 +000020// loop) only have predecessors from inside of the loop (and are thus dominated
21// by the loop header). This simplifies transformations such as store-sinking
22// that are built into LICM.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000023//
Chris Lattner2ab6a732003-10-13 00:37:13 +000024// This pass also guarantees that loops will have exactly one backedge.
25//
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000026// Note that the simplifycfg pass will clean up blocks which are split out but
Chris Lattneree2c50c2003-10-12 21:43:28 +000027// end up being unnecessary, so usage of this pass should not pessimize
28// generated code.
29//
30// This pass obviously modifies the CFG, but updates loop information and
31// dominator information.
Chris Lattner38acf9e2002-09-26 16:17:31 +000032//
33//===----------------------------------------------------------------------===//
34
Chris Lattnerd216e8b2006-12-19 22:17:40 +000035#define DEBUG_TYPE "loopsimplify"
Chris Lattner38acf9e2002-09-26 16:17:31 +000036#include "llvm/Transforms/Scalar.h"
Chris Lattner3cb63dd2007-10-29 02:30:37 +000037#include "llvm/Constants.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000038#include "llvm/Instructions.h"
Chris Lattner2ef703e2004-03-14 03:59:22 +000039#include "llvm/Function.h"
40#include "llvm/Type.h"
Chris Lattnercec5b882005-03-25 06:37:22 +000041#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0f98e752003-12-19 06:27:08 +000042#include "llvm/Analysis/Dominators.h"
43#include "llvm/Analysis/LoopInfo.h"
Chris Lattner54b9c3b2008-04-21 01:28:02 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner38acf9e2002-09-26 16:17:31 +000045#include "llvm/Support/CFG.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000047#include "llvm/ADT/SetOperations.h"
48#include "llvm/ADT/SetVector.h"
49#include "llvm/ADT/Statistic.h"
50#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattner66ea98e2003-12-10 17:20:35 +000051using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000052
Chris Lattnerd216e8b2006-12-19 22:17:40 +000053STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
54STATISTIC(NumNested , "Number of nested loops split out");
Chris Lattner38acf9e2002-09-26 16:17:31 +000055
Chris Lattnerd216e8b2006-12-19 22:17:40 +000056namespace {
Chris Lattner95255282006-06-28 23:17:24 +000057 struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000058 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000059 LoopSimplify() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000060
Chris Lattnercec5b882005-03-25 06:37:22 +000061 // AA - If we have an alias analysis object to update, this is it, otherwise
62 // this is null.
63 AliasAnalysis *AA;
Chris Lattnerc27e0562006-02-14 22:34:08 +000064 LoopInfo *LI;
Devang Patel0e7f7282007-06-21 17:23:45 +000065 DominatorTree *DT;
Chris Lattner38acf9e2002-09-26 16:17:31 +000066 virtual bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +000067
Chris Lattner38acf9e2002-09-26 16:17:31 +000068 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 // We need loop information to identify the loops...
70 AU.addRequired<LoopInfo>();
Chris Lattner786c5642004-03-13 22:01:26 +000071 AU.addRequired<DominatorTree>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000072
73 AU.addPreserved<LoopInfo>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000074 AU.addPreserved<DominatorTree>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000075 AU.addPreserved<DominanceFrontier>();
Devang Patel4c37c072008-06-06 17:50:58 +000076 AU.addPreserved<AliasAnalysis>();
Chris Lattner94f40322005-08-10 02:07:32 +000077 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
Chris Lattner38acf9e2002-09-26 16:17:31 +000078 }
Devang Patel58e0ef12007-07-19 18:02:32 +000079
80 /// verifyAnalysis() - Verify loop nest.
81 void verifyAnalysis() const {
82#ifndef NDEBUG
83 LoopInfo *NLI = &getAnalysis<LoopInfo>();
84 for (LoopInfo::iterator I = NLI->begin(), E = NLI->end(); I != E; ++I)
85 (*I)->verifyLoop();
86#endif
87 }
88
Chris Lattner38acf9e2002-09-26 16:17:31 +000089 private:
90 bool ProcessLoop(Loop *L);
Chris Lattner59fb87d2004-04-18 22:27:10 +000091 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner38acf9e2002-09-26 16:17:31 +000092 void InsertPreheaderForLoop(Loop *L);
Chris Lattner529b28d2004-04-13 05:05:33 +000093 Loop *SeparateNestedLoop(Loop *L);
Chris Lattner2ab6a732003-10-13 00:37:13 +000094 void InsertUniqueBackedgeBlock(Loop *L);
Chris Lattner120fce52006-09-23 08:19:21 +000095 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
Chris Lattner54b9c3b2008-04-21 01:28:02 +000096 SmallVectorImpl<BasicBlock*> &SplitPreds,
Chris Lattner120fce52006-09-23 08:19:21 +000097 Loop *L);
Chris Lattner38acf9e2002-09-26 16:17:31 +000098 };
Chris Lattner38acf9e2002-09-26 16:17:31 +000099}
100
Dan Gohman844731a2008-05-13 00:00:25 +0000101char LoopSimplify::ID = 0;
102static RegisterPass<LoopSimplify>
103X("loopsimplify", "Canonicalize natural loops", true);
104
Chris Lattner38acf9e2002-09-26 16:17:31 +0000105// Publically exposed interface to pass...
Dan Gohman6ddba2b2008-05-13 02:05:11 +0000106const PassInfo *const llvm::LoopSimplifyID = &X;
Chris Lattner4b501562004-09-20 04:43:15 +0000107FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner38acf9e2002-09-26 16:17:31 +0000108
Chris Lattner38acf9e2002-09-26 16:17:31 +0000109/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
110/// it in any convenient order) inserting preheaders...
111///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000112bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000113 bool Changed = false;
Chris Lattnerc27e0562006-02-14 22:34:08 +0000114 LI = &getAnalysis<LoopInfo>();
Duncan Sands1465d612009-01-28 13:14:17 +0000115 AA = getAnalysisIfAvailable<AliasAnalysis>();
Devang Patel0e7f7282007-06-21 17:23:45 +0000116 DT = &getAnalysis<DominatorTree>();
Chris Lattner38acf9e2002-09-26 16:17:31 +0000117
Chris Lattnerfa789462006-08-12 04:51:20 +0000118 // Check to see that no blocks (other than the header) in loops have
119 // predecessors that are not in loops. This is not valid for natural loops,
120 // but can occur if the blocks are unreachable. Since they are unreachable we
121 // can just shamelessly destroy their terminators to make them not branch into
122 // the loop!
123 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
124 // This case can only occur for unreachable blocks. Blocks that are
125 // unreachable can't be in loops, so filter those blocks out.
126 if (LI->getLoopFor(BB)) continue;
127
128 bool BlockUnreachable = false;
Nick Lewycky280a6e62008-04-25 16:53:59 +0000129 TerminatorInst *TI = BB->getTerminator();
Chris Lattnerfa789462006-08-12 04:51:20 +0000130
131 // Check to see if any successors of this block are non-loop-header loops
132 // that are not the header.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000133 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
Chris Lattnerfa789462006-08-12 04:51:20 +0000134 // If this successor is not in a loop, BB is clearly ok.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000135 Loop *L = LI->getLoopFor(TI->getSuccessor(i));
Chris Lattnerfa789462006-08-12 04:51:20 +0000136 if (!L) continue;
137
138 // If the succ is the loop header, and if L is a top-level loop, then this
139 // is an entrance into a loop through the header, which is also ok.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000140 if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
Chris Lattnerfa789462006-08-12 04:51:20 +0000141 continue;
142
143 // Otherwise, this is an entrance into a loop from some place invalid.
144 // Either the loop structure is invalid and this is not a natural loop (in
145 // which case the compiler is buggy somewhere else) or BB is unreachable.
146 BlockUnreachable = true;
147 break;
148 }
149
150 // If this block is ok, check the next one.
151 if (!BlockUnreachable) continue;
152
153 // Otherwise, this block is dead. To clean up the CFG and to allow later
154 // loop transformations to ignore this case, we delete the edges into the
155 // loop by replacing the terminator.
156
157 // Remove PHI entries from the successors.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000158 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
159 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattnerfa789462006-08-12 04:51:20 +0000160
Chris Lattner3cb63dd2007-10-29 02:30:37 +0000161 // Add a new unreachable instruction before the old terminator.
Chris Lattnerfa789462006-08-12 04:51:20 +0000162 new UnreachableInst(TI);
163
164 // Delete the dead terminator.
Chris Lattner3cb63dd2007-10-29 02:30:37 +0000165 if (AA) AA->deleteValue(TI);
166 if (!TI->use_empty())
167 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
168 TI->eraseFromParent();
Chris Lattnerfa789462006-08-12 04:51:20 +0000169 Changed |= true;
170 }
171
Chris Lattnerc27e0562006-02-14 22:34:08 +0000172 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner329c1c62004-01-08 00:09:44 +0000173 Changed |= ProcessLoop(*I);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000174
175 return Changed;
176}
177
Chris Lattner38acf9e2002-09-26 16:17:31 +0000178/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
179/// all loops have preheaders.
180///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000181bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000182 bool Changed = false;
Chris Lattner3bb46572006-08-12 05:25:00 +0000183ReprocessLoop:
184
Chris Lattner0ab9f962006-02-14 23:06:02 +0000185 // Canonicalize inner loops before outer loops. Inner loop canonicalization
186 // can provide work for the outer loop to canonicalize.
187 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
188 Changed |= ProcessLoop(*I);
189
Chris Lattner2ef703e2004-03-14 03:59:22 +0000190 assert(L->getBlocks()[0] == L->getHeader() &&
191 "Header isn't first block in loop?");
Chris Lattner2ef703e2004-03-14 03:59:22 +0000192
Chris Lattnerfa789462006-08-12 04:51:20 +0000193 // Does the loop already have a preheader? If so, don't insert one.
Chris Lattner38acf9e2002-09-26 16:17:31 +0000194 if (L->getLoopPreheader() == 0) {
195 InsertPreheaderForLoop(L);
196 NumInserted++;
197 Changed = true;
198 }
199
Chris Lattner66ea98e2003-12-10 17:20:35 +0000200 // Next, check to make sure that all exit nodes of the loop only have
201 // predecessors that are inside of the loop. This check guarantees that the
202 // loop preheader/header will dominate the exit blocks. If the exit block has
Chris Lattneree628cf2006-02-12 01:59:10 +0000203 // predecessors from outside of the loop, split the edge now.
Devang Patelb7211a22007-08-21 00:31:24 +0000204 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattneree628cf2006-02-12 01:59:10 +0000205 L->getExitBlocks(ExitBlocks);
Chris Lattnerc27e0562006-02-14 22:34:08 +0000206
Chris Lattneree628cf2006-02-12 01:59:10 +0000207 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerfed22aa2004-07-15 08:20:22 +0000208 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
209 E = ExitBlockSet.end(); I != E; ++I) {
210 BasicBlock *ExitBlock = *I;
Chris Lattnerde7aee72004-07-15 05:36:31 +0000211 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
212 PI != PE; ++PI)
Chris Lattner8587eb32006-02-11 02:13:17 +0000213 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
214 // allowed.
Chris Lattneree628cf2006-02-12 01:59:10 +0000215 if (!L->contains(*PI)) {
Chris Lattnerfed22aa2004-07-15 08:20:22 +0000216 RewriteLoopExitBlock(L, ExitBlock);
Chris Lattnerde7aee72004-07-15 05:36:31 +0000217 NumInserted++;
218 Changed = true;
219 break;
220 }
Chris Lattnerfed22aa2004-07-15 08:20:22 +0000221 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000222
Chris Lattner529b28d2004-04-13 05:05:33 +0000223 // If the header has more than two predecessors at this point (from the
224 // preheader and from multiple backedges), we must adjust the loop.
Chris Lattner3bb46572006-08-12 05:25:00 +0000225 unsigned NumBackedges = L->getNumBackEdges();
226 if (NumBackedges != 1) {
227 // If this is really a nested loop, rip it out into a child loop. Don't do
228 // this for loops with a giant number of backedges, just factor them into a
229 // common backedge instead.
230 if (NumBackedges < 8) {
231 if (Loop *NL = SeparateNestedLoop(L)) {
232 ++NumNested;
233 // This is a big restructuring change, reprocess the whole loop.
234 ProcessLoop(NL);
235 Changed = true;
236 // GCC doesn't tail recursion eliminate this.
237 goto ReprocessLoop;
238 }
Chris Lattner529b28d2004-04-13 05:05:33 +0000239 }
240
Chris Lattner3bb46572006-08-12 05:25:00 +0000241 // If we either couldn't, or didn't want to, identify nesting of the loops,
242 // insert a new block that all backedges target, then make it jump to the
243 // loop header.
Chris Lattner2ab6a732003-10-13 00:37:13 +0000244 InsertUniqueBackedgeBlock(L);
245 NumInserted++;
246 Changed = true;
247 }
248
Chris Lattner94f40322005-08-10 02:07:32 +0000249 // Scan over the PHI nodes in the loop header. Since they now have only two
250 // incoming values (the loop is canonicalized), we may have simplified the PHI
251 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
252 PHINode *PN;
Chris Lattner94f40322005-08-10 02:07:32 +0000253 for (BasicBlock::iterator I = L->getHeader()->begin();
254 (PN = dyn_cast<PHINode>(I++)); )
Chris Lattner98599ba2005-08-10 17:15:20 +0000255 if (Value *V = PN->hasConstantValue()) {
Devang Patel4c37c072008-06-06 17:50:58 +0000256 if (AA) AA->deleteValue(PN);
257 PN->replaceAllUsesWith(V);
258 PN->eraseFromParent();
259 }
Chris Lattner94f40322005-08-10 02:07:32 +0000260
Chris Lattner38acf9e2002-09-26 16:17:31 +0000261 return Changed;
262}
263
Chris Lattner38acf9e2002-09-26 16:17:31 +0000264/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
265/// preheader, this method is called to insert one. This method has two phases:
266/// preheader insertion and analysis updating.
267///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000268void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000269 BasicBlock *Header = L->getHeader();
270
271 // Compute the set of predecessors of the loop that are not in the loop.
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000272 SmallVector<BasicBlock*, 8> OutsideBlocks;
Chris Lattner38acf9e2002-09-26 16:17:31 +0000273 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
274 PI != PE; ++PI)
Chris Lattner8587eb32006-02-11 02:13:17 +0000275 if (!L->contains(*PI)) // Coming in from outside the loop?
276 OutsideBlocks.push_back(*PI); // Keep track of it...
Misha Brukmanfd939082005-04-21 23:48:37 +0000277
Chris Lattnerc3984572006-09-23 07:40:52 +0000278 // Split out the loop pre-header.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000279 BasicBlock *NewBB =
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000280 SplitBlockPredecessors(Header, &OutsideBlocks[0], OutsideBlocks.size(),
281 ".preheader", this);
Chris Lattnerc3984572006-09-23 07:40:52 +0000282
Misha Brukmanfd939082005-04-21 23:48:37 +0000283
Chris Lattner38acf9e2002-09-26 16:17:31 +0000284 //===--------------------------------------------------------------------===//
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000285 // Update analysis results now that we have performed the transformation
Chris Lattner38acf9e2002-09-26 16:17:31 +0000286 //
Misha Brukmanfd939082005-04-21 23:48:37 +0000287
Chris Lattner38acf9e2002-09-26 16:17:31 +0000288 // We know that we have loop information to update... update it now.
289 if (Loop *Parent = L->getParentLoop())
Owen Andersond735ee82007-11-27 03:43:35 +0000290 Parent->addBasicBlockToLoop(NewBB, LI->getBase());
Chris Lattner9f879cf2003-02-27 22:48:57 +0000291
Chris Lattner120fce52006-09-23 08:19:21 +0000292 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
293 // code layout too horribly.
294 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000295}
296
Chris Lattner529b28d2004-04-13 05:05:33 +0000297/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
298/// blocks. This method is used to split exit blocks that have predecessors
299/// outside of the loop.
Chris Lattner59fb87d2004-04-18 22:27:10 +0000300BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000301 SmallVector<BasicBlock*, 8> LoopBlocks;
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000302 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
303 if (L->contains(*I))
304 LoopBlocks.push_back(*I);
305
Chris Lattner7e7ad492003-02-27 22:31:07 +0000306 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000307 BasicBlock *NewBB = SplitBlockPredecessors(Exit, &LoopBlocks[0],
308 LoopBlocks.size(), ".loopexit",
309 this);
Chris Lattner7e7ad492003-02-27 22:31:07 +0000310
Chris Lattnerc27e0562006-02-14 22:34:08 +0000311 // Update Loop Information - we know that the new block will be in whichever
312 // loop the Exit block is in. Note that it may not be in that immediate loop,
313 // if the successor is some other loop header. In that case, we continue
314 // walking up the loop tree to find a loop that contains both the successor
315 // block and the predecessor block.
316 Loop *SuccLoop = LI->getLoopFor(Exit);
317 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
318 SuccLoop = SuccLoop->getParentLoop();
319 if (SuccLoop)
Owen Andersond735ee82007-11-27 03:43:35 +0000320 SuccLoop->addBasicBlockToLoop(NewBB, LI->getBase());
Chris Lattner74cd04e2003-02-28 03:07:54 +0000321
Chris Lattner59fb87d2004-04-18 22:27:10 +0000322 return NewBB;
Chris Lattner2ab6a732003-10-13 00:37:13 +0000323}
324
Chris Lattner529b28d2004-04-13 05:05:33 +0000325/// AddBlockAndPredsToSet - Add the specified block, and all of its
326/// predecessors, to the specified set, if it's not already in there. Stop
327/// predecessor traversal when we reach StopBlock.
Devang Patel58d7fbf2007-04-20 20:04:37 +0000328static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
Chris Lattner529b28d2004-04-13 05:05:33 +0000329 std::set<BasicBlock*> &Blocks) {
Devang Patel58d7fbf2007-04-20 20:04:37 +0000330 std::vector<BasicBlock *> WorkList;
331 WorkList.push_back(InputBB);
332 do {
333 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
334 if (Blocks.insert(BB).second && BB != StopBlock)
335 // If BB is not already processed and it is not a stop block then
336 // insert its predecessor in the work list
337 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
338 BasicBlock *WBB = *I;
339 WorkList.push_back(WBB);
340 }
341 } while(!WorkList.empty());
Chris Lattner529b28d2004-04-13 05:05:33 +0000342}
343
Chris Lattner1f62f822004-04-13 15:21:18 +0000344/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
345/// PHI node that tells us how to partition the loops.
Devang Pateldba24132007-06-08 01:50:32 +0000346static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorTree *DT,
Owen Andersonad190142007-04-09 22:54:50 +0000347 AliasAnalysis *AA) {
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000348 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
349 PHINode *PN = cast<PHINode>(I);
Chris Lattner1f62f822004-04-13 15:21:18 +0000350 ++I;
Nate Begemana83ba0f2005-08-04 23:24:19 +0000351 if (Value *V = PN->hasConstantValue())
Devang Pateldba24132007-06-08 01:50:32 +0000352 if (!isa<Instruction>(V) || DT->dominates(cast<Instruction>(V), PN)) {
Chris Lattnerc30bda72004-10-17 21:22:38 +0000353 // This is a degenerate PHI already, don't modify it!
354 PN->replaceAllUsesWith(V);
Chris Lattnercec5b882005-03-25 06:37:22 +0000355 if (AA) AA->deleteValue(PN);
Chris Lattnerfee34112005-03-06 21:35:38 +0000356 PN->eraseFromParent();
Chris Lattnerc30bda72004-10-17 21:22:38 +0000357 continue;
358 }
359
360 // Scan this PHI node looking for a use of the PHI node by itself.
361 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
362 if (PN->getIncomingValue(i) == PN &&
363 L->contains(PN->getIncomingBlock(i)))
364 // We found something tasty to remove.
365 return PN;
Chris Lattner1f62f822004-04-13 15:21:18 +0000366 }
367 return 0;
368}
369
Chris Lattner120fce52006-09-23 08:19:21 +0000370// PlaceSplitBlockCarefully - If the block isn't already, move the new block to
371// right after some 'outside block' block. This prevents the preheader from
372// being placed inside the loop body, e.g. when the loop hasn't been rotated.
373void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000374 SmallVectorImpl<BasicBlock*> &SplitPreds,
Chris Lattner120fce52006-09-23 08:19:21 +0000375 Loop *L) {
376 // Check to see if NewBB is already well placed.
377 Function::iterator BBI = NewBB; --BBI;
378 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
379 if (&*BBI == SplitPreds[i])
380 return;
381 }
382
383 // If it isn't already after an outside block, move it after one. This is
384 // always good as it makes the uncond branch from the outside block into a
385 // fall-through.
386
387 // Figure out *which* outside block to put this after. Prefer an outside
388 // block that neighbors a BB actually in the loop.
389 BasicBlock *FoundBB = 0;
390 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
391 Function::iterator BBI = SplitPreds[i];
392 if (++BBI != NewBB->getParent()->end() &&
393 L->contains(BBI)) {
394 FoundBB = SplitPreds[i];
395 break;
396 }
397 }
398
399 // If our heuristic for a *good* bb to place this after doesn't find
400 // anything, just pick something. It's likely better than leaving it within
401 // the loop.
402 if (!FoundBB)
403 FoundBB = SplitPreds[0];
404 NewBB->moveAfter(FoundBB);
405}
406
407
Chris Lattner529b28d2004-04-13 05:05:33 +0000408/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
409/// them out into a nested loop. This is important for code that looks like
410/// this:
411///
412/// Loop:
413/// ...
414/// br cond, Loop, Next
415/// ...
416/// br cond2, Loop, Out
417///
418/// To identify this common case, we look at the PHI nodes in the header of the
419/// loop. PHI nodes with unchanging values on one backedge correspond to values
420/// that change in the "outer" loop, but not in the "inner" loop.
421///
422/// If we are able to separate out a loop, return the new outer loop that was
423/// created.
424///
425Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
Devang Pateldba24132007-06-08 01:50:32 +0000426 PHINode *PN = FindPHIToPartitionLoops(L, DT, AA);
Chris Lattner1f62f822004-04-13 15:21:18 +0000427 if (PN == 0) return 0; // No known way to partition.
Chris Lattner529b28d2004-04-13 05:05:33 +0000428
Chris Lattner1f62f822004-04-13 15:21:18 +0000429 // Pull out all predecessors that have varying values in the loop. This
430 // handles the case when a PHI node has multiple instances of itself as
431 // arguments.
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000432 SmallVector<BasicBlock*, 8> OuterLoopPreds;
Chris Lattner1f62f822004-04-13 15:21:18 +0000433 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
434 if (PN->getIncomingValue(i) != PN ||
435 !L->contains(PN->getIncomingBlock(i)))
436 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner529b28d2004-04-13 05:05:33 +0000437
Chris Lattner4b662422004-04-13 16:23:25 +0000438 BasicBlock *Header = L->getHeader();
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000439 BasicBlock *NewBB = SplitBlockPredecessors(Header, &OuterLoopPreds[0],
440 OuterLoopPreds.size(),
441 ".outer", this);
Chris Lattner529b28d2004-04-13 05:05:33 +0000442
Chris Lattner120fce52006-09-23 08:19:21 +0000443 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
444 // code layout too horribly.
445 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
446
Chris Lattner529b28d2004-04-13 05:05:33 +0000447 // Create the new outer loop.
448 Loop *NewOuter = new Loop();
449
Chris Lattner529b28d2004-04-13 05:05:33 +0000450 // Change the parent loop to use the outer loop as its child now.
451 if (Loop *Parent = L->getParentLoop())
452 Parent->replaceChildLoopWith(L, NewOuter);
453 else
Chris Lattnerc27e0562006-02-14 22:34:08 +0000454 LI->changeTopLevelLoop(L, NewOuter);
Chris Lattner529b28d2004-04-13 05:05:33 +0000455
456 // This block is going to be our new header block: add it to this loop and all
457 // parent loops.
Owen Andersond735ee82007-11-27 03:43:35 +0000458 NewOuter->addBasicBlockToLoop(NewBB, LI->getBase());
Chris Lattner529b28d2004-04-13 05:05:33 +0000459
460 // L is now a subloop of our outer loop.
461 NewOuter->addChildLoop(L);
462
Dan Gohman9b787632008-06-22 20:18:58 +0000463 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
464 I != E; ++I)
465 NewOuter->addBlockEntry(*I);
Chris Lattner529b28d2004-04-13 05:05:33 +0000466
467 // Determine which blocks should stay in L and which should be moved out to
468 // the Outer loop now.
Chris Lattner529b28d2004-04-13 05:05:33 +0000469 std::set<BasicBlock*> BlocksInL;
470 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
Devang Pateldba24132007-06-08 01:50:32 +0000471 if (DT->dominates(Header, *PI))
Chris Lattner529b28d2004-04-13 05:05:33 +0000472 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
473
474
475 // Scan all of the loop children of L, moving them to OuterLoop if they are
476 // not part of the inner loop.
David Greenec08fa282007-06-29 02:53:16 +0000477 const std::vector<Loop*> &SubLoops = L->getSubLoops();
478 for (size_t I = 0; I != SubLoops.size(); )
479 if (BlocksInL.count(SubLoops[I]->getHeader()))
Chris Lattner529b28d2004-04-13 05:05:33 +0000480 ++I; // Loop remains in L
481 else
David Greenec08fa282007-06-29 02:53:16 +0000482 NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
Chris Lattner529b28d2004-04-13 05:05:33 +0000483
484 // Now that we know which blocks are in L and which need to be moved to
485 // OuterLoop, move any blocks that need it.
486 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
487 BasicBlock *BB = L->getBlocks()[i];
488 if (!BlocksInL.count(BB)) {
489 // Move this block to the parent, updating the exit blocks sets
490 L->removeBlockFromLoop(BB);
Chris Lattnerc27e0562006-02-14 22:34:08 +0000491 if ((*LI)[BB] == L)
492 LI->changeLoopFor(BB, NewOuter);
Chris Lattner529b28d2004-04-13 05:05:33 +0000493 --i;
494 }
495 }
496
Chris Lattner529b28d2004-04-13 05:05:33 +0000497 return NewOuter;
498}
499
500
501
Chris Lattner2ab6a732003-10-13 00:37:13 +0000502/// InsertUniqueBackedgeBlock - This method is called when the specified loop
503/// has more than one backedge in it. If this occurs, revector all of these
504/// backedges to target a new basic block and have that block branch to the loop
505/// header. This ensures that loops have exactly one backedge.
506///
507void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
508 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
509
510 // Get information about the loop
511 BasicBlock *Preheader = L->getLoopPreheader();
512 BasicBlock *Header = L->getHeader();
513 Function *F = Header->getParent();
514
515 // Figure out which basic blocks contain back-edges to the loop header.
516 std::vector<BasicBlock*> BackedgeBlocks;
517 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
518 if (*I != Preheader) BackedgeBlocks.push_back(*I);
519
520 // Create and insert the new backedge block...
Gabor Greif051a9502008-04-06 20:25:17 +0000521 BasicBlock *BEBlock = BasicBlock::Create(Header->getName()+".backedge", F);
522 BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000523
524 // Move the new backedge block to right after the last backedge block.
525 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
526 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000527
Chris Lattner2ab6a732003-10-13 00:37:13 +0000528 // Now that the block has been inserted into the function, create PHI nodes in
529 // the backedge block which correspond to any PHI nodes in the header block.
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000530 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
531 PHINode *PN = cast<PHINode>(I);
Gabor Greif051a9502008-04-06 20:25:17 +0000532 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".be",
533 BETerminator);
Chris Lattner55517062005-01-29 00:39:08 +0000534 NewPN->reserveOperandSpace(BackedgeBlocks.size());
Chris Lattnercec5b882005-03-25 06:37:22 +0000535 if (AA) AA->copyValue(PN, NewPN);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000536
537 // Loop over the PHI node, moving all entries except the one for the
538 // preheader over to the new PHI node.
539 unsigned PreheaderIdx = ~0U;
540 bool HasUniqueIncomingValue = true;
541 Value *UniqueValue = 0;
542 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
543 BasicBlock *IBB = PN->getIncomingBlock(i);
544 Value *IV = PN->getIncomingValue(i);
545 if (IBB == Preheader) {
546 PreheaderIdx = i;
547 } else {
548 NewPN->addIncoming(IV, IBB);
549 if (HasUniqueIncomingValue) {
550 if (UniqueValue == 0)
551 UniqueValue = IV;
552 else if (UniqueValue != IV)
553 HasUniqueIncomingValue = false;
554 }
555 }
556 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000557
Chris Lattner2ab6a732003-10-13 00:37:13 +0000558 // Delete all of the incoming values from the old PN except the preheader's
559 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
560 if (PreheaderIdx != 0) {
561 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
562 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
563 }
Chris Lattner55517062005-01-29 00:39:08 +0000564 // Nuke all entries except the zero'th.
565 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
566 PN->removeIncomingValue(e-i, false);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000567
568 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
569 PN->addIncoming(NewPN, BEBlock);
570
571 // As an optimization, if all incoming values in the new PhiNode (which is a
572 // subset of the incoming values of the old PHI node) have the same value,
573 // eliminate the PHI Node.
574 if (HasUniqueIncomingValue) {
575 NewPN->replaceAllUsesWith(UniqueValue);
Chris Lattnercec5b882005-03-25 06:37:22 +0000576 if (AA) AA->deleteValue(NewPN);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000577 BEBlock->getInstList().erase(NewPN);
578 }
579 }
580
581 // Now that all of the PHI nodes have been inserted and adjusted, modify the
Nick Lewycky280a6e62008-04-25 16:53:59 +0000582 // backedge blocks to just to the BEBlock instead of the header.
Chris Lattner2ab6a732003-10-13 00:37:13 +0000583 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
584 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
585 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
586 if (TI->getSuccessor(Op) == Header)
587 TI->setSuccessor(Op, BEBlock);
588 }
589
590 //===--- Update all analyses which we must preserve now -----------------===//
591
592 // Update Loop Information - we know that this block is now in the current
593 // loop and all parent loops.
Owen Andersond735ee82007-11-27 03:43:35 +0000594 L->addBasicBlockToLoop(BEBlock, LI->getBase());
Chris Lattner2ab6a732003-10-13 00:37:13 +0000595
Devang Patel0e7f7282007-06-21 17:23:45 +0000596 // Update dominator information
597 DT->splitBlock(BEBlock);
Duncan Sands1465d612009-01-28 13:14:17 +0000598 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel0e7f7282007-06-21 17:23:45 +0000599 DF->splitBlock(BEBlock);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000600}