blob: ada9cfd3f1c89ed155022a8b6b6a3c93ee814910 [file] [log] [blame]
Chris Lattner67a98012003-10-12 21:44:18 +00001//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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
35#include "llvm/Transforms/Scalar.h"
Chris Lattner2ef703e2004-03-14 03:59:22 +000036#include "llvm/Constant.h"
Chris Lattner38acf9e2002-09-26 16:17:31 +000037#include "llvm/iTerminators.h"
38#include "llvm/iPHINode.h"
Chris Lattner2ef703e2004-03-14 03:59:22 +000039#include "llvm/Function.h"
40#include "llvm/Type.h"
Chris Lattner0f98e752003-12-19 06:27:08 +000041#include "llvm/Analysis/Dominators.h"
42#include "llvm/Analysis/LoopInfo.h"
Chris Lattner38acf9e2002-09-26 16:17:31 +000043#include "llvm/Support/CFG.h"
Chris Lattner529b28d2004-04-13 05:05:33 +000044#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000045#include "Support/SetOperations.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000046#include "Support/Statistic.h"
Chris Lattner74cd04e2003-02-28 03:07:54 +000047#include "Support/DepthFirstIterator.h"
Chris Lattner66ea98e2003-12-10 17:20:35 +000048using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000049
Chris Lattner38acf9e2002-09-26 16:17:31 +000050namespace {
Chris Lattneree2c50c2003-10-12 21:43:28 +000051 Statistic<>
Chris Lattner66ea98e2003-12-10 17:20:35 +000052 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
Chris Lattner529b28d2004-04-13 05:05:33 +000053 Statistic<>
54 NumNested("loopsimplify", "Number of nested loops split out");
Chris Lattner38acf9e2002-09-26 16:17:31 +000055
Chris Lattneree2c50c2003-10-12 21:43:28 +000056 struct LoopSimplify : public FunctionPass {
Chris Lattner38acf9e2002-09-26 16:17:31 +000057 virtual bool runOnFunction(Function &F);
58
59 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60 // We need loop information to identify the loops...
61 AU.addRequired<LoopInfo>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000062 AU.addRequired<DominatorSet>();
Chris Lattner786c5642004-03-13 22:01:26 +000063 AU.addRequired<DominatorTree>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000064
65 AU.addPreserved<LoopInfo>();
66 AU.addPreserved<DominatorSet>();
67 AU.addPreserved<ImmediateDominators>();
68 AU.addPreserved<DominatorTree>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000069 AU.addPreserved<DominanceFrontier>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000070 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
71 }
72 private:
73 bool ProcessLoop(Loop *L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000074 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
75 const std::vector<BasicBlock*> &Preds);
76 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner38acf9e2002-09-26 16:17:31 +000077 void InsertPreheaderForLoop(Loop *L);
Chris Lattner529b28d2004-04-13 05:05:33 +000078 Loop *SeparateNestedLoop(Loop *L);
Chris Lattner2ab6a732003-10-13 00:37:13 +000079 void InsertUniqueBackedgeBlock(Loop *L);
80
81 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
82 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner38acf9e2002-09-26 16:17:31 +000083 };
84
Chris Lattneree2c50c2003-10-12 21:43:28 +000085 RegisterOpt<LoopSimplify>
86 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner38acf9e2002-09-26 16:17:31 +000087}
88
89// Publically exposed interface to pass...
Chris Lattner66ea98e2003-12-10 17:20:35 +000090const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
91Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner38acf9e2002-09-26 16:17:31 +000092
Chris Lattner38acf9e2002-09-26 16:17:31 +000093/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
94/// it in any convenient order) inserting preheaders...
95///
Chris Lattneree2c50c2003-10-12 21:43:28 +000096bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner38acf9e2002-09-26 16:17:31 +000097 bool Changed = false;
98 LoopInfo &LI = getAnalysis<LoopInfo>();
99
Chris Lattner329c1c62004-01-08 00:09:44 +0000100 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
101 Changed |= ProcessLoop(*I);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000102
103 return Changed;
104}
105
106
107/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
108/// all loops have preheaders.
109///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000110bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000111 bool Changed = false;
112
Chris Lattner2ef703e2004-03-14 03:59:22 +0000113 // Check to see that no blocks (other than the header) in the loop have
114 // predecessors that are not in the loop. This is not valid for natural
115 // loops, but can occur if the blocks are unreachable. Since they are
116 // unreachable we can just shamelessly destroy their terminators to make them
117 // not branch into the loop!
118 assert(L->getBlocks()[0] == L->getHeader() &&
119 "Header isn't first block in loop?");
120 for (unsigned i = 1, e = L->getBlocks().size(); i != e; ++i) {
121 BasicBlock *LoopBB = L->getBlocks()[i];
122 Retry:
123 for (pred_iterator PI = pred_begin(LoopBB), E = pred_end(LoopBB);
124 PI != E; ++PI)
125 if (!L->contains(*PI)) {
126 // This predecessor is not in the loop. Kill its terminator!
127 BasicBlock *DeadBlock = *PI;
128 for (succ_iterator SI = succ_begin(DeadBlock), E = succ_end(DeadBlock);
129 SI != E; ++SI)
130 (*SI)->removePredecessor(DeadBlock); // Remove PHI node entries
131
132 // Delete the dead terminator.
133 DeadBlock->getInstList().pop_back();
134
135 Value *RetVal = 0;
136 if (LoopBB->getParent()->getReturnType() != Type::VoidTy)
137 RetVal = Constant::getNullValue(LoopBB->getParent()->getReturnType());
138 new ReturnInst(RetVal, DeadBlock);
139 goto Retry; // We just invalidated the pred_iterator. Retry.
140 }
141 }
142
Chris Lattner38acf9e2002-09-26 16:17:31 +0000143 // Does the loop already have a preheader? If so, don't modify the loop...
144 if (L->getLoopPreheader() == 0) {
145 InsertPreheaderForLoop(L);
146 NumInserted++;
147 Changed = true;
148 }
149
Chris Lattner66ea98e2003-12-10 17:20:35 +0000150 // Next, check to make sure that all exit nodes of the loop only have
151 // predecessors that are inside of the loop. This check guarantees that the
152 // loop preheader/header will dominate the exit blocks. If the exit block has
153 // predecessors from outside of the loop, split the edge now.
154 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i) {
155 BasicBlock *ExitBlock = L->getExitBlocks()[i];
156 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
157 PI != PE; ++PI)
158 if (!L->contains(*PI)) {
159 RewriteLoopExitBlock(L, ExitBlock);
160 NumInserted++;
161 Changed = true;
162 break;
163 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000164 }
165
Chris Lattner529b28d2004-04-13 05:05:33 +0000166 // If the header has more than two predecessors at this point (from the
167 // preheader and from multiple backedges), we must adjust the loop.
Chris Lattner2ab6a732003-10-13 00:37:13 +0000168 if (L->getNumBackEdges() != 1) {
Chris Lattner529b28d2004-04-13 05:05:33 +0000169 // If this is really a nested loop, rip it out into a child loop.
170 if (Loop *NL = SeparateNestedLoop(L)) {
171 ++NumNested;
172 // This is a big restructuring change, reprocess the whole loop.
173 ProcessLoop(NL);
174 return true;
175 }
176
Chris Lattner2ab6a732003-10-13 00:37:13 +0000177 InsertUniqueBackedgeBlock(L);
178 NumInserted++;
179 Changed = true;
180 }
181
Chris Lattner329c1c62004-01-08 00:09:44 +0000182 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
183 Changed |= ProcessLoop(*I);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000184 return Changed;
185}
186
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000187/// SplitBlockPredecessors - Split the specified block into two blocks. We want
188/// to move the predecessors specified in the Preds list to point to the new
189/// block, leaving the remaining predecessors pointing to BB. This method
190/// updates the SSA PHINode's, but no other analyses.
191///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000192BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
193 const char *Suffix,
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000194 const std::vector<BasicBlock*> &Preds) {
195
196 // Create new basic block, insert right before the original block...
Chris Lattnerc24a0762004-02-04 03:58:28 +0000197 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000198
199 // The preheader first gets an unconditional branch to the loop header...
Chris Lattner108e4ab2003-11-21 16:52:05 +0000200 BranchInst *BI = new BranchInst(BB, NewBB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000201
202 // For every PHI node in the block, insert a PHI node into NewBB where the
203 // incoming values from the out of loop edges are moved to NewBB. We have two
204 // possible cases here. If the loop is dead, we just insert dummy entries
205 // into the PHI nodes for the new edge. If the loop is not dead, we move the
206 // incoming edges in BB into new PHI nodes in NewBB.
207 //
208 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner0f98e752003-12-19 06:27:08 +0000209 // Check to see if the values being merged into the new block need PHI
210 // nodes. If so, insert them.
211 for (BasicBlock::iterator I = BB->begin();
Chris Lattner529b28d2004-04-13 05:05:33 +0000212 PHINode *PN = dyn_cast<PHINode>(I); ) {
213 ++I;
214
Chris Lattner0f98e752003-12-19 06:27:08 +0000215 // Check to see if all of the values coming in are the same. If so, we
216 // don't need to create a new PHI node.
217 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
218 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
219 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
220 InVal = 0;
221 break;
222 }
223
224 // If the values coming into the block are not the same, we need a PHI.
225 if (InVal == 0) {
Chris Lattner010ba102003-12-09 23:12:55 +0000226 // Create the new PHI node, insert it into NewBB at the end of the block
227 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
228
229 // Move all of the edges from blocks outside the loop to the new PHI
230 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Chris Lattner529b28d2004-04-13 05:05:33 +0000231 Value *V = PN->removeIncomingValue(Preds[i], false);
Chris Lattner010ba102003-12-09 23:12:55 +0000232 NewPHI->addIncoming(V, Preds[i]);
233 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000234 InVal = NewPHI;
235 } else {
236 // Remove all of the edges coming into the PHI nodes from outside of the
237 // block.
238 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
239 PN->removeIncomingValue(Preds[i], false);
Chris Lattner010ba102003-12-09 23:12:55 +0000240 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000241
242 // Add an incoming value to the PHI node in the loop for the preheader
243 // edge.
244 PN->addIncoming(InVal, NewBB);
Chris Lattner529b28d2004-04-13 05:05:33 +0000245
246 // Can we eliminate this phi node now?
247 if (Value *V = hasConstantValue(PN)) {
248 PN->replaceAllUsesWith(V);
249 BB->getInstList().erase(PN);
250 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000251 }
252
253 // Now that the PHI nodes are updated, actually move the edges from
254 // Preds to point to NewBB instead of BB.
255 //
256 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
257 TerminatorInst *TI = Preds[i]->getTerminator();
258 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
259 if (TI->getSuccessor(s) == BB)
260 TI->setSuccessor(s, NewBB);
261 }
262
263 } else { // Otherwise the loop is dead...
264 for (BasicBlock::iterator I = BB->begin();
Chris Lattnere408e252003-04-23 16:37:45 +0000265 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000266 // Insert dummy values as the incoming value...
267 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
268 }
269 return NewBB;
270}
271
Chris Lattner8f6396e2003-05-12 22:04:34 +0000272// ChangeExitBlock - This recursive function is used to change any exit blocks
273// that use OldExit to use NewExit instead. This is recursive because children
274// may need to be processed as well.
275//
276static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) {
277 if (L->hasExitBlock(OldExit)) {
278 L->changeExitBlock(OldExit, NewExit);
Chris Lattner329c1c62004-01-08 00:09:44 +0000279 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
280 ChangeExitBlock(*I, OldExit, NewExit);
Chris Lattner8f6396e2003-05-12 22:04:34 +0000281 }
282}
283
Chris Lattner38acf9e2002-09-26 16:17:31 +0000284
285/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
286/// preheader, this method is called to insert one. This method has two phases:
287/// preheader insertion and analysis updating.
288///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000289void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000290 BasicBlock *Header = L->getHeader();
291
292 // Compute the set of predecessors of the loop that are not in the loop.
293 std::vector<BasicBlock*> OutsideBlocks;
294 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
295 PI != PE; ++PI)
296 if (!L->contains(*PI)) // Coming in from outside the loop?
297 OutsideBlocks.push_back(*PI); // Keep track of it...
298
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000299 // Split out the loop pre-header
300 BasicBlock *NewBB =
301 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000302
Chris Lattner38acf9e2002-09-26 16:17:31 +0000303 //===--------------------------------------------------------------------===//
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000304 // Update analysis results now that we have performed the transformation
Chris Lattner38acf9e2002-09-26 16:17:31 +0000305 //
306
307 // We know that we have loop information to update... update it now.
308 if (Loop *Parent = L->getParentLoop())
309 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner9f879cf2003-02-27 22:48:57 +0000310
311 // If the header for the loop used to be an exit node for another loop, then
312 // we need to update this to know that the loop-preheader is now the exit
313 // node. Note that the only loop that could have our header as an exit node
Chris Lattner8f6396e2003-05-12 22:04:34 +0000314 // is a sibling loop, ie, one with the same parent loop, or one if it's
315 // children.
316 //
Chris Lattner329c1c62004-01-08 00:09:44 +0000317 LoopInfo::iterator ParentLoops, ParentLoopsE;
318 if (Loop *Parent = L->getParentLoop()) {
319 ParentLoops = Parent->begin();
320 ParentLoopsE = Parent->end();
321 } else { // Must check top-level loops...
322 ParentLoops = getAnalysis<LoopInfo>().begin();
323 ParentLoopsE = getAnalysis<LoopInfo>().end();
324 }
Chris Lattner9f879cf2003-02-27 22:48:57 +0000325
Chris Lattner8f6396e2003-05-12 22:04:34 +0000326 // Loop over all sibling loops, performing the substitution (recursively to
327 // include child loops)...
Chris Lattner329c1c62004-01-08 00:09:44 +0000328 for (; ParentLoops != ParentLoopsE; ++ParentLoops)
329 ChangeExitBlock(*ParentLoops, Header, NewBB);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000330
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000331 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
Chris Lattner786c5642004-03-13 22:01:26 +0000332 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner85ebd542004-03-16 06:00:15 +0000333
334
335 // Update the dominator tree information.
336 // The immediate dominator of the preheader is the immediate dominator of
337 // the old header.
338 DominatorTree::Node *PHDomTreeNode =
339 DT.createNewNode(NewBB, DT.getNode(Header)->getIDom());
340
341 // Change the header node so that PNHode is the new immediate dominator
342 DT.changeImmediateDominator(DT.getNode(Header), PHDomTreeNode);
Chris Lattner786c5642004-03-13 22:01:26 +0000343
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000344 {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000345 // The blocks that dominate NewBB are the blocks that dominate Header,
346 // minus Header, plus NewBB.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000347 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000348 DomSet.erase(Header); // Header does not dominate us...
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000349 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner4d018922002-09-29 21:41:38 +0000350
351 // The newly created basic block dominates all nodes dominated by Header.
Chris Lattner85ebd542004-03-16 06:00:15 +0000352 for (df_iterator<DominatorTree::Node*> DFI = df_begin(PHDomTreeNode),
353 E = df_end(PHDomTreeNode); DFI != E; ++DFI)
354 DS.addDominator((*DFI)->getBlock(), NewBB);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000355 }
356
357 // Update immediate dominator information if we have it...
358 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
359 // Whatever i-dominated the header node now immediately dominates NewBB
360 ID->addNewBlock(NewBB, ID->get(Header));
361
362 // The preheader now is the immediate dominator for the header node...
363 ID->setImmediateDominator(Header, NewBB);
364 }
365
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000366 // Update dominance frontier information...
367 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
368 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
369 // everything that Header does, and it strictly dominates Header in
370 // addition.
371 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
372 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
373 NewDFSet.erase(Header);
374 DF->addBasicBlock(NewBB, NewDFSet);
375
376 // Now we must loop over all of the dominance frontiers in the function,
Misha Brukmandfa5f832003-09-09 21:54:45 +0000377 // replacing occurrences of Header with NewBB in some cases. If a block
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000378 // dominates a (now) predecessor of NewBB, but did not strictly dominate
379 // Header, it will have Header in it's DF set, but should now have NewBB in
380 // its set.
381 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
382 // Get all of the dominators of the predecessor...
383 const DominatorSet::DomSetType &PredDoms =
384 DS.getDominators(OutsideBlocks[i]);
385 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
386 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
387 BasicBlock *PredDom = *PDI;
388 // If the loop header is in DF(PredDom), then PredDom didn't dominate
389 // the header but did dominate a predecessor outside of the loop. Now
390 // we change this entry to include the preheader in the DF instead of
391 // the header.
392 DominanceFrontier::iterator DFI = DF->find(PredDom);
393 assert(DFI != DF->end() && "No dominance frontier for node?");
394 if (DFI->second.count(Header)) {
395 DF->removeFromFrontier(DFI, Header);
396 DF->addToFrontier(DFI, NewBB);
397 }
398 }
399 }
400 }
401}
402
Chris Lattner529b28d2004-04-13 05:05:33 +0000403/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
404/// blocks. This method is used to split exit blocks that have predecessors
405/// outside of the loop.
Chris Lattneree2c50c2003-10-12 21:43:28 +0000406void LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000407 DominatorSet &DS = getAnalysis<DominatorSet>();
Chris Lattner7e7ad492003-02-27 22:31:07 +0000408 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
409 != L->getExitBlocks().end() && "Not a current exit block!");
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000410
411 std::vector<BasicBlock*> LoopBlocks;
412 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
413 if (L->contains(*I))
414 LoopBlocks.push_back(*I);
415
Chris Lattner7e7ad492003-02-27 22:31:07 +0000416 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
417 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
418
Chris Lattner69269ac2003-02-27 21:50:19 +0000419 // Update Loop Information - we know that the new block will be in the parent
420 // loop of L.
421 if (Loop *Parent = L->getParentLoop())
422 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner74cd04e2003-02-28 03:07:54 +0000423
424 // Replace any instances of Exit with NewBB in this and any nested loops...
425 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
Chris Lattner63159382003-02-28 16:54:17 +0000426 if (I->hasExitBlock(Exit))
427 I->changeExitBlock(Exit, NewBB); // Update exit block information
Chris Lattner69269ac2003-02-27 21:50:19 +0000428
Chris Lattner2ab6a732003-10-13 00:37:13 +0000429 // Update dominator information (set, immdom, domtree, and domfrontier)
430 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
431}
432
Chris Lattner529b28d2004-04-13 05:05:33 +0000433/// AddBlockAndPredsToSet - Add the specified block, and all of its
434/// predecessors, to the specified set, if it's not already in there. Stop
435/// predecessor traversal when we reach StopBlock.
436static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
437 std::set<BasicBlock*> &Blocks) {
438 if (!Blocks.insert(BB).second) return; // already processed.
439 if (BB == StopBlock) return; // Stop here!
440
441 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
442 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
443}
444
445static void ReplaceExitBlocksOfLoopAndParents(Loop *L, BasicBlock *Old,
446 BasicBlock *New) {
447 if (!L->hasExitBlock(Old)) return;
448 L->changeExitBlock(Old, New);
449 ReplaceExitBlocksOfLoopAndParents(L->getParentLoop(), Old, New);
450}
451
452/// VerifyExitBlocks - This is a function which can be useful for hacking on the
453/// LoopSimplify Code.
454static void VerifyExitBlocks(Loop *L) {
455 std::vector<BasicBlock*> ExitBlocks;
456 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
457 BasicBlock *BB = L->getBlocks()[i];
458 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
459 if (!L->contains(*SI))
460 ExitBlocks.push_back(*SI);
461 }
462
463 std::vector<BasicBlock*> EB = L->getExitBlocks();
464 std::sort(EB.begin(), EB.end());
465 std::sort(ExitBlocks.begin(), ExitBlocks.end());
466 assert(EB == ExitBlocks && "Exit blocks were incorrectly updated!");
467
468 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
469 VerifyExitBlocks(*I);
470}
471
Chris Lattner1f62f822004-04-13 15:21:18 +0000472/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
473/// PHI node that tells us how to partition the loops.
474static PHINode *FindPHIToPartitionLoops(Loop *L) {
475 for (BasicBlock::iterator I = L->getHeader()->begin();
476 PHINode *PN = dyn_cast<PHINode>(I); ) {
477 ++I;
478 if (Value *V = hasConstantValue(PN)) {
479 // This is a degenerate PHI already, don't modify it!
480 PN->replaceAllUsesWith(V);
481 PN->getParent()->getInstList().erase(PN);
482 } else {
483 // Scan this PHI node looking for a use of the PHI node by itself.
484 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
485 if (PN->getIncomingValue(i) == PN &&
486 L->contains(PN->getIncomingBlock(i)))
487 // We found something tasty to remove.
488 return PN;
489 }
490 }
491 return 0;
492}
493
Chris Lattner529b28d2004-04-13 05:05:33 +0000494/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
495/// them out into a nested loop. This is important for code that looks like
496/// this:
497///
498/// Loop:
499/// ...
500/// br cond, Loop, Next
501/// ...
502/// br cond2, Loop, Out
503///
504/// To identify this common case, we look at the PHI nodes in the header of the
505/// loop. PHI nodes with unchanging values on one backedge correspond to values
506/// that change in the "outer" loop, but not in the "inner" loop.
507///
508/// If we are able to separate out a loop, return the new outer loop that was
509/// created.
510///
511Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
Chris Lattner1f62f822004-04-13 15:21:18 +0000512 PHINode *PN = FindPHIToPartitionLoops(L);
513 if (PN == 0) return 0; // No known way to partition.
Chris Lattner529b28d2004-04-13 05:05:33 +0000514
Chris Lattner1f62f822004-04-13 15:21:18 +0000515 // Pull out all predecessors that have varying values in the loop. This
516 // handles the case when a PHI node has multiple instances of itself as
517 // arguments.
Chris Lattner529b28d2004-04-13 05:05:33 +0000518 std::vector<BasicBlock*> OuterLoopPreds;
Chris Lattner1f62f822004-04-13 15:21:18 +0000519 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
520 if (PN->getIncomingValue(i) != PN ||
521 !L->contains(PN->getIncomingBlock(i)))
522 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner529b28d2004-04-13 05:05:33 +0000523
Chris Lattner4b662422004-04-13 16:23:25 +0000524 BasicBlock *Header = L->getHeader();
Chris Lattner529b28d2004-04-13 05:05:33 +0000525 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
526
527 // Update dominator information (set, immdom, domtree, and domfrontier)
528 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
529
530 // Create the new outer loop.
531 Loop *NewOuter = new Loop();
532
533 LoopInfo &LI = getAnalysis<LoopInfo>();
534
535 // Change the parent loop to use the outer loop as its child now.
536 if (Loop *Parent = L->getParentLoop())
537 Parent->replaceChildLoopWith(L, NewOuter);
538 else
539 LI.changeTopLevelLoop(L, NewOuter);
540
541 // This block is going to be our new header block: add it to this loop and all
542 // parent loops.
543 NewOuter->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
544
545 // L is now a subloop of our outer loop.
546 NewOuter->addChildLoop(L);
547
548 // Add all of L's exit blocks to the outer loop.
549 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i)
550 NewOuter->addExitBlock(L->getExitBlocks()[i]);
551
552 // Add temporary exit block entries for NewBB. Add one for each edge in L
553 // that goes to NewBB.
554 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB); PI != E; ++PI)
555 if (L->contains(*PI))
556 L->addExitBlock(NewBB);
557
558 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
559 NewOuter->addBlockEntry(L->getBlocks()[i]);
560
561 // Determine which blocks should stay in L and which should be moved out to
562 // the Outer loop now.
563 DominatorSet &DS = getAnalysis<DominatorSet>();
564 std::set<BasicBlock*> BlocksInL;
565 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
566 if (DS.dominates(Header, *PI))
567 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
568
569
570 // Scan all of the loop children of L, moving them to OuterLoop if they are
571 // not part of the inner loop.
572 for (Loop::iterator I = L->begin(); I != L->end(); )
573 if (BlocksInL.count((*I)->getHeader()))
574 ++I; // Loop remains in L
575 else
576 NewOuter->addChildLoop(L->removeChildLoop(I));
577
578 // Now that we know which blocks are in L and which need to be moved to
579 // OuterLoop, move any blocks that need it.
580 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
581 BasicBlock *BB = L->getBlocks()[i];
582 if (!BlocksInL.count(BB)) {
583 // Move this block to the parent, updating the exit blocks sets
584 L->removeBlockFromLoop(BB);
585 if (LI[BB] == L)
586 LI.changeLoopFor(BB, NewOuter);
587 --i;
588 }
589 }
590
591 // Check all subloops of this loop, replacing any exit blocks that got
592 // revectored with the new basic block.
593 for (pred_iterator I = pred_begin(NewBB), E = pred_end(NewBB); I != E; ++I)
594 if (NewOuter->contains(*I)) {
595 // Change any exit blocks that used to go to Header to go to NewBB
596 // instead.
597 ReplaceExitBlocksOfLoopAndParents((Loop*)LI[*I], Header, NewBB);
598 }
599
600 //VerifyExitBlocks(NewOuter);
601 return NewOuter;
602}
603
604
605
Chris Lattner2ab6a732003-10-13 00:37:13 +0000606/// InsertUniqueBackedgeBlock - This method is called when the specified loop
607/// has more than one backedge in it. If this occurs, revector all of these
608/// backedges to target a new basic block and have that block branch to the loop
609/// header. This ensures that loops have exactly one backedge.
610///
611void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
612 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
613
614 // Get information about the loop
615 BasicBlock *Preheader = L->getLoopPreheader();
616 BasicBlock *Header = L->getHeader();
617 Function *F = Header->getParent();
618
619 // Figure out which basic blocks contain back-edges to the loop header.
620 std::vector<BasicBlock*> BackedgeBlocks;
621 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
622 if (*I != Preheader) BackedgeBlocks.push_back(*I);
623
624 // Create and insert the new backedge block...
625 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattner108e4ab2003-11-21 16:52:05 +0000626 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000627
628 // Move the new backedge block to right after the last backedge block.
629 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
630 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
631
632 // Now that the block has been inserted into the function, create PHI nodes in
633 // the backedge block which correspond to any PHI nodes in the header block.
634 for (BasicBlock::iterator I = Header->begin();
635 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
636 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
637 BETerminator);
638 NewPN->op_reserve(2*BackedgeBlocks.size());
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 PN->op_erase(PN->op_begin()+2, PN->op_end());
668
669 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
670 PN->addIncoming(NewPN, BEBlock);
671
672 // As an optimization, if all incoming values in the new PhiNode (which is a
673 // subset of the incoming values of the old PHI node) have the same value,
674 // eliminate the PHI Node.
675 if (HasUniqueIncomingValue) {
676 NewPN->replaceAllUsesWith(UniqueValue);
677 BEBlock->getInstList().erase(NewPN);
678 }
679 }
680
681 // Now that all of the PHI nodes have been inserted and adjusted, modify the
682 // backedge blocks to just to the BEBlock instead of the header.
683 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
684 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
685 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
686 if (TI->getSuccessor(Op) == Header)
687 TI->setSuccessor(Op, BEBlock);
688 }
689
690 //===--- Update all analyses which we must preserve now -----------------===//
691
692 // Update Loop Information - we know that this block is now in the current
693 // loop and all parent loops.
694 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
695
696 // Replace any instances of Exit with NewBB in this and any nested loops...
697 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
698 if (I->hasExitBlock(Header))
699 I->changeExitBlock(Header, BEBlock); // Update exit block information
700
701 // Update dominator information (set, immdom, domtree, and domfrontier)
702 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
703}
704
705/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
706/// different kinds of dominator information (dominator sets, immediate
707/// dominators, dominator trees, and dominance frontiers) after a new block has
708/// been added to the CFG.
709///
Chris Lattner4f02fc22004-02-05 21:12:24 +0000710/// This only supports the case when an existing block (known as "NewBBSucc"),
711/// had some of its predecessors factored into a new basic block. This
Chris Lattner2ab6a732003-10-13 00:37:13 +0000712/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner4f02fc22004-02-05 21:12:24 +0000713/// unconditional branch to NewBBSucc, and moves some predecessors of
714/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
715/// PredBlocks, even though they are the same as
716/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattner2ab6a732003-10-13 00:37:13 +0000717///
718void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
719 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000720 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattner2ab6a732003-10-13 00:37:13 +0000721 assert(succ_begin(NewBB) != succ_end(NewBB) &&
722 ++succ_begin(NewBB) == succ_end(NewBB) &&
723 "NewBB should have a single successor!");
Chris Lattner4f02fc22004-02-05 21:12:24 +0000724 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000725 DominatorSet &DS = getAnalysis<DominatorSet>();
726
Chris Lattner4f303bd2004-04-01 19:06:07 +0000727 // Update dominator information... The blocks that dominate NewBB are the
728 // intersection of the dominators of predecessors, plus the block itself.
729 //
730 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
731 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
732 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
733 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
734 DS.addBasicBlock(NewBB, NewBBDomSet);
735
Chris Lattner4f02fc22004-02-05 21:12:24 +0000736 // The newly inserted basic block will dominate existing basic blocks iff the
737 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
738 // the non-pred blocks, then they all must be the same block!
Chris Lattner4f303bd2004-04-01 19:06:07 +0000739 //
Chris Lattner4f02fc22004-02-05 21:12:24 +0000740 bool NewBBDominatesNewBBSucc = true;
741 {
742 BasicBlock *OnePred = PredBlocks[0];
743 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
744 if (PredBlocks[i] != OnePred) {
745 NewBBDominatesNewBBSucc = false;
746 break;
747 }
748
749 if (NewBBDominatesNewBBSucc)
750 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
751 PI != E; ++PI)
Chris Lattner99dcc1d2004-02-05 23:20:59 +0000752 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000753 NewBBDominatesNewBBSucc = false;
754 break;
755 }
756 }
757
Chris Lattner4f303bd2004-04-01 19:06:07 +0000758 // The other scenario where the new block can dominate its successors are when
759 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
760 // already.
761 if (!NewBBDominatesNewBBSucc) {
762 NewBBDominatesNewBBSucc = true;
763 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
764 PI != E; ++PI)
765 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
766 NewBBDominatesNewBBSucc = false;
767 break;
768 }
769 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000770
Chris Lattner4f02fc22004-02-05 21:12:24 +0000771 // If NewBB dominates some blocks, then it will dominate all blocks that
Chris Lattner3e0b8702004-02-05 22:33:26 +0000772 // NewBBSucc does.
Chris Lattner4f02fc22004-02-05 21:12:24 +0000773 if (NewBBDominatesNewBBSucc) {
774 BasicBlock *PredBlock = PredBlocks[0];
775 Function *F = NewBB->getParent();
776 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner3e0b8702004-02-05 22:33:26 +0000777 if (DS.dominates(NewBBSucc, I))
Chris Lattner4f02fc22004-02-05 21:12:24 +0000778 DS.addDominator(I, NewBB);
779 }
780
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000781 // Update immediate dominator information if we have it...
782 BasicBlock *NewBBIDom = 0;
783 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000784 // To find the immediate dominator of the new exit node, we trace up the
785 // immediate dominators of a predecessor until we find a basic block that
786 // dominates the exit block.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000787 //
Chris Lattner2ab6a732003-10-13 00:37:13 +0000788 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000789 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
790 assert(Dom != 0 && "No shared dominator found???");
791 Dom = ID->get(Dom);
792 }
793
794 // Set the immediate dominator now...
795 ID->addNewBlock(NewBB, Dom);
796 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
Chris Lattner4f02fc22004-02-05 21:12:24 +0000797
798 // If NewBB strictly dominates other blocks, we need to update their idom's
799 // now. The only block that need adjustment is the NewBBSucc block, whose
800 // idom should currently be set to PredBlocks[0].
Chris Lattner4edf6c02004-04-01 19:21:46 +0000801 if (NewBBDominatesNewBBSucc)
Chris Lattner4f02fc22004-02-05 21:12:24 +0000802 ID->setImmediateDominator(NewBBSucc, NewBB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000803 }
804
805 // Update DominatorTree information if it is active.
806 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000807 // If we don't have ImmediateDominator info around, calculate the idom as
808 // above.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000809 DominatorTree::Node *NewBBIDomNode;
810 if (NewBBIDom) {
811 NewBBIDomNode = DT->getNode(NewBBIDom);
812 } else {
Chris Lattner2ab6a732003-10-13 00:37:13 +0000813 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
Chris Lattnerc444a422003-09-11 16:26:13 +0000814 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000815 NewBBIDomNode = NewBBIDomNode->getIDom();
816 assert(NewBBIDomNode && "No shared dominator found??");
817 }
818 }
819
Chris Lattner4f02fc22004-02-05 21:12:24 +0000820 // Create the new dominator tree node... and set the idom of NewBB.
821 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
822
823 // If NewBB strictly dominates other blocks, then it is now the immediate
824 // dominator of NewBBSucc. Update the dominator tree as appropriate.
825 if (NewBBDominatesNewBBSucc) {
826 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
Chris Lattner4f02fc22004-02-05 21:12:24 +0000827 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
828 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000829 }
830
831 // Update dominance frontier information...
832 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
Chris Lattner4b662422004-04-13 16:23:25 +0000833 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
834 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
835 // a predecessor of.
Chris Lattner4f02fc22004-02-05 21:12:24 +0000836 if (NewBBDominatesNewBBSucc) {
837 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
838 if (DFI != DF->end()) {
839 DominanceFrontier::DomSetType Set = DFI->second;
840 // Filter out stuff in Set that we do not dominate a predecessor of.
841 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
842 E = Set.end(); SetI != E;) {
843 bool DominatesPred = false;
844 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
845 PI != E; ++PI)
846 if (DS.dominates(NewBB, *PI))
847 DominatesPred = true;
848 if (!DominatesPred)
849 Set.erase(SetI++);
850 else
851 ++SetI;
852 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000853
Chris Lattner4f02fc22004-02-05 21:12:24 +0000854 DF->addBasicBlock(NewBB, Set);
855 }
856
857 } else {
858 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
859 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
860 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
861 DominanceFrontier::DomSetType NewDFSet;
862 NewDFSet.insert(NewBBSucc);
863 DF->addBasicBlock(NewBB, NewDFSet);
Chris Lattner4b662422004-04-13 16:23:25 +0000864 }
Chris Lattner2ab6a732003-10-13 00:37:13 +0000865
Chris Lattner4b662422004-04-13 16:23:25 +0000866 // Now we must loop over all of the dominance frontiers in the function,
867 // replacing occurrences of NewBBSucc with NewBB in some cases. All
868 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
869 // their dominance frontier must be updated to contain NewBB instead.
870 //
871 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
872 BasicBlock *Pred = PredBlocks[i];
873 // Get all of the dominators of the predecessor...
874 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
875 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
876 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
877 BasicBlock *PredDom = *PDI;
878
879 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
880 // dominate NewBBSucc but did dominate a predecessor of it. Now we
881 // change this entry to include NewBB in the DF instead of NewBBSucc.
882 DominanceFrontier::iterator DFI = DF->find(PredDom);
883 assert(DFI != DF->end() && "No dominance frontier for node?");
884 if (DFI->second.count(NewBBSucc)) {
885 // If NewBBSucc should not stay in our dominator frontier, remove it.
886 // We remove it unless there is a predecessor of NewBBSucc that we
887 // dominate, but we don't strictly dominate NewBBSucc.
888 bool ShouldRemove = true;
889 if (PredDom == NewBBSucc || !DS.dominates(PredDom, NewBBSucc)) {
890 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
891 // Check to see if it dominates any predecessors of NewBBSucc.
892 for (pred_iterator PI = pred_begin(NewBBSucc),
893 E = pred_end(NewBBSucc); PI != E; ++PI)
894 if (DS.dominates(PredDom, *PI)) {
895 ShouldRemove = false;
896 break;
897 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000898 }
Chris Lattner4b662422004-04-13 16:23:25 +0000899
900 if (ShouldRemove)
901 DF->removeFromFrontier(DFI, NewBBSucc);
902 DF->addToFrontier(DFI, NewBB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000903 }
904 }
905 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000906 }
Chris Lattner38acf9e2002-09-26 16:17:31 +0000907}
Brian Gaeked0fde302003-11-11 22:41:34 +0000908