blob: b90f46f71706cca4a8e34bba9933dc47c5df9446 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// 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.
13//
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
20// 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.
23//
24// This pass also guarantees that loops will have exactly one backedge.
25//
26// Note that the simplifycfg pass will clean up blocks which are split out but
27// 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.
32//
33//===----------------------------------------------------------------------===//
34
35#define DEBUG_TYPE "loopsimplify"
36#include "llvm/Transforms/Scalar.h"
Chris Lattner55fb7932007-10-29 02:30:37 +000037#include "llvm/Constants.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038#include "llvm/Instructions.h"
39#include "llvm/Function.h"
40#include "llvm/Type.h"
41#include "llvm/Analysis/AliasAnalysis.h"
42#include "llvm/Analysis/Dominators.h"
43#include "llvm/Analysis/LoopInfo.h"
44#include "llvm/Support/CFG.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/ADT/SetOperations.h"
47#include "llvm/ADT/SetVector.h"
48#include "llvm/ADT/Statistic.h"
49#include "llvm/ADT/DepthFirstIterator.h"
50using namespace llvm;
51
52STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
53STATISTIC(NumNested , "Number of nested loops split out");
54
55namespace {
56 struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass {
57 static char ID; // Pass identification, replacement for typeid
58 LoopSimplify() : FunctionPass((intptr_t)&ID) {}
59
60 // AA - If we have an alias analysis object to update, this is it, otherwise
61 // this is null.
62 AliasAnalysis *AA;
63 LoopInfo *LI;
64 DominatorTree *DT;
65 virtual bool runOnFunction(Function &F);
66
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 // We need loop information to identify the loops...
69 AU.addRequired<LoopInfo>();
70 AU.addRequired<DominatorTree>();
71
72 AU.addPreserved<LoopInfo>();
73 AU.addPreserved<DominatorTree>();
74 AU.addPreserved<DominanceFrontier>();
75 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
76 }
Devang Patela5eb9a32007-07-19 18:02:32 +000077
78 /// verifyAnalysis() - Verify loop nest.
79 void verifyAnalysis() const {
80#ifndef NDEBUG
81 LoopInfo *NLI = &getAnalysis<LoopInfo>();
82 for (LoopInfo::iterator I = NLI->begin(), E = NLI->end(); I != E; ++I)
83 (*I)->verifyLoop();
84#endif
85 }
86
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087 private:
88 bool ProcessLoop(Loop *L);
89 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
90 const std::vector<BasicBlock*> &Preds);
91 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
92 void InsertPreheaderForLoop(Loop *L);
93 Loop *SeparateNestedLoop(Loop *L);
94 void InsertUniqueBackedgeBlock(Loop *L);
95 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
96 std::vector<BasicBlock*> &SplitPreds,
97 Loop *L);
98 };
99
100 char LoopSimplify::ID = 0;
101 RegisterPass<LoopSimplify>
102 X("loopsimplify", "Canonicalize natural loops", true);
103}
104
105// Publically exposed interface to pass...
106const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
107FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
108
109/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
110/// it in any convenient order) inserting preheaders...
111///
112bool LoopSimplify::runOnFunction(Function &F) {
113 bool Changed = false;
114 LI = &getAnalysis<LoopInfo>();
115 AA = getAnalysisToUpdate<AliasAnalysis>();
116 DT = &getAnalysis<DominatorTree>();
117
118 // 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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129
130 // Check to see if any successors of this block are non-loop-header loops
131 // that are not the header.
Nick Lewycky95a0d762008-03-09 05:24:34 +0000132 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133 // If this successor is not in a loop, BB is clearly ok.
Nick Lewycky95a0d762008-03-09 05:24:34 +0000134 Loop *L = LI->getLoopFor(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135 if (!L) continue;
136
137 // If the succ is the loop header, and if L is a top-level loop, then this
138 // is an entrance into a loop through the header, which is also ok.
Nick Lewycky95a0d762008-03-09 05:24:34 +0000139 if (L->getHeader() == *I && L->getParentLoop() == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140 continue;
141
142 // Otherwise, this is an entrance into a loop from some place invalid.
143 // Either the loop structure is invalid and this is not a natural loop (in
144 // which case the compiler is buggy somewhere else) or BB is unreachable.
145 BlockUnreachable = true;
146 break;
147 }
148
149 // If this block is ok, check the next one.
150 if (!BlockUnreachable) continue;
151
152 // Otherwise, this block is dead. To clean up the CFG and to allow later
153 // loop transformations to ignore this case, we delete the edges into the
154 // loop by replacing the terminator.
155
156 // Remove PHI entries from the successors.
Nick Lewycky95a0d762008-03-09 05:24:34 +0000157 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
158 (*I)->removePredecessor(BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159
Chris Lattner55fb7932007-10-29 02:30:37 +0000160 // Add a new unreachable instruction before the old terminator.
Nick Lewycky95a0d762008-03-09 05:24:34 +0000161 TerminatorInst *TI = BB->getTerminator();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 new UnreachableInst(TI);
163
164 // Delete the dead terminator.
Chris Lattner55fb7932007-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();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 Changed |= true;
170 }
171
172 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
173 Changed |= ProcessLoop(*I);
174
175 return Changed;
176}
177
178/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
179/// all loops have preheaders.
180///
181bool LoopSimplify::ProcessLoop(Loop *L) {
182 bool Changed = false;
183ReprocessLoop:
184
185 // 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
190 assert(L->getBlocks()[0] == L->getHeader() &&
191 "Header isn't first block in loop?");
192
193 // Does the loop already have a preheader? If so, don't insert one.
194 if (L->getLoopPreheader() == 0) {
195 InsertPreheaderForLoop(L);
196 NumInserted++;
197 Changed = true;
198 }
199
200 // 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
203 // predecessors from outside of the loop, split the edge now.
Devang Patel02451fa2007-08-21 00:31:24 +0000204 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 L->getExitBlocks(ExitBlocks);
206
207 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
208 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
209 E = ExitBlockSet.end(); I != E; ++I) {
210 BasicBlock *ExitBlock = *I;
211 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
212 PI != PE; ++PI)
213 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
214 // allowed.
215 if (!L->contains(*PI)) {
216 RewriteLoopExitBlock(L, ExitBlock);
217 NumInserted++;
218 Changed = true;
219 break;
220 }
221 }
222
223 // If the header has more than two predecessors at this point (from the
224 // preheader and from multiple backedges), we must adjust the loop.
225 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 }
239 }
240
241 // 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.
244 InsertUniqueBackedgeBlock(L);
245 NumInserted++;
246 Changed = true;
247 }
248
249 // 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;
253 for (BasicBlock::iterator I = L->getHeader()->begin();
254 (PN = dyn_cast<PHINode>(I++)); )
255 if (Value *V = PN->hasConstantValue()) {
256 PN->replaceAllUsesWith(V);
257 PN->eraseFromParent();
258 }
259
260 return Changed;
261}
262
263/// SplitBlockPredecessors - Split the specified block into two blocks. We want
264/// to move the predecessors specified in the Preds list to point to the new
265/// block, leaving the remaining predecessors pointing to BB. This method
Chris Lattnera4c2b612008-04-21 00:54:38 +0000266/// updates the SSA PHINode's, AliasAnalysis, DominatorTree and
267/// DominanceFrontier, but no other analyses.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268///
269BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
270 const char *Suffix,
271 const std::vector<BasicBlock*> &Preds) {
272
Chris Lattnera4c2b612008-04-21 00:54:38 +0000273 // Create new basic block, insert right before the original block.
Chris Lattnerd2724962008-04-21 00:23:14 +0000274 BasicBlock *NewBB =
275 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276
Chris Lattnera4c2b612008-04-21 00:54:38 +0000277 // The preheader first gets an unconditional branch to the loop header.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000278 BranchInst *BI = BranchInst::Create(BB, NewBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279
280 // For every PHI node in the block, insert a PHI node into NewBB where the
281 // incoming values from the out of loop edges are moved to NewBB. We have two
282 // possible cases here. If the loop is dead, we just insert dummy entries
283 // into the PHI nodes for the new edge. If the loop is not dead, we move the
284 // incoming edges in BB into new PHI nodes in NewBB.
285 //
Chris Lattnerd2724962008-04-21 00:23:14 +0000286 if (Preds.empty()) { // Is the loop obviously dead?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
288 PHINode *PN = cast<PHINode>(I);
289 // Insert dummy values as the incoming value...
290 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
291 }
Chris Lattnera4c2b612008-04-21 00:54:38 +0000292
293 DT->splitBlock(NewBB);
294 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
295 DF->splitBlock(NewBB);
296
Chris Lattnerd2724962008-04-21 00:23:14 +0000297 return NewBB;
298 }
299
300 // Check to see if the values being merged into the new block need PHI
301 // nodes. If so, insert them.
302 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
303 PHINode *PN = cast<PHINode>(I);
304 ++I;
305
306 // Check to see if all of the values coming in are the same. If so, we
307 // don't need to create a new PHI node.
308 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
309 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
310 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
311 InVal = 0;
312 break;
313 }
314
315 // If the values coming into the block are not the same, we need a PHI.
316 if (InVal == 0) {
317 // Create the new PHI node, insert it into NewBB at the end of the block
318 PHINode *NewPHI =
319 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
320 if (AA) AA->copyValue(PN, NewPHI);
321
322 // Move all of the edges from blocks outside the loop to the new PHI
323 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
324 Value *V = PN->removeIncomingValue(Preds[i], false);
325 NewPHI->addIncoming(V, Preds[i]);
326 }
327 InVal = NewPHI;
328 } else {
329 // Remove all of the edges coming into the PHI nodes from outside of the
330 // block.
331 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
332 PN->removeIncomingValue(Preds[i], false);
333 }
334
335 // Add an incoming value to the PHI node in the loop for the preheader
336 // edge.
337 PN->addIncoming(InVal, NewBB);
338
339 // Can we eliminate this phi node now?
340 if (Value *V = PN->hasConstantValue(true)) {
341 Instruction *I = dyn_cast<Instruction>(V);
342 // If I is in NewBB, the Dominator call will fail, because NewBB isn't
343 // registered in DominatorTree yet. Handle this case explicitly.
344 if (!I || (I->getParent() != NewBB &&
Chris Lattnera4c2b612008-04-21 00:54:38 +0000345 DT->dominates(I, PN))) {
Chris Lattnerd2724962008-04-21 00:23:14 +0000346 PN->replaceAllUsesWith(V);
347 if (AA) AA->deleteValue(PN);
348 BB->getInstList().erase(PN);
349 }
350 }
351 }
352
353 // Now that the PHI nodes are updated, actually move the edges from
354 // Preds to point to NewBB instead of BB.
355 //
356 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
357 TerminatorInst *TI = Preds[i]->getTerminator();
358 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
359 if (TI->getSuccessor(s) == BB)
360 TI->setSuccessor(s, NewBB);
361
362 if (Preds[i]->getUnwindDest() == BB)
363 Preds[i]->setUnwindDest(NewBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000364 }
365
Chris Lattnera4c2b612008-04-21 00:54:38 +0000366 DT->splitBlock(NewBB);
367 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
368 DF->splitBlock(NewBB);
369
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370 return NewBB;
371}
372
373/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
374/// preheader, this method is called to insert one. This method has two phases:
375/// preheader insertion and analysis updating.
376///
377void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
378 BasicBlock *Header = L->getHeader();
379
380 // Compute the set of predecessors of the loop that are not in the loop.
381 std::vector<BasicBlock*> OutsideBlocks;
382 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
383 PI != PE; ++PI)
384 if (!L->contains(*PI)) // Coming in from outside the loop?
385 OutsideBlocks.push_back(*PI); // Keep track of it...
386
387 // Split out the loop pre-header.
388 BasicBlock *NewBB =
389 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
390
391
392 //===--------------------------------------------------------------------===//
393 // Update analysis results now that we have performed the transformation
394 //
395
396 // We know that we have loop information to update... update it now.
397 if (Loop *Parent = L->getParentLoop())
Owen Andersonca0b9d42007-11-27 03:43:35 +0000398 Parent->addBasicBlockToLoop(NewBB, LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
401 // code layout too horribly.
402 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
403}
404
405/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
406/// blocks. This method is used to split exit blocks that have predecessors
407/// outside of the loop.
408BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
409 std::vector<BasicBlock*> LoopBlocks;
410 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
411 if (L->contains(*I))
412 LoopBlocks.push_back(*I);
413
414 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
415 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
416
417 // Update Loop Information - we know that the new block will be in whichever
418 // loop the Exit block is in. Note that it may not be in that immediate loop,
419 // if the successor is some other loop header. In that case, we continue
420 // walking up the loop tree to find a loop that contains both the successor
421 // block and the predecessor block.
422 Loop *SuccLoop = LI->getLoopFor(Exit);
423 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
424 SuccLoop = SuccLoop->getParentLoop();
425 if (SuccLoop)
Owen Andersonca0b9d42007-11-27 03:43:35 +0000426 SuccLoop->addBasicBlockToLoop(NewBB, LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428 return NewBB;
429}
430
431/// AddBlockAndPredsToSet - Add the specified block, and all of its
432/// predecessors, to the specified set, if it's not already in there. Stop
433/// predecessor traversal when we reach StopBlock.
434static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
435 std::set<BasicBlock*> &Blocks) {
436 std::vector<BasicBlock *> WorkList;
437 WorkList.push_back(InputBB);
438 do {
439 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
440 if (Blocks.insert(BB).second && BB != StopBlock)
441 // If BB is not already processed and it is not a stop block then
442 // insert its predecessor in the work list
443 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
444 BasicBlock *WBB = *I;
445 WorkList.push_back(WBB);
446 }
447 } while(!WorkList.empty());
448}
449
450/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
451/// PHI node that tells us how to partition the loops.
452static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorTree *DT,
453 AliasAnalysis *AA) {
454 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
455 PHINode *PN = cast<PHINode>(I);
456 ++I;
457 if (Value *V = PN->hasConstantValue())
458 if (!isa<Instruction>(V) || DT->dominates(cast<Instruction>(V), PN)) {
459 // This is a degenerate PHI already, don't modify it!
460 PN->replaceAllUsesWith(V);
461 if (AA) AA->deleteValue(PN);
462 PN->eraseFromParent();
463 continue;
464 }
465
466 // Scan this PHI node looking for a use of the PHI node by itself.
467 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
468 if (PN->getIncomingValue(i) == PN &&
469 L->contains(PN->getIncomingBlock(i)))
470 // We found something tasty to remove.
471 return PN;
472 }
473 return 0;
474}
475
476// PlaceSplitBlockCarefully - If the block isn't already, move the new block to
477// right after some 'outside block' block. This prevents the preheader from
478// being placed inside the loop body, e.g. when the loop hasn't been rotated.
479void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
480 std::vector<BasicBlock*>&SplitPreds,
481 Loop *L) {
482 // Check to see if NewBB is already well placed.
483 Function::iterator BBI = NewBB; --BBI;
484 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
485 if (&*BBI == SplitPreds[i])
486 return;
487 }
488
489 // If it isn't already after an outside block, move it after one. This is
490 // always good as it makes the uncond branch from the outside block into a
491 // fall-through.
492
493 // Figure out *which* outside block to put this after. Prefer an outside
494 // block that neighbors a BB actually in the loop.
495 BasicBlock *FoundBB = 0;
496 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
497 Function::iterator BBI = SplitPreds[i];
498 if (++BBI != NewBB->getParent()->end() &&
499 L->contains(BBI)) {
500 FoundBB = SplitPreds[i];
501 break;
502 }
503 }
504
505 // If our heuristic for a *good* bb to place this after doesn't find
506 // anything, just pick something. It's likely better than leaving it within
507 // the loop.
508 if (!FoundBB)
509 FoundBB = SplitPreds[0];
510 NewBB->moveAfter(FoundBB);
511}
512
513
514/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
515/// them out into a nested loop. This is important for code that looks like
516/// this:
517///
518/// Loop:
519/// ...
520/// br cond, Loop, Next
521/// ...
522/// br cond2, Loop, Out
523///
524/// To identify this common case, we look at the PHI nodes in the header of the
525/// loop. PHI nodes with unchanging values on one backedge correspond to values
526/// that change in the "outer" loop, but not in the "inner" loop.
527///
528/// If we are able to separate out a loop, return the new outer loop that was
529/// created.
530///
531Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
532 PHINode *PN = FindPHIToPartitionLoops(L, DT, AA);
533 if (PN == 0) return 0; // No known way to partition.
534
535 // Pull out all predecessors that have varying values in the loop. This
536 // handles the case when a PHI node has multiple instances of itself as
537 // arguments.
538 std::vector<BasicBlock*> OuterLoopPreds;
539 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
540 if (PN->getIncomingValue(i) != PN ||
541 !L->contains(PN->getIncomingBlock(i)))
542 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
543
544 BasicBlock *Header = L->getHeader();
545 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
546
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
548 // code layout too horribly.
549 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
550
551 // Create the new outer loop.
552 Loop *NewOuter = new Loop();
553
554 // Change the parent loop to use the outer loop as its child now.
555 if (Loop *Parent = L->getParentLoop())
556 Parent->replaceChildLoopWith(L, NewOuter);
557 else
558 LI->changeTopLevelLoop(L, NewOuter);
559
560 // This block is going to be our new header block: add it to this loop and all
561 // parent loops.
Owen Andersonca0b9d42007-11-27 03:43:35 +0000562 NewOuter->addBasicBlockToLoop(NewBB, LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000563
564 // L is now a subloop of our outer loop.
565 NewOuter->addChildLoop(L);
566
567 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
568 NewOuter->addBlockEntry(L->getBlocks()[i]);
569
570 // Determine which blocks should stay in L and which should be moved out to
571 // the Outer loop now.
572 std::set<BasicBlock*> BlocksInL;
573 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
574 if (DT->dominates(Header, *PI))
575 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
576
577
578 // Scan all of the loop children of L, moving them to OuterLoop if they are
579 // not part of the inner loop.
580 const std::vector<Loop*> &SubLoops = L->getSubLoops();
581 for (size_t I = 0; I != SubLoops.size(); )
582 if (BlocksInL.count(SubLoops[I]->getHeader()))
583 ++I; // Loop remains in L
584 else
585 NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
586
587 // Now that we know which blocks are in L and which need to be moved to
588 // OuterLoop, move any blocks that need it.
589 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
590 BasicBlock *BB = L->getBlocks()[i];
591 if (!BlocksInL.count(BB)) {
592 // Move this block to the parent, updating the exit blocks sets
593 L->removeBlockFromLoop(BB);
594 if ((*LI)[BB] == L)
595 LI->changeLoopFor(BB, NewOuter);
596 --i;
597 }
598 }
599
600 return NewOuter;
601}
602
603
604
605/// InsertUniqueBackedgeBlock - This method is called when the specified loop
606/// has more than one backedge in it. If this occurs, revector all of these
607/// backedges to target a new basic block and have that block branch to the loop
608/// header. This ensures that loops have exactly one backedge.
609///
610void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
611 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
612
613 // Get information about the loop
614 BasicBlock *Preheader = L->getLoopPreheader();
615 BasicBlock *Header = L->getHeader();
616 Function *F = Header->getParent();
617
618 // Figure out which basic blocks contain back-edges to the loop header.
619 std::vector<BasicBlock*> BackedgeBlocks;
620 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
621 if (*I != Preheader) BackedgeBlocks.push_back(*I);
622
623 // Create and insert the new backedge block...
Gabor Greifd6da1d02008-04-06 20:25:17 +0000624 BasicBlock *BEBlock = BasicBlock::Create(Header->getName()+".backedge", F);
625 BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626
627 // Move the new backedge block to right after the last backedge block.
628 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
629 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
630
631 // Now that the block has been inserted into the function, create PHI nodes in
632 // the backedge block which correspond to any PHI nodes in the header block.
633 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
634 PHINode *PN = cast<PHINode>(I);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000635 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".be",
636 BETerminator);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637 NewPN->reserveOperandSpace(BackedgeBlocks.size());
638 if (AA) AA->copyValue(PN, NewPN);
639
640 // Loop over the PHI node, moving all entries except the one for the
641 // preheader over to the new PHI node.
642 unsigned PreheaderIdx = ~0U;
643 bool HasUniqueIncomingValue = true;
644 Value *UniqueValue = 0;
645 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
646 BasicBlock *IBB = PN->getIncomingBlock(i);
647 Value *IV = PN->getIncomingValue(i);
648 if (IBB == Preheader) {
649 PreheaderIdx = i;
650 } else {
651 NewPN->addIncoming(IV, IBB);
652 if (HasUniqueIncomingValue) {
653 if (UniqueValue == 0)
654 UniqueValue = IV;
655 else if (UniqueValue != IV)
656 HasUniqueIncomingValue = false;
657 }
658 }
659 }
660
661 // Delete all of the incoming values from the old PN except the preheader's
662 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
663 if (PreheaderIdx != 0) {
664 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
665 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
666 }
667 // Nuke all entries except the zero'th.
668 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
669 PN->removeIncomingValue(e-i, false);
670
671 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
672 PN->addIncoming(NewPN, BEBlock);
673
674 // As an optimization, if all incoming values in the new PhiNode (which is a
675 // subset of the incoming values of the old PHI node) have the same value,
676 // eliminate the PHI Node.
677 if (HasUniqueIncomingValue) {
678 NewPN->replaceAllUsesWith(UniqueValue);
679 if (AA) AA->deleteValue(NewPN);
680 BEBlock->getInstList().erase(NewPN);
681 }
682 }
683
684 // Now that all of the PHI nodes have been inserted and adjusted, modify the
Nick Lewycky95a0d762008-03-09 05:24:34 +0000685 // backedge blocks to branch to the BEBlock instead of the header.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
687 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
688 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
689 if (TI->getSuccessor(Op) == Header)
690 TI->setSuccessor(Op, BEBlock);
Nick Lewycky95a0d762008-03-09 05:24:34 +0000691
692 if (BackedgeBlocks[i]->getUnwindDest() == Header)
693 BackedgeBlocks[i]->setUnwindDest(BEBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 }
695
696 //===--- Update all analyses which we must preserve now -----------------===//
697
698 // Update Loop Information - we know that this block is now in the current
699 // loop and all parent loops.
Owen Andersonca0b9d42007-11-27 03:43:35 +0000700 L->addBasicBlockToLoop(BEBlock, LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701
702 // Update dominator information
703 DT->splitBlock(BEBlock);
704 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
705 DF->splitBlock(BEBlock);
706}