blob: ab850d58fc6b52ca839215616d2d444fc5c2ca92 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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 Lattner2ef703e2004-03-14 03:59:22 +000037#include "llvm/Constant.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 {
Chris Lattnercec5b882005-03-25 06:37:22 +000057 // AA - If we have an alias analysis object to update, this is it, otherwise
58 // this is null.
59 AliasAnalysis *AA;
Chris Lattnerc27e0562006-02-14 22:34:08 +000060 LoopInfo *LI;
Chris Lattnercec5b882005-03-25 06:37:22 +000061
Chris Lattner38acf9e2002-09-26 16:17:31 +000062 virtual bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +000063
Chris Lattner38acf9e2002-09-26 16:17:31 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 // We need loop information to identify the loops...
66 AU.addRequired<LoopInfo>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000067 AU.addRequired<DominatorSet>();
Chris Lattner786c5642004-03-13 22:01:26 +000068 AU.addRequired<DominatorTree>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000069
70 AU.addPreserved<LoopInfo>();
71 AU.addPreserved<DominatorSet>();
72 AU.addPreserved<ImmediateDominators>();
Chris Lattnerbaec98d2006-01-09 08:03:08 +000073 AU.addPreserved<ETForest>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000074 AU.addPreserved<DominatorTree>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000075 AU.addPreserved<DominanceFrontier>();
Chris Lattner94f40322005-08-10 02:07:32 +000076 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
Chris Lattner38acf9e2002-09-26 16:17:31 +000077 }
78 private:
79 bool ProcessLoop(Loop *L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000080 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
81 const std::vector<BasicBlock*> &Preds);
Chris Lattner59fb87d2004-04-18 22:27:10 +000082 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner38acf9e2002-09-26 16:17:31 +000083 void InsertPreheaderForLoop(Loop *L);
Chris Lattner529b28d2004-04-13 05:05:33 +000084 Loop *SeparateNestedLoop(Loop *L);
Chris Lattner2ab6a732003-10-13 00:37:13 +000085 void InsertUniqueBackedgeBlock(Loop *L);
Chris Lattner120fce52006-09-23 08:19:21 +000086 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
87 std::vector<BasicBlock*> &SplitPreds,
88 Loop *L);
89
Chris Lattner2ab6a732003-10-13 00:37:13 +000090 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
91 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner38acf9e2002-09-26 16:17:31 +000092 };
93
Chris Lattner7f8897f2006-08-27 22:42:52 +000094 RegisterPass<LoopSimplify>
Chris Lattneree2c50c2003-10-12 21:43:28 +000095 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner38acf9e2002-09-26 16:17:31 +000096}
97
98// Publically exposed interface to pass...
Chris Lattner66ea98e2003-12-10 17:20:35 +000099const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
Chris Lattner4b501562004-09-20 04:43:15 +0000100FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner38acf9e2002-09-26 16:17:31 +0000101
Chris Lattner38acf9e2002-09-26 16:17:31 +0000102/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
103/// it in any convenient order) inserting preheaders...
104///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000105bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000106 bool Changed = false;
Chris Lattnerc27e0562006-02-14 22:34:08 +0000107 LI = &getAnalysis<LoopInfo>();
Chris Lattnercec5b882005-03-25 06:37:22 +0000108 AA = getAnalysisToUpdate<AliasAnalysis>();
Chris Lattner38acf9e2002-09-26 16:17:31 +0000109
Chris Lattnerfa789462006-08-12 04:51:20 +0000110 // Check to see that no blocks (other than the header) in loops have
111 // predecessors that are not in loops. This is not valid for natural loops,
112 // but can occur if the blocks are unreachable. Since they are unreachable we
113 // can just shamelessly destroy their terminators to make them not branch into
114 // the loop!
115 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
116 // This case can only occur for unreachable blocks. Blocks that are
117 // unreachable can't be in loops, so filter those blocks out.
118 if (LI->getLoopFor(BB)) continue;
119
120 bool BlockUnreachable = false;
121 TerminatorInst *TI = BB->getTerminator();
122
123 // Check to see if any successors of this block are non-loop-header loops
124 // that are not the header.
125 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
126 // If this successor is not in a loop, BB is clearly ok.
127 Loop *L = LI->getLoopFor(TI->getSuccessor(i));
128 if (!L) continue;
129
130 // If the succ is the loop header, and if L is a top-level loop, then this
131 // is an entrance into a loop through the header, which is also ok.
132 if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
133 continue;
134
135 // Otherwise, this is an entrance into a loop from some place invalid.
136 // Either the loop structure is invalid and this is not a natural loop (in
137 // which case the compiler is buggy somewhere else) or BB is unreachable.
138 BlockUnreachable = true;
139 break;
140 }
141
142 // If this block is ok, check the next one.
143 if (!BlockUnreachable) continue;
144
145 // Otherwise, this block is dead. To clean up the CFG and to allow later
146 // loop transformations to ignore this case, we delete the edges into the
147 // loop by replacing the terminator.
148
149 // Remove PHI entries from the successors.
150 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
151 TI->getSuccessor(i)->removePredecessor(BB);
152
153 // Add a new unreachable instruction.
154 new UnreachableInst(TI);
155
156 // Delete the dead terminator.
157 if (AA) AA->deleteValue(&BB->back());
158 BB->getInstList().pop_back();
159 Changed |= true;
160 }
161
Chris Lattnerc27e0562006-02-14 22:34:08 +0000162 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner329c1c62004-01-08 00:09:44 +0000163 Changed |= ProcessLoop(*I);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000164
165 return Changed;
166}
167
Chris Lattner38acf9e2002-09-26 16:17:31 +0000168/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
169/// all loops have preheaders.
170///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000171bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000172 bool Changed = false;
Chris Lattner3bb46572006-08-12 05:25:00 +0000173ReprocessLoop:
174
Chris Lattner0ab9f962006-02-14 23:06:02 +0000175 // Canonicalize inner loops before outer loops. Inner loop canonicalization
176 // can provide work for the outer loop to canonicalize.
177 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
178 Changed |= ProcessLoop(*I);
179
Chris Lattner2ef703e2004-03-14 03:59:22 +0000180 assert(L->getBlocks()[0] == L->getHeader() &&
181 "Header isn't first block in loop?");
Chris Lattner2ef703e2004-03-14 03:59:22 +0000182
Chris Lattnerfa789462006-08-12 04:51:20 +0000183 // Does the loop already have a preheader? If so, don't insert one.
Chris Lattner38acf9e2002-09-26 16:17:31 +0000184 if (L->getLoopPreheader() == 0) {
185 InsertPreheaderForLoop(L);
186 NumInserted++;
187 Changed = true;
188 }
189
Chris Lattner66ea98e2003-12-10 17:20:35 +0000190 // Next, check to make sure that all exit nodes of the loop only have
191 // predecessors that are inside of the loop. This check guarantees that the
192 // loop preheader/header will dominate the exit blocks. If the exit block has
Chris Lattneree628cf2006-02-12 01:59:10 +0000193 // predecessors from outside of the loop, split the edge now.
194 std::vector<BasicBlock*> ExitBlocks;
195 L->getExitBlocks(ExitBlocks);
Chris Lattnerc27e0562006-02-14 22:34:08 +0000196
Chris Lattneree628cf2006-02-12 01:59:10 +0000197 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerfed22aa2004-07-15 08:20:22 +0000198 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
199 E = ExitBlockSet.end(); I != E; ++I) {
200 BasicBlock *ExitBlock = *I;
Chris Lattnerde7aee72004-07-15 05:36:31 +0000201 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
202 PI != PE; ++PI)
Chris Lattner8587eb32006-02-11 02:13:17 +0000203 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
204 // allowed.
Chris Lattneree628cf2006-02-12 01:59:10 +0000205 if (!L->contains(*PI)) {
Chris Lattnerfed22aa2004-07-15 08:20:22 +0000206 RewriteLoopExitBlock(L, ExitBlock);
Chris Lattnerde7aee72004-07-15 05:36:31 +0000207 NumInserted++;
208 Changed = true;
209 break;
210 }
Chris Lattnerfed22aa2004-07-15 08:20:22 +0000211 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000212
Chris Lattner529b28d2004-04-13 05:05:33 +0000213 // If the header has more than two predecessors at this point (from the
214 // preheader and from multiple backedges), we must adjust the loop.
Chris Lattner3bb46572006-08-12 05:25:00 +0000215 unsigned NumBackedges = L->getNumBackEdges();
216 if (NumBackedges != 1) {
217 // If this is really a nested loop, rip it out into a child loop. Don't do
218 // this for loops with a giant number of backedges, just factor them into a
219 // common backedge instead.
220 if (NumBackedges < 8) {
221 if (Loop *NL = SeparateNestedLoop(L)) {
222 ++NumNested;
223 // This is a big restructuring change, reprocess the whole loop.
224 ProcessLoop(NL);
225 Changed = true;
226 // GCC doesn't tail recursion eliminate this.
227 goto ReprocessLoop;
228 }
Chris Lattner529b28d2004-04-13 05:05:33 +0000229 }
230
Chris Lattner3bb46572006-08-12 05:25:00 +0000231 // If we either couldn't, or didn't want to, identify nesting of the loops,
232 // insert a new block that all backedges target, then make it jump to the
233 // loop header.
Chris Lattner2ab6a732003-10-13 00:37:13 +0000234 InsertUniqueBackedgeBlock(L);
235 NumInserted++;
236 Changed = true;
237 }
238
Chris Lattner94f40322005-08-10 02:07:32 +0000239 // Scan over the PHI nodes in the loop header. Since they now have only two
240 // incoming values (the loop is canonicalized), we may have simplified the PHI
241 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
242 PHINode *PN;
Chris Lattner94f40322005-08-10 02:07:32 +0000243 for (BasicBlock::iterator I = L->getHeader()->begin();
244 (PN = dyn_cast<PHINode>(I++)); )
Chris Lattner98599ba2005-08-10 17:15:20 +0000245 if (Value *V = PN->hasConstantValue()) {
Chris Lattner94f40322005-08-10 02:07:32 +0000246 PN->replaceAllUsesWith(V);
247 PN->eraseFromParent();
248 }
249
Chris Lattner38acf9e2002-09-26 16:17:31 +0000250 return Changed;
251}
252
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000253/// SplitBlockPredecessors - Split the specified block into two blocks. We want
254/// to move the predecessors specified in the Preds list to point to the new
255/// block, leaving the remaining predecessors pointing to BB. This method
256/// updates the SSA PHINode's, but no other analyses.
257///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000258BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
259 const char *Suffix,
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000260 const std::vector<BasicBlock*> &Preds) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000261
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000262 // Create new basic block, insert right before the original block...
Chris Lattnerc24a0762004-02-04 03:58:28 +0000263 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000264
265 // The preheader first gets an unconditional branch to the loop header...
Chris Lattner108e4ab2003-11-21 16:52:05 +0000266 BranchInst *BI = new BranchInst(BB, NewBB);
Misha Brukmanfd939082005-04-21 23:48:37 +0000267
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000268 // For every PHI node in the block, insert a PHI node into NewBB where the
269 // incoming values from the out of loop edges are moved to NewBB. We have two
270 // possible cases here. If the loop is dead, we just insert dummy entries
271 // into the PHI nodes for the new edge. If the loop is not dead, we move the
272 // incoming edges in BB into new PHI nodes in NewBB.
273 //
274 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner0f98e752003-12-19 06:27:08 +0000275 // Check to see if the values being merged into the new block need PHI
276 // nodes. If so, insert them.
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000277 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
278 PHINode *PN = cast<PHINode>(I);
Chris Lattner529b28d2004-04-13 05:05:33 +0000279 ++I;
280
Chris Lattner0f98e752003-12-19 06:27:08 +0000281 // Check to see if all of the values coming in are the same. If so, we
282 // don't need to create a new PHI node.
283 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
284 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
285 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
286 InVal = 0;
287 break;
288 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000289
Chris Lattner0f98e752003-12-19 06:27:08 +0000290 // If the values coming into the block are not the same, we need a PHI.
291 if (InVal == 0) {
Chris Lattner010ba102003-12-09 23:12:55 +0000292 // Create the new PHI node, insert it into NewBB at the end of the block
293 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
Chris Lattnercec5b882005-03-25 06:37:22 +0000294 if (AA) AA->copyValue(PN, NewPHI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000295
Chris Lattner010ba102003-12-09 23:12:55 +0000296 // Move all of the edges from blocks outside the loop to the new PHI
297 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Chris Lattner529b28d2004-04-13 05:05:33 +0000298 Value *V = PN->removeIncomingValue(Preds[i], false);
Chris Lattner010ba102003-12-09 23:12:55 +0000299 NewPHI->addIncoming(V, Preds[i]);
300 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000301 InVal = NewPHI;
302 } else {
303 // Remove all of the edges coming into the PHI nodes from outside of the
304 // block.
305 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
306 PN->removeIncomingValue(Preds[i], false);
Chris Lattner010ba102003-12-09 23:12:55 +0000307 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000308
309 // Add an incoming value to the PHI node in the loop for the preheader
310 // edge.
311 PN->addIncoming(InVal, NewBB);
Chris Lattner529b28d2004-04-13 05:05:33 +0000312
313 // Can we eliminate this phi node now?
Chris Lattner5e1b2312005-08-05 00:57:45 +0000314 if (Value *V = PN->hasConstantValue(true)) {
Chris Lattnerc30bda72004-10-17 21:22:38 +0000315 if (!isa<Instruction>(V) ||
316 getAnalysis<DominatorSet>().dominates(cast<Instruction>(V), PN)) {
317 PN->replaceAllUsesWith(V);
Chris Lattnercec5b882005-03-25 06:37:22 +0000318 if (AA) AA->deleteValue(PN);
Chris Lattnerc30bda72004-10-17 21:22:38 +0000319 BB->getInstList().erase(PN);
320 }
Chris Lattner529b28d2004-04-13 05:05:33 +0000321 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000322 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000323
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000324 // Now that the PHI nodes are updated, actually move the edges from
325 // Preds to point to NewBB instead of BB.
326 //
327 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
328 TerminatorInst *TI = Preds[i]->getTerminator();
329 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
330 if (TI->getSuccessor(s) == BB)
331 TI->setSuccessor(s, NewBB);
332 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000333
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000334 } else { // Otherwise the loop is dead...
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000335 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
336 PHINode *PN = cast<PHINode>(I);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000337 // Insert dummy values as the incoming value...
338 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000339 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000340 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000341 return NewBB;
342}
343
Chris Lattner38acf9e2002-09-26 16:17:31 +0000344/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
345/// preheader, this method is called to insert one. This method has two phases:
346/// preheader insertion and analysis updating.
347///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000348void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000349 BasicBlock *Header = L->getHeader();
350
351 // Compute the set of predecessors of the loop that are not in the loop.
352 std::vector<BasicBlock*> OutsideBlocks;
353 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
354 PI != PE; ++PI)
Chris Lattner8587eb32006-02-11 02:13:17 +0000355 if (!L->contains(*PI)) // Coming in from outside the loop?
356 OutsideBlocks.push_back(*PI); // Keep track of it...
Misha Brukmanfd939082005-04-21 23:48:37 +0000357
Chris Lattnerc3984572006-09-23 07:40:52 +0000358 // Split out the loop pre-header.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000359 BasicBlock *NewBB =
360 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattnerc3984572006-09-23 07:40:52 +0000361
Misha Brukmanfd939082005-04-21 23:48:37 +0000362
Chris Lattner38acf9e2002-09-26 16:17:31 +0000363 //===--------------------------------------------------------------------===//
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000364 // Update analysis results now that we have performed the transformation
Chris Lattner38acf9e2002-09-26 16:17:31 +0000365 //
Misha Brukmanfd939082005-04-21 23:48:37 +0000366
Chris Lattner38acf9e2002-09-26 16:17:31 +0000367 // We know that we have loop information to update... update it now.
368 if (Loop *Parent = L->getParentLoop())
Chris Lattnerc27e0562006-02-14 22:34:08 +0000369 Parent->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner9f879cf2003-02-27 22:48:57 +0000370
Chris Lattnerc3984572006-09-23 07:40:52 +0000371 UpdateDomInfoForRevectoredPreds(NewBB, OutsideBlocks);
Chris Lattner120fce52006-09-23 08:19:21 +0000372
373 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
374 // code layout too horribly.
375 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000376}
377
Chris Lattner529b28d2004-04-13 05:05:33 +0000378/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
379/// blocks. This method is used to split exit blocks that have predecessors
380/// outside of the loop.
Chris Lattner59fb87d2004-04-18 22:27:10 +0000381BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000382 std::vector<BasicBlock*> LoopBlocks;
383 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
384 if (L->contains(*I))
385 LoopBlocks.push_back(*I);
386
Chris Lattner7e7ad492003-02-27 22:31:07 +0000387 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
388 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
389
Chris Lattnerc27e0562006-02-14 22:34:08 +0000390 // Update Loop Information - we know that the new block will be in whichever
391 // loop the Exit block is in. Note that it may not be in that immediate loop,
392 // if the successor is some other loop header. In that case, we continue
393 // walking up the loop tree to find a loop that contains both the successor
394 // block and the predecessor block.
395 Loop *SuccLoop = LI->getLoopFor(Exit);
396 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
397 SuccLoop = SuccLoop->getParentLoop();
398 if (SuccLoop)
399 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner74cd04e2003-02-28 03:07:54 +0000400
Chris Lattner2ab6a732003-10-13 00:37:13 +0000401 // Update dominator information (set, immdom, domtree, and domfrontier)
402 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
Chris Lattner59fb87d2004-04-18 22:27:10 +0000403 return NewBB;
Chris Lattner2ab6a732003-10-13 00:37:13 +0000404}
405
Chris Lattner529b28d2004-04-13 05:05:33 +0000406/// AddBlockAndPredsToSet - Add the specified block, and all of its
407/// predecessors, to the specified set, if it's not already in there. Stop
408/// predecessor traversal when we reach StopBlock.
409static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
410 std::set<BasicBlock*> &Blocks) {
411 if (!Blocks.insert(BB).second) return; // already processed.
412 if (BB == StopBlock) return; // Stop here!
413
414 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
415 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
416}
417
Chris Lattner1f62f822004-04-13 15:21:18 +0000418/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
419/// PHI node that tells us how to partition the loops.
Chris Lattnercec5b882005-03-25 06:37:22 +0000420static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorSet &DS,
421 AliasAnalysis *AA) {
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000422 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
423 PHINode *PN = cast<PHINode>(I);
Chris Lattner1f62f822004-04-13 15:21:18 +0000424 ++I;
Nate Begemana83ba0f2005-08-04 23:24:19 +0000425 if (Value *V = PN->hasConstantValue())
Chris Lattnerc30bda72004-10-17 21:22:38 +0000426 if (!isa<Instruction>(V) || DS.dominates(cast<Instruction>(V), PN)) {
427 // This is a degenerate PHI already, don't modify it!
428 PN->replaceAllUsesWith(V);
Chris Lattnercec5b882005-03-25 06:37:22 +0000429 if (AA) AA->deleteValue(PN);
Chris Lattnerfee34112005-03-06 21:35:38 +0000430 PN->eraseFromParent();
Chris Lattnerc30bda72004-10-17 21:22:38 +0000431 continue;
432 }
433
434 // Scan this PHI node looking for a use of the PHI node by itself.
435 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
436 if (PN->getIncomingValue(i) == PN &&
437 L->contains(PN->getIncomingBlock(i)))
438 // We found something tasty to remove.
439 return PN;
Chris Lattner1f62f822004-04-13 15:21:18 +0000440 }
441 return 0;
442}
443
Chris Lattner120fce52006-09-23 08:19:21 +0000444// PlaceSplitBlockCarefully - If the block isn't already, move the new block to
445// right after some 'outside block' block. This prevents the preheader from
446// being placed inside the loop body, e.g. when the loop hasn't been rotated.
447void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
448 std::vector<BasicBlock*>&SplitPreds,
449 Loop *L) {
450 // Check to see if NewBB is already well placed.
451 Function::iterator BBI = NewBB; --BBI;
452 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
453 if (&*BBI == SplitPreds[i])
454 return;
455 }
456
457 // If it isn't already after an outside block, move it after one. This is
458 // always good as it makes the uncond branch from the outside block into a
459 // fall-through.
460
461 // Figure out *which* outside block to put this after. Prefer an outside
462 // block that neighbors a BB actually in the loop.
463 BasicBlock *FoundBB = 0;
464 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
465 Function::iterator BBI = SplitPreds[i];
466 if (++BBI != NewBB->getParent()->end() &&
467 L->contains(BBI)) {
468 FoundBB = SplitPreds[i];
469 break;
470 }
471 }
472
473 // If our heuristic for a *good* bb to place this after doesn't find
474 // anything, just pick something. It's likely better than leaving it within
475 // the loop.
476 if (!FoundBB)
477 FoundBB = SplitPreds[0];
478 NewBB->moveAfter(FoundBB);
479}
480
481
Chris Lattner529b28d2004-04-13 05:05:33 +0000482/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
483/// them out into a nested loop. This is important for code that looks like
484/// this:
485///
486/// Loop:
487/// ...
488/// br cond, Loop, Next
489/// ...
490/// br cond2, Loop, Out
491///
492/// To identify this common case, we look at the PHI nodes in the header of the
493/// loop. PHI nodes with unchanging values on one backedge correspond to values
494/// that change in the "outer" loop, but not in the "inner" loop.
495///
496/// If we are able to separate out a loop, return the new outer loop that was
497/// created.
498///
499Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
Chris Lattnercec5b882005-03-25 06:37:22 +0000500 PHINode *PN = FindPHIToPartitionLoops(L, getAnalysis<DominatorSet>(), AA);
Chris Lattner1f62f822004-04-13 15:21:18 +0000501 if (PN == 0) return 0; // No known way to partition.
Chris Lattner529b28d2004-04-13 05:05:33 +0000502
Chris Lattner1f62f822004-04-13 15:21:18 +0000503 // Pull out all predecessors that have varying values in the loop. This
504 // handles the case when a PHI node has multiple instances of itself as
505 // arguments.
Chris Lattner529b28d2004-04-13 05:05:33 +0000506 std::vector<BasicBlock*> OuterLoopPreds;
Chris Lattner1f62f822004-04-13 15:21:18 +0000507 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
508 if (PN->getIncomingValue(i) != PN ||
509 !L->contains(PN->getIncomingBlock(i)))
510 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner529b28d2004-04-13 05:05:33 +0000511
Chris Lattner4b662422004-04-13 16:23:25 +0000512 BasicBlock *Header = L->getHeader();
Chris Lattner529b28d2004-04-13 05:05:33 +0000513 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
514
515 // Update dominator information (set, immdom, domtree, and domfrontier)
516 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
517
Chris Lattner120fce52006-09-23 08:19:21 +0000518 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
519 // code layout too horribly.
520 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
521
Chris Lattner529b28d2004-04-13 05:05:33 +0000522 // Create the new outer loop.
523 Loop *NewOuter = new Loop();
524
Chris Lattner529b28d2004-04-13 05:05:33 +0000525 // Change the parent loop to use the outer loop as its child now.
526 if (Loop *Parent = L->getParentLoop())
527 Parent->replaceChildLoopWith(L, NewOuter);
528 else
Chris Lattnerc27e0562006-02-14 22:34:08 +0000529 LI->changeTopLevelLoop(L, NewOuter);
Chris Lattner529b28d2004-04-13 05:05:33 +0000530
531 // This block is going to be our new header block: add it to this loop and all
532 // parent loops.
Chris Lattnerc27e0562006-02-14 22:34:08 +0000533 NewOuter->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner529b28d2004-04-13 05:05:33 +0000534
535 // L is now a subloop of our outer loop.
536 NewOuter->addChildLoop(L);
537
Chris Lattner529b28d2004-04-13 05:05:33 +0000538 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
539 NewOuter->addBlockEntry(L->getBlocks()[i]);
540
541 // Determine which blocks should stay in L and which should be moved out to
542 // the Outer loop now.
543 DominatorSet &DS = getAnalysis<DominatorSet>();
544 std::set<BasicBlock*> BlocksInL;
545 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
546 if (DS.dominates(Header, *PI))
547 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
548
549
550 // Scan all of the loop children of L, moving them to OuterLoop if they are
551 // not part of the inner loop.
552 for (Loop::iterator I = L->begin(); I != L->end(); )
553 if (BlocksInL.count((*I)->getHeader()))
554 ++I; // Loop remains in L
555 else
556 NewOuter->addChildLoop(L->removeChildLoop(I));
557
558 // Now that we know which blocks are in L and which need to be moved to
559 // OuterLoop, move any blocks that need it.
560 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
561 BasicBlock *BB = L->getBlocks()[i];
562 if (!BlocksInL.count(BB)) {
563 // Move this block to the parent, updating the exit blocks sets
564 L->removeBlockFromLoop(BB);
Chris Lattnerc27e0562006-02-14 22:34:08 +0000565 if ((*LI)[BB] == L)
566 LI->changeLoopFor(BB, NewOuter);
Chris Lattner529b28d2004-04-13 05:05:33 +0000567 --i;
568 }
569 }
570
Chris Lattner529b28d2004-04-13 05:05:33 +0000571 return NewOuter;
572}
573
574
575
Chris Lattner2ab6a732003-10-13 00:37:13 +0000576/// InsertUniqueBackedgeBlock - This method is called when the specified loop
577/// has more than one backedge in it. If this occurs, revector all of these
578/// backedges to target a new basic block and have that block branch to the loop
579/// header. This ensures that loops have exactly one backedge.
580///
581void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
582 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
583
584 // Get information about the loop
585 BasicBlock *Preheader = L->getLoopPreheader();
586 BasicBlock *Header = L->getHeader();
587 Function *F = Header->getParent();
588
589 // Figure out which basic blocks contain back-edges to the loop header.
590 std::vector<BasicBlock*> BackedgeBlocks;
591 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
592 if (*I != Preheader) BackedgeBlocks.push_back(*I);
593
594 // Create and insert the new backedge block...
595 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattner108e4ab2003-11-21 16:52:05 +0000596 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000597
598 // Move the new backedge block to right after the last backedge block.
599 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
600 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000601
Chris Lattner2ab6a732003-10-13 00:37:13 +0000602 // Now that the block has been inserted into the function, create PHI nodes in
603 // the backedge block which correspond to any PHI nodes in the header block.
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000604 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
605 PHINode *PN = cast<PHINode>(I);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000606 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
607 BETerminator);
Chris Lattner55517062005-01-29 00:39:08 +0000608 NewPN->reserveOperandSpace(BackedgeBlocks.size());
Chris Lattnercec5b882005-03-25 06:37:22 +0000609 if (AA) AA->copyValue(PN, NewPN);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000610
611 // Loop over the PHI node, moving all entries except the one for the
612 // preheader over to the new PHI node.
613 unsigned PreheaderIdx = ~0U;
614 bool HasUniqueIncomingValue = true;
615 Value *UniqueValue = 0;
616 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
617 BasicBlock *IBB = PN->getIncomingBlock(i);
618 Value *IV = PN->getIncomingValue(i);
619 if (IBB == Preheader) {
620 PreheaderIdx = i;
621 } else {
622 NewPN->addIncoming(IV, IBB);
623 if (HasUniqueIncomingValue) {
624 if (UniqueValue == 0)
625 UniqueValue = IV;
626 else if (UniqueValue != IV)
627 HasUniqueIncomingValue = false;
628 }
629 }
630 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000631
Chris Lattner2ab6a732003-10-13 00:37:13 +0000632 // Delete all of the incoming values from the old PN except the preheader's
633 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
634 if (PreheaderIdx != 0) {
635 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
636 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
637 }
Chris Lattner55517062005-01-29 00:39:08 +0000638 // Nuke all entries except the zero'th.
639 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
640 PN->removeIncomingValue(e-i, false);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000641
642 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
643 PN->addIncoming(NewPN, BEBlock);
644
645 // As an optimization, if all incoming values in the new PhiNode (which is a
646 // subset of the incoming values of the old PHI node) have the same value,
647 // eliminate the PHI Node.
648 if (HasUniqueIncomingValue) {
649 NewPN->replaceAllUsesWith(UniqueValue);
Chris Lattnercec5b882005-03-25 06:37:22 +0000650 if (AA) AA->deleteValue(NewPN);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000651 BEBlock->getInstList().erase(NewPN);
652 }
653 }
654
655 // Now that all of the PHI nodes have been inserted and adjusted, modify the
656 // backedge blocks to just to the BEBlock instead of the header.
657 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
658 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
659 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
660 if (TI->getSuccessor(Op) == Header)
661 TI->setSuccessor(Op, BEBlock);
662 }
663
664 //===--- Update all analyses which we must preserve now -----------------===//
665
666 // Update Loop Information - we know that this block is now in the current
667 // loop and all parent loops.
Chris Lattnerc27e0562006-02-14 22:34:08 +0000668 L->addBasicBlockToLoop(BEBlock, *LI);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000669
Chris Lattner2ab6a732003-10-13 00:37:13 +0000670 // Update dominator information (set, immdom, domtree, and domfrontier)
671 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
672}
673
674/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
675/// different kinds of dominator information (dominator sets, immediate
676/// dominators, dominator trees, and dominance frontiers) after a new block has
677/// been added to the CFG.
678///
Chris Lattner4f02fc22004-02-05 21:12:24 +0000679/// This only supports the case when an existing block (known as "NewBBSucc"),
680/// had some of its predecessors factored into a new basic block. This
Chris Lattner2ab6a732003-10-13 00:37:13 +0000681/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner4f02fc22004-02-05 21:12:24 +0000682/// unconditional branch to NewBBSucc, and moves some predecessors of
683/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
684/// PredBlocks, even though they are the same as
685/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattner2ab6a732003-10-13 00:37:13 +0000686///
687void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
688 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000689 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattner2ab6a732003-10-13 00:37:13 +0000690 assert(succ_begin(NewBB) != succ_end(NewBB) &&
691 ++succ_begin(NewBB) == succ_end(NewBB) &&
692 "NewBB should have a single successor!");
Chris Lattner4f02fc22004-02-05 21:12:24 +0000693 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000694 DominatorSet &DS = getAnalysis<DominatorSet>();
695
Chris Lattner4f303bd2004-04-01 19:06:07 +0000696 // Update dominator information... The blocks that dominate NewBB are the
697 // intersection of the dominators of predecessors, plus the block itself.
698 //
699 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
Chris Lattnerc3984572006-09-23 07:40:52 +0000700 {
701 unsigned i, e = PredBlocks.size();
702 // It is possible for some preds to not be reachable, and thus have empty
703 // dominator sets (all blocks must dom themselves, so no domset would
704 // otherwise be empty). If we see any of these, don't intersect with them,
705 // as that would certainly leave the resultant set empty.
706 for (i = 1; NewBBDomSet.empty(); ++i) {
707 assert(i != e && "Didn't find reachable pred?");
708 NewBBDomSet = DS.getDominators(PredBlocks[i]);
709 }
710
711 // Intersect the rest of the non-empty sets.
712 for (; i != e; ++i) {
713 const DominatorSet::DomSetType &PredDS = DS.getDominators(PredBlocks[i]);
714 if (!PredDS.empty())
715 set_intersect(NewBBDomSet, PredDS);
716 }
717 NewBBDomSet.insert(NewBB); // All blocks dominate themselves.
718 DS.addBasicBlock(NewBB, NewBBDomSet);
719 }
Chris Lattner4f303bd2004-04-01 19:06:07 +0000720
Chris Lattner4f02fc22004-02-05 21:12:24 +0000721 // The newly inserted basic block will dominate existing basic blocks iff the
722 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
723 // the non-pred blocks, then they all must be the same block!
Chris Lattner4f303bd2004-04-01 19:06:07 +0000724 //
Chris Lattner4f02fc22004-02-05 21:12:24 +0000725 bool NewBBDominatesNewBBSucc = true;
726 {
727 BasicBlock *OnePred = PredBlocks[0];
Chris Lattnerc3984572006-09-23 07:40:52 +0000728 unsigned i, e = PredBlocks.size();
729 for (i = 1; !DS.isReachable(OnePred); ++i) {
730 assert(i != e && "Didn't find reachable pred?");
731 OnePred = PredBlocks[i];
732 }
733
734 for (; i != e; ++i)
735 if (PredBlocks[i] != OnePred && DS.isReachable(PredBlocks[i])) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000736 NewBBDominatesNewBBSucc = false;
737 break;
738 }
739
740 if (NewBBDominatesNewBBSucc)
741 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
742 PI != E; ++PI)
Chris Lattner99dcc1d2004-02-05 23:20:59 +0000743 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000744 NewBBDominatesNewBBSucc = false;
745 break;
746 }
747 }
748
Chris Lattner4f303bd2004-04-01 19:06:07 +0000749 // The other scenario where the new block can dominate its successors are when
750 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
751 // already.
752 if (!NewBBDominatesNewBBSucc) {
753 NewBBDominatesNewBBSucc = true;
754 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
755 PI != E; ++PI)
756 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
757 NewBBDominatesNewBBSucc = false;
758 break;
759 }
760 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000761
Chris Lattner4f02fc22004-02-05 21:12:24 +0000762 // If NewBB dominates some blocks, then it will dominate all blocks that
Chris Lattner3e0b8702004-02-05 22:33:26 +0000763 // NewBBSucc does.
Chris Lattner4f02fc22004-02-05 21:12:24 +0000764 if (NewBBDominatesNewBBSucc) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000765 Function *F = NewBB->getParent();
766 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner3e0b8702004-02-05 22:33:26 +0000767 if (DS.dominates(NewBBSucc, I))
Chris Lattner4f02fc22004-02-05 21:12:24 +0000768 DS.addDominator(I, NewBB);
769 }
770
Chris Lattnerc3984572006-09-23 07:40:52 +0000771 // Update immediate dominator information if we have it.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000772 BasicBlock *NewBBIDom = 0;
773 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000774 // To find the immediate dominator of the new exit node, we trace up the
775 // immediate dominators of a predecessor until we find a basic block that
776 // dominates the exit block.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000777 //
Chris Lattnerc3984572006-09-23 07:40:52 +0000778 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor.
779
780 // Find a reachable pred.
781 for (unsigned i = 1; !DS.isReachable(Dom); ++i) {
782 assert(i != PredBlocks.size() && "Didn't find reachable pred!");
783 Dom = PredBlocks[i];
784 }
785
786 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000787 assert(Dom != 0 && "No shared dominator found???");
788 Dom = ID->get(Dom);
789 }
790
791 // Set the immediate dominator now...
792 ID->addNewBlock(NewBB, Dom);
793 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
Chris Lattner4f02fc22004-02-05 21:12:24 +0000794
795 // If NewBB strictly dominates other blocks, we need to update their idom's
796 // now. The only block that need adjustment is the NewBBSucc block, whose
797 // idom should currently be set to PredBlocks[0].
Chris Lattner4edf6c02004-04-01 19:21:46 +0000798 if (NewBBDominatesNewBBSucc)
Chris Lattner4f02fc22004-02-05 21:12:24 +0000799 ID->setImmediateDominator(NewBBSucc, NewBB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000800 }
801
802 // Update DominatorTree information if it is active.
803 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000804 // If we don't have ImmediateDominator info around, calculate the idom as
805 // above.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000806 DominatorTree::Node *NewBBIDomNode;
807 if (NewBBIDom) {
808 NewBBIDomNode = DT->getNode(NewBBIDom);
809 } else {
Chris Lattnerc3984572006-09-23 07:40:52 +0000810 // Scan all the pred blocks that were pulled out. Any individual one may
811 // actually be unreachable, which would mean it doesn't have dom info.
812 NewBBIDomNode = 0;
813 for (unsigned i = 0; !NewBBIDomNode; ++i) {
814 assert(i != PredBlocks.size() && "No reachable preds?");
815 NewBBIDomNode = DT->getNode(PredBlocks[i]);
816 }
817
Chris Lattnerc444a422003-09-11 16:26:13 +0000818 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000819 NewBBIDomNode = NewBBIDomNode->getIDom();
820 assert(NewBBIDomNode && "No shared dominator found??");
821 }
Chris Lattnerbaec98d2006-01-09 08:03:08 +0000822 NewBBIDom = NewBBIDomNode->getBlock();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000823 }
824
Chris Lattner4f02fc22004-02-05 21:12:24 +0000825 // Create the new dominator tree node... and set the idom of NewBB.
826 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
827
828 // If NewBB strictly dominates other blocks, then it is now the immediate
829 // dominator of NewBBSucc. Update the dominator tree as appropriate.
830 if (NewBBDominatesNewBBSucc) {
831 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
Chris Lattner4f02fc22004-02-05 21:12:24 +0000832 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
833 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000834 }
835
Chris Lattnerbaec98d2006-01-09 08:03:08 +0000836 // Update ET-Forest information if it is active.
837 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
838 EF->addNewBlock(NewBB, NewBBIDom);
839 if (NewBBDominatesNewBBSucc)
840 EF->setImmediateDominator(NewBBSucc, NewBB);
841 }
842
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000843 // Update dominance frontier information...
844 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
Chris Lattner4b662422004-04-13 16:23:25 +0000845 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
846 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
847 // a predecessor of.
Chris Lattner4f02fc22004-02-05 21:12:24 +0000848 if (NewBBDominatesNewBBSucc) {
849 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
850 if (DFI != DF->end()) {
851 DominanceFrontier::DomSetType Set = DFI->second;
852 // Filter out stuff in Set that we do not dominate a predecessor of.
853 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
854 E = Set.end(); SetI != E;) {
855 bool DominatesPred = false;
856 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
857 PI != E; ++PI)
858 if (DS.dominates(NewBB, *PI))
859 DominatesPred = true;
860 if (!DominatesPred)
861 Set.erase(SetI++);
862 else
863 ++SetI;
864 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000865
Chris Lattner4f02fc22004-02-05 21:12:24 +0000866 DF->addBasicBlock(NewBB, Set);
867 }
868
869 } else {
870 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
871 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
872 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
873 DominanceFrontier::DomSetType NewDFSet;
874 NewDFSet.insert(NewBBSucc);
875 DF->addBasicBlock(NewBB, NewDFSet);
Chris Lattner4b662422004-04-13 16:23:25 +0000876 }
Chris Lattner2ab6a732003-10-13 00:37:13 +0000877
Chris Lattner4b662422004-04-13 16:23:25 +0000878 // Now we must loop over all of the dominance frontiers in the function,
879 // replacing occurrences of NewBBSucc with NewBB in some cases. All
880 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
881 // their dominance frontier must be updated to contain NewBB instead.
882 //
883 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
884 BasicBlock *Pred = PredBlocks[i];
885 // Get all of the dominators of the predecessor...
886 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
887 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
888 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
889 BasicBlock *PredDom = *PDI;
Misha Brukmanfd939082005-04-21 23:48:37 +0000890
Chris Lattner4b662422004-04-13 16:23:25 +0000891 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
892 // dominate NewBBSucc but did dominate a predecessor of it. Now we
893 // change this entry to include NewBB in the DF instead of NewBBSucc.
894 DominanceFrontier::iterator DFI = DF->find(PredDom);
895 assert(DFI != DF->end() && "No dominance frontier for node?");
896 if (DFI->second.count(NewBBSucc)) {
897 // If NewBBSucc should not stay in our dominator frontier, remove it.
898 // We remove it unless there is a predecessor of NewBBSucc that we
899 // dominate, but we don't strictly dominate NewBBSucc.
900 bool ShouldRemove = true;
901 if (PredDom == NewBBSucc || !DS.dominates(PredDom, NewBBSucc)) {
902 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
903 // Check to see if it dominates any predecessors of NewBBSucc.
904 for (pred_iterator PI = pred_begin(NewBBSucc),
905 E = pred_end(NewBBSucc); PI != E; ++PI)
906 if (DS.dominates(PredDom, *PI)) {
907 ShouldRemove = false;
908 break;
909 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000910 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000911
Chris Lattner4b662422004-04-13 16:23:25 +0000912 if (ShouldRemove)
913 DF->removeFromFrontier(DFI, NewBBSucc);
914 DF->addToFrontier(DFI, NewBB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000915 }
916 }
917 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000918 }
Chris Lattner38acf9e2002-09-26 16:17:31 +0000919}
Brian Gaeked0fde302003-11-11 22:41:34 +0000920