blob: e6f5e7c39cd329e24035bfd474ac8650e44d3c85 [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 Lattner38acf9e2002-09-26 16:17:31 +000044#include "llvm/Support/CFG.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000045#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000046#include "llvm/ADT/SetOperations.h"
47#include "llvm/ADT/SetVector.h"
48#include "llvm/ADT/Statistic.h"
49#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattner66ea98e2003-12-10 17:20:35 +000050using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000051
Chris Lattnerd216e8b2006-12-19 22:17:40 +000052STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
53STATISTIC(NumNested , "Number of nested loops split out");
Chris Lattner38acf9e2002-09-26 16:17:31 +000054
Chris Lattnerd216e8b2006-12-19 22:17:40 +000055namespace {
Chris Lattner95255282006-06-28 23:17:24 +000056 struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000057 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000058 LoopSimplify() : FunctionPass((intptr_t)&ID) {}
59
Chris Lattnercec5b882005-03-25 06:37:22 +000060 // AA - If we have an alias analysis object to update, this is it, otherwise
61 // this is null.
62 AliasAnalysis *AA;
Chris Lattnerc27e0562006-02-14 22:34:08 +000063 LoopInfo *LI;
Devang Patel0e7f7282007-06-21 17:23:45 +000064 DominatorTree *DT;
Chris Lattner38acf9e2002-09-26 16:17:31 +000065 virtual bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +000066
Chris Lattner38acf9e2002-09-26 16:17:31 +000067 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 // We need loop information to identify the loops...
69 AU.addRequired<LoopInfo>();
Chris Lattner786c5642004-03-13 22:01:26 +000070 AU.addRequired<DominatorTree>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000071
72 AU.addPreserved<LoopInfo>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000073 AU.addPreserved<DominatorTree>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000074 AU.addPreserved<DominanceFrontier>();
Chris Lattner94f40322005-08-10 02:07:32 +000075 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
Chris Lattner38acf9e2002-09-26 16:17:31 +000076 }
Devang Patel58e0ef12007-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
Chris Lattner38acf9e2002-09-26 16:17:31 +000087 private:
88 bool ProcessLoop(Loop *L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000089 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
90 const std::vector<BasicBlock*> &Preds);
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,
96 std::vector<BasicBlock*> &SplitPreds,
97 Loop *L);
Chris Lattner38acf9e2002-09-26 16:17:31 +000098 };
99
Devang Patel19974732007-05-03 01:11:54 +0000100 char LoopSimplify::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000101 RegisterPass<LoopSimplify>
Chris Lattneree2c50c2003-10-12 21:43:28 +0000102 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000103}
104
105// Publically exposed interface to pass...
Chris Lattner66ea98e2003-12-10 17:20:35 +0000106const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
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>();
Chris Lattnercec5b882005-03-25 06:37:22 +0000115 AA = getAnalysisToUpdate<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;
Chris Lattnerfa789462006-08-12 04:51:20 +0000129
130 // Check to see if any successors of this block are non-loop-header loops
131 // that are not the header.
Nick Lewycky529de8a2008-03-09 05:24:34 +0000132 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Chris Lattnerfa789462006-08-12 04:51:20 +0000133 // If this successor is not in a loop, BB is clearly ok.
Nick Lewycky529de8a2008-03-09 05:24:34 +0000134 Loop *L = LI->getLoopFor(*I);
Chris Lattnerfa789462006-08-12 04:51:20 +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 Lewycky529de8a2008-03-09 05:24:34 +0000139 if (L->getHeader() == *I && L->getParentLoop() == 0)
Chris Lattnerfa789462006-08-12 04:51:20 +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 Lewycky529de8a2008-03-09 05:24:34 +0000157 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
158 (*I)->removePredecessor(BB);
Chris Lattnerfa789462006-08-12 04:51:20 +0000159
Chris Lattner3cb63dd2007-10-29 02:30:37 +0000160 // Add a new unreachable instruction before the old terminator.
Nick Lewycky529de8a2008-03-09 05:24:34 +0000161 TerminatorInst *TI = BB->getTerminator();
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()) {
Chris Lattner94f40322005-08-10 02:07:32 +0000256 PN->replaceAllUsesWith(V);
257 PN->eraseFromParent();
258 }
259
Chris Lattner38acf9e2002-09-26 16:17:31 +0000260 return Changed;
261}
262
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000263/// 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
266/// updates the SSA PHINode's, but no other analyses.
267///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000268BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
269 const char *Suffix,
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000270 const std::vector<BasicBlock*> &Preds) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000271
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000272 // Create new basic block, insert right before the original block...
Gabor Greif051a9502008-04-06 20:25:17 +0000273 BasicBlock *NewBB = BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000274
275 // The preheader first gets an unconditional branch to the loop header...
Gabor Greif051a9502008-04-06 20:25:17 +0000276 BranchInst *BI = BranchInst::Create(BB, NewBB);
Misha Brukmanfd939082005-04-21 23:48:37 +0000277
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000278 // For every PHI node in the block, insert a PHI node into NewBB where the
279 // incoming values from the out of loop edges are moved to NewBB. We have two
280 // possible cases here. If the loop is dead, we just insert dummy entries
281 // into the PHI nodes for the new edge. If the loop is not dead, we move the
282 // incoming edges in BB into new PHI nodes in NewBB.
283 //
284 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner0f98e752003-12-19 06:27:08 +0000285 // Check to see if the values being merged into the new block need PHI
286 // nodes. If so, insert them.
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000287 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
288 PHINode *PN = cast<PHINode>(I);
Chris Lattner529b28d2004-04-13 05:05:33 +0000289 ++I;
290
Chris Lattner0f98e752003-12-19 06:27:08 +0000291 // Check to see if all of the values coming in are the same. If so, we
292 // don't need to create a new PHI node.
293 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
294 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
295 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
296 InVal = 0;
297 break;
298 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000299
Chris Lattner0f98e752003-12-19 06:27:08 +0000300 // If the values coming into the block are not the same, we need a PHI.
301 if (InVal == 0) {
Chris Lattner010ba102003-12-09 23:12:55 +0000302 // Create the new PHI node, insert it into NewBB at the end of the block
Gabor Greif051a9502008-04-06 20:25:17 +0000303 PHINode *NewPHI = PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
Chris Lattnercec5b882005-03-25 06:37:22 +0000304 if (AA) AA->copyValue(PN, NewPHI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000305
Chris Lattner010ba102003-12-09 23:12:55 +0000306 // Move all of the edges from blocks outside the loop to the new PHI
307 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Chris Lattner529b28d2004-04-13 05:05:33 +0000308 Value *V = PN->removeIncomingValue(Preds[i], false);
Chris Lattner010ba102003-12-09 23:12:55 +0000309 NewPHI->addIncoming(V, Preds[i]);
310 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000311 InVal = NewPHI;
312 } else {
313 // Remove all of the edges coming into the PHI nodes from outside of the
314 // block.
315 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
316 PN->removeIncomingValue(Preds[i], false);
Chris Lattner010ba102003-12-09 23:12:55 +0000317 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000318
319 // Add an incoming value to the PHI node in the loop for the preheader
320 // edge.
321 PN->addIncoming(InVal, NewBB);
Chris Lattner529b28d2004-04-13 05:05:33 +0000322
323 // Can we eliminate this phi node now?
Chris Lattner5e1b2312005-08-05 00:57:45 +0000324 if (Value *V = PN->hasConstantValue(true)) {
Nick Lewyckya397ce12007-04-08 01:04:30 +0000325 Instruction *I = dyn_cast<Instruction>(V);
Devang Pateldba24132007-06-08 01:50:32 +0000326 // If I is in NewBB, the Dominator call will fail, because NewBB isn't
327 // registered in DominatorTree yet. Handle this case explicitly.
Nick Lewyckya397ce12007-04-08 01:04:30 +0000328 if (!I || (I->getParent() != NewBB &&
Devang Pateldba24132007-06-08 01:50:32 +0000329 getAnalysis<DominatorTree>().dominates(I, PN))) {
Chris Lattnerc30bda72004-10-17 21:22:38 +0000330 PN->replaceAllUsesWith(V);
Chris Lattnercec5b882005-03-25 06:37:22 +0000331 if (AA) AA->deleteValue(PN);
Chris Lattnerc30bda72004-10-17 21:22:38 +0000332 BB->getInstList().erase(PN);
333 }
Chris Lattner529b28d2004-04-13 05:05:33 +0000334 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000335 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000336
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000337 // Now that the PHI nodes are updated, actually move the edges from
338 // Preds to point to NewBB instead of BB.
339 //
340 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
341 TerminatorInst *TI = Preds[i]->getTerminator();
342 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
343 if (TI->getSuccessor(s) == BB)
344 TI->setSuccessor(s, NewBB);
Nick Lewycky529de8a2008-03-09 05:24:34 +0000345
346 if (Preds[i]->getUnwindDest() == BB)
347 Preds[i]->setUnwindDest(NewBB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000348 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000349
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000350 } else { // Otherwise the loop is dead...
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000351 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
352 PHINode *PN = cast<PHINode>(I);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000353 // Insert dummy values as the incoming value...
354 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000355 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000356 }
Devang Patel0e7f7282007-06-21 17:23:45 +0000357
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000358 return NewBB;
359}
360
Chris Lattner38acf9e2002-09-26 16:17:31 +0000361/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
362/// preheader, this method is called to insert one. This method has two phases:
363/// preheader insertion and analysis updating.
364///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000365void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000366 BasicBlock *Header = L->getHeader();
367
368 // Compute the set of predecessors of the loop that are not in the loop.
369 std::vector<BasicBlock*> OutsideBlocks;
370 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
371 PI != PE; ++PI)
Chris Lattner8587eb32006-02-11 02:13:17 +0000372 if (!L->contains(*PI)) // Coming in from outside the loop?
373 OutsideBlocks.push_back(*PI); // Keep track of it...
Misha Brukmanfd939082005-04-21 23:48:37 +0000374
Chris Lattnerc3984572006-09-23 07:40:52 +0000375 // Split out the loop pre-header.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000376 BasicBlock *NewBB =
377 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattnerc3984572006-09-23 07:40:52 +0000378
Misha Brukmanfd939082005-04-21 23:48:37 +0000379
Chris Lattner38acf9e2002-09-26 16:17:31 +0000380 //===--------------------------------------------------------------------===//
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000381 // Update analysis results now that we have performed the transformation
Chris Lattner38acf9e2002-09-26 16:17:31 +0000382 //
Misha Brukmanfd939082005-04-21 23:48:37 +0000383
Chris Lattner38acf9e2002-09-26 16:17:31 +0000384 // We know that we have loop information to update... update it now.
385 if (Loop *Parent = L->getParentLoop())
Owen Andersond735ee82007-11-27 03:43:35 +0000386 Parent->addBasicBlockToLoop(NewBB, LI->getBase());
Chris Lattner9f879cf2003-02-27 22:48:57 +0000387
Devang Patel0e7f7282007-06-21 17:23:45 +0000388 DT->splitBlock(NewBB);
389 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
390 DF->splitBlock(NewBB);
391
Chris Lattner120fce52006-09-23 08:19:21 +0000392 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
393 // code layout too horribly.
394 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000395}
396
Chris Lattner529b28d2004-04-13 05:05:33 +0000397/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
398/// blocks. This method is used to split exit blocks that have predecessors
399/// outside of the loop.
Chris Lattner59fb87d2004-04-18 22:27:10 +0000400BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000401 std::vector<BasicBlock*> LoopBlocks;
402 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
403 if (L->contains(*I))
404 LoopBlocks.push_back(*I);
405
Chris Lattner7e7ad492003-02-27 22:31:07 +0000406 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
407 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
408
Chris Lattnerc27e0562006-02-14 22:34:08 +0000409 // Update Loop Information - we know that the new block will be in whichever
410 // loop the Exit block is in. Note that it may not be in that immediate loop,
411 // if the successor is some other loop header. In that case, we continue
412 // walking up the loop tree to find a loop that contains both the successor
413 // block and the predecessor block.
414 Loop *SuccLoop = LI->getLoopFor(Exit);
415 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
416 SuccLoop = SuccLoop->getParentLoop();
417 if (SuccLoop)
Owen Andersond735ee82007-11-27 03:43:35 +0000418 SuccLoop->addBasicBlockToLoop(NewBB, LI->getBase());
Chris Lattner74cd04e2003-02-28 03:07:54 +0000419
Devang Patel0e7f7282007-06-21 17:23:45 +0000420 // Update Dominator Information
421 DT->splitBlock(NewBB);
422 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
423 DF->splitBlock(NewBB);
424
Chris Lattner59fb87d2004-04-18 22:27:10 +0000425 return NewBB;
Chris Lattner2ab6a732003-10-13 00:37:13 +0000426}
427
Chris Lattner529b28d2004-04-13 05:05:33 +0000428/// AddBlockAndPredsToSet - Add the specified block, and all of its
429/// predecessors, to the specified set, if it's not already in there. Stop
430/// predecessor traversal when we reach StopBlock.
Devang Patel58d7fbf2007-04-20 20:04:37 +0000431static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
Chris Lattner529b28d2004-04-13 05:05:33 +0000432 std::set<BasicBlock*> &Blocks) {
Devang Patel58d7fbf2007-04-20 20:04:37 +0000433 std::vector<BasicBlock *> WorkList;
434 WorkList.push_back(InputBB);
435 do {
436 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
437 if (Blocks.insert(BB).second && BB != StopBlock)
438 // If BB is not already processed and it is not a stop block then
439 // insert its predecessor in the work list
440 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
441 BasicBlock *WBB = *I;
442 WorkList.push_back(WBB);
443 }
444 } while(!WorkList.empty());
Chris Lattner529b28d2004-04-13 05:05:33 +0000445}
446
Chris Lattner1f62f822004-04-13 15:21:18 +0000447/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
448/// PHI node that tells us how to partition the loops.
Devang Pateldba24132007-06-08 01:50:32 +0000449static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorTree *DT,
Owen Andersonad190142007-04-09 22:54:50 +0000450 AliasAnalysis *AA) {
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000451 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
452 PHINode *PN = cast<PHINode>(I);
Chris Lattner1f62f822004-04-13 15:21:18 +0000453 ++I;
Nate Begemana83ba0f2005-08-04 23:24:19 +0000454 if (Value *V = PN->hasConstantValue())
Devang Pateldba24132007-06-08 01:50:32 +0000455 if (!isa<Instruction>(V) || DT->dominates(cast<Instruction>(V), PN)) {
Chris Lattnerc30bda72004-10-17 21:22:38 +0000456 // This is a degenerate PHI already, don't modify it!
457 PN->replaceAllUsesWith(V);
Chris Lattnercec5b882005-03-25 06:37:22 +0000458 if (AA) AA->deleteValue(PN);
Chris Lattnerfee34112005-03-06 21:35:38 +0000459 PN->eraseFromParent();
Chris Lattnerc30bda72004-10-17 21:22:38 +0000460 continue;
461 }
462
463 // Scan this PHI node looking for a use of the PHI node by itself.
464 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
465 if (PN->getIncomingValue(i) == PN &&
466 L->contains(PN->getIncomingBlock(i)))
467 // We found something tasty to remove.
468 return PN;
Chris Lattner1f62f822004-04-13 15:21:18 +0000469 }
470 return 0;
471}
472
Chris Lattner120fce52006-09-23 08:19:21 +0000473// PlaceSplitBlockCarefully - If the block isn't already, move the new block to
474// right after some 'outside block' block. This prevents the preheader from
475// being placed inside the loop body, e.g. when the loop hasn't been rotated.
476void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
477 std::vector<BasicBlock*>&SplitPreds,
478 Loop *L) {
479 // Check to see if NewBB is already well placed.
480 Function::iterator BBI = NewBB; --BBI;
481 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
482 if (&*BBI == SplitPreds[i])
483 return;
484 }
485
486 // If it isn't already after an outside block, move it after one. This is
487 // always good as it makes the uncond branch from the outside block into a
488 // fall-through.
489
490 // Figure out *which* outside block to put this after. Prefer an outside
491 // block that neighbors a BB actually in the loop.
492 BasicBlock *FoundBB = 0;
493 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
494 Function::iterator BBI = SplitPreds[i];
495 if (++BBI != NewBB->getParent()->end() &&
496 L->contains(BBI)) {
497 FoundBB = SplitPreds[i];
498 break;
499 }
500 }
501
502 // If our heuristic for a *good* bb to place this after doesn't find
503 // anything, just pick something. It's likely better than leaving it within
504 // the loop.
505 if (!FoundBB)
506 FoundBB = SplitPreds[0];
507 NewBB->moveAfter(FoundBB);
508}
509
510
Chris Lattner529b28d2004-04-13 05:05:33 +0000511/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
512/// them out into a nested loop. This is important for code that looks like
513/// this:
514///
515/// Loop:
516/// ...
517/// br cond, Loop, Next
518/// ...
519/// br cond2, Loop, Out
520///
521/// To identify this common case, we look at the PHI nodes in the header of the
522/// loop. PHI nodes with unchanging values on one backedge correspond to values
523/// that change in the "outer" loop, but not in the "inner" loop.
524///
525/// If we are able to separate out a loop, return the new outer loop that was
526/// created.
527///
528Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
Devang Pateldba24132007-06-08 01:50:32 +0000529 PHINode *PN = FindPHIToPartitionLoops(L, DT, AA);
Chris Lattner1f62f822004-04-13 15:21:18 +0000530 if (PN == 0) return 0; // No known way to partition.
Chris Lattner529b28d2004-04-13 05:05:33 +0000531
Chris Lattner1f62f822004-04-13 15:21:18 +0000532 // Pull out all predecessors that have varying values in the loop. This
533 // handles the case when a PHI node has multiple instances of itself as
534 // arguments.
Chris Lattner529b28d2004-04-13 05:05:33 +0000535 std::vector<BasicBlock*> OuterLoopPreds;
Chris Lattner1f62f822004-04-13 15:21:18 +0000536 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
537 if (PN->getIncomingValue(i) != PN ||
538 !L->contains(PN->getIncomingBlock(i)))
539 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner529b28d2004-04-13 05:05:33 +0000540
Chris Lattner4b662422004-04-13 16:23:25 +0000541 BasicBlock *Header = L->getHeader();
Chris Lattner529b28d2004-04-13 05:05:33 +0000542 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
543
Devang Patel0e7f7282007-06-21 17:23:45 +0000544 // Update dominator information
545 DT->splitBlock(NewBB);
546 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
547 DF->splitBlock(NewBB);
Chris Lattner529b28d2004-04-13 05:05:33 +0000548
Chris Lattner120fce52006-09-23 08:19:21 +0000549 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
550 // code layout too horribly.
551 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
552
Chris Lattner529b28d2004-04-13 05:05:33 +0000553 // Create the new outer loop.
554 Loop *NewOuter = new Loop();
555
Chris Lattner529b28d2004-04-13 05:05:33 +0000556 // Change the parent loop to use the outer loop as its child now.
557 if (Loop *Parent = L->getParentLoop())
558 Parent->replaceChildLoopWith(L, NewOuter);
559 else
Chris Lattnerc27e0562006-02-14 22:34:08 +0000560 LI->changeTopLevelLoop(L, NewOuter);
Chris Lattner529b28d2004-04-13 05:05:33 +0000561
562 // This block is going to be our new header block: add it to this loop and all
563 // parent loops.
Owen Andersond735ee82007-11-27 03:43:35 +0000564 NewOuter->addBasicBlockToLoop(NewBB, LI->getBase());
Chris Lattner529b28d2004-04-13 05:05:33 +0000565
566 // L is now a subloop of our outer loop.
567 NewOuter->addChildLoop(L);
568
Chris Lattner529b28d2004-04-13 05:05:33 +0000569 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
570 NewOuter->addBlockEntry(L->getBlocks()[i]);
571
572 // Determine which blocks should stay in L and which should be moved out to
573 // the Outer loop now.
Chris Lattner529b28d2004-04-13 05:05:33 +0000574 std::set<BasicBlock*> BlocksInL;
575 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
Devang Pateldba24132007-06-08 01:50:32 +0000576 if (DT->dominates(Header, *PI))
Chris Lattner529b28d2004-04-13 05:05:33 +0000577 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
578
579
580 // Scan all of the loop children of L, moving them to OuterLoop if they are
581 // not part of the inner loop.
David Greenec08fa282007-06-29 02:53:16 +0000582 const std::vector<Loop*> &SubLoops = L->getSubLoops();
583 for (size_t I = 0; I != SubLoops.size(); )
584 if (BlocksInL.count(SubLoops[I]->getHeader()))
Chris Lattner529b28d2004-04-13 05:05:33 +0000585 ++I; // Loop remains in L
586 else
David Greenec08fa282007-06-29 02:53:16 +0000587 NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
Chris Lattner529b28d2004-04-13 05:05:33 +0000588
589 // Now that we know which blocks are in L and which need to be moved to
590 // OuterLoop, move any blocks that need it.
591 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
592 BasicBlock *BB = L->getBlocks()[i];
593 if (!BlocksInL.count(BB)) {
594 // Move this block to the parent, updating the exit blocks sets
595 L->removeBlockFromLoop(BB);
Chris Lattnerc27e0562006-02-14 22:34:08 +0000596 if ((*LI)[BB] == L)
597 LI->changeLoopFor(BB, NewOuter);
Chris Lattner529b28d2004-04-13 05:05:33 +0000598 --i;
599 }
600 }
601
Chris Lattner529b28d2004-04-13 05:05:33 +0000602 return NewOuter;
603}
604
605
606
Chris Lattner2ab6a732003-10-13 00:37:13 +0000607/// InsertUniqueBackedgeBlock - This method is called when the specified loop
608/// has more than one backedge in it. If this occurs, revector all of these
609/// backedges to target a new basic block and have that block branch to the loop
610/// header. This ensures that loops have exactly one backedge.
611///
612void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
613 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
614
615 // Get information about the loop
616 BasicBlock *Preheader = L->getLoopPreheader();
617 BasicBlock *Header = L->getHeader();
618 Function *F = Header->getParent();
619
620 // Figure out which basic blocks contain back-edges to the loop header.
621 std::vector<BasicBlock*> BackedgeBlocks;
622 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
623 if (*I != Preheader) BackedgeBlocks.push_back(*I);
624
625 // Create and insert the new backedge block...
Gabor Greif051a9502008-04-06 20:25:17 +0000626 BasicBlock *BEBlock = BasicBlock::Create(Header->getName()+".backedge", F);
627 BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000628
629 // Move the new backedge block to right after the last backedge block.
630 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
631 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000632
Chris Lattner2ab6a732003-10-13 00:37:13 +0000633 // Now that the block has been inserted into the function, create PHI nodes in
634 // the backedge block which correspond to any PHI nodes in the header block.
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000635 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
636 PHINode *PN = cast<PHINode>(I);
Gabor Greif051a9502008-04-06 20:25:17 +0000637 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".be",
638 BETerminator);
Chris Lattner55517062005-01-29 00:39:08 +0000639 NewPN->reserveOperandSpace(BackedgeBlocks.size());
Chris Lattnercec5b882005-03-25 06:37:22 +0000640 if (AA) AA->copyValue(PN, NewPN);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000641
642 // Loop over the PHI node, moving all entries except the one for the
643 // preheader over to the new PHI node.
644 unsigned PreheaderIdx = ~0U;
645 bool HasUniqueIncomingValue = true;
646 Value *UniqueValue = 0;
647 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
648 BasicBlock *IBB = PN->getIncomingBlock(i);
649 Value *IV = PN->getIncomingValue(i);
650 if (IBB == Preheader) {
651 PreheaderIdx = i;
652 } else {
653 NewPN->addIncoming(IV, IBB);
654 if (HasUniqueIncomingValue) {
655 if (UniqueValue == 0)
656 UniqueValue = IV;
657 else if (UniqueValue != IV)
658 HasUniqueIncomingValue = false;
659 }
660 }
661 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000662
Chris Lattner2ab6a732003-10-13 00:37:13 +0000663 // Delete all of the incoming values from the old PN except the preheader's
664 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
665 if (PreheaderIdx != 0) {
666 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
667 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
668 }
Chris Lattner55517062005-01-29 00:39:08 +0000669 // Nuke all entries except the zero'th.
670 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
671 PN->removeIncomingValue(e-i, false);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000672
673 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
674 PN->addIncoming(NewPN, BEBlock);
675
676 // As an optimization, if all incoming values in the new PhiNode (which is a
677 // subset of the incoming values of the old PHI node) have the same value,
678 // eliminate the PHI Node.
679 if (HasUniqueIncomingValue) {
680 NewPN->replaceAllUsesWith(UniqueValue);
Chris Lattnercec5b882005-03-25 06:37:22 +0000681 if (AA) AA->deleteValue(NewPN);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000682 BEBlock->getInstList().erase(NewPN);
683 }
684 }
685
686 // Now that all of the PHI nodes have been inserted and adjusted, modify the
Nick Lewycky529de8a2008-03-09 05:24:34 +0000687 // backedge blocks to branch to the BEBlock instead of the header.
Chris Lattner2ab6a732003-10-13 00:37:13 +0000688 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
689 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
690 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
691 if (TI->getSuccessor(Op) == Header)
692 TI->setSuccessor(Op, BEBlock);
Nick Lewycky529de8a2008-03-09 05:24:34 +0000693
694 if (BackedgeBlocks[i]->getUnwindDest() == Header)
695 BackedgeBlocks[i]->setUnwindDest(BEBlock);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000696 }
697
698 //===--- Update all analyses which we must preserve now -----------------===//
699
700 // Update Loop Information - we know that this block is now in the current
701 // loop and all parent loops.
Owen Andersond735ee82007-11-27 03:43:35 +0000702 L->addBasicBlockToLoop(BEBlock, LI->getBase());
Chris Lattner2ab6a732003-10-13 00:37:13 +0000703
Devang Patel0e7f7282007-06-21 17:23:45 +0000704 // Update dominator information
705 DT->splitBlock(BEBlock);
706 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
707 DF->splitBlock(BEBlock);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000708}