blob: ba63f9b371a9d504db886aff5c554001d6d7f5a3 [file] [log] [blame]
Chris Lattner55d47882003-10-12 21:44:18 +00001//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
John Criswell482202a2003-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 Lattner61992f62002-09-26 16:17:31 +00009//
Chris Lattner154e4d52003-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 Lattner650096a2003-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 Lattner7710f2f2003-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 Lattner650096a2003-02-27 20:27:08 +000023//
Chris Lattnerc4622a62003-10-13 00:37:13 +000024// This pass also guarantees that loops will have exactly one backedge.
25//
Chris Lattner650096a2003-02-27 20:27:08 +000026// Note that the simplifycfg pass will clean up blocks which are split out but
Chris Lattner154e4d52003-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 Lattner61992f62002-09-26 16:17:31 +000032//
33//===----------------------------------------------------------------------===//
34
35#include "llvm/Transforms/Scalar.h"
Chris Lattnerd0788122004-03-14 03:59:22 +000036#include "llvm/Constant.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000037#include "llvm/Instructions.h"
Chris Lattnerd0788122004-03-14 03:59:22 +000038#include "llvm/Function.h"
39#include "llvm/Type.h"
Chris Lattner514e8432005-03-25 06:37:22 +000040#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner031a3f82003-12-19 06:27:08 +000041#include "llvm/Analysis/Dominators.h"
42#include "llvm/Analysis/LoopInfo.h"
Chris Lattner61992f62002-09-26 16:17:31 +000043#include "llvm/Support/CFG.h"
Chris Lattner84170522004-04-13 05:05:33 +000044#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000045#include "llvm/ADT/SetOperations.h"
46#include "llvm/ADT/SetVector.h"
47#include "llvm/ADT/Statistic.h"
48#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattner7710f2f2003-12-10 17:20:35 +000049using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000050
Chris Lattner61992f62002-09-26 16:17:31 +000051namespace {
Chris Lattner154e4d52003-10-12 21:43:28 +000052 Statistic<>
Chris Lattner7710f2f2003-12-10 17:20:35 +000053 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
Chris Lattner84170522004-04-13 05:05:33 +000054 Statistic<>
55 NumNested("loopsimplify", "Number of nested loops split out");
Chris Lattner61992f62002-09-26 16:17:31 +000056
Chris Lattner154e4d52003-10-12 21:43:28 +000057 struct LoopSimplify : public FunctionPass {
Chris Lattner514e8432005-03-25 06:37:22 +000058 // AA - If we have an alias analysis object to update, this is it, otherwise
59 // this is null.
60 AliasAnalysis *AA;
61
Chris Lattner61992f62002-09-26 16:17:31 +000062 virtual bool runOnFunction(Function &F);
63
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 // We need loop information to identify the loops...
66 AU.addRequired<LoopInfo>();
Chris Lattner650096a2003-02-27 20:27:08 +000067 AU.addRequired<DominatorSet>();
Chris Lattner797cb2f2004-03-13 22:01:26 +000068 AU.addRequired<DominatorTree>();
Chris Lattner61992f62002-09-26 16:17:31 +000069
70 AU.addPreserved<LoopInfo>();
71 AU.addPreserved<DominatorSet>();
72 AU.addPreserved<ImmediateDominators>();
73 AU.addPreserved<DominatorTree>();
Chris Lattner650096a2003-02-27 20:27:08 +000074 AU.addPreserved<DominanceFrontier>();
Chris Lattner61992f62002-09-26 16:17:31 +000075 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
76 }
77 private:
78 bool ProcessLoop(Loop *L);
Chris Lattner650096a2003-02-27 20:27:08 +000079 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
80 const std::vector<BasicBlock*> &Preds);
Chris Lattner82782632004-04-18 22:27:10 +000081 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner61992f62002-09-26 16:17:31 +000082 void InsertPreheaderForLoop(Loop *L);
Chris Lattner84170522004-04-13 05:05:33 +000083 Loop *SeparateNestedLoop(Loop *L);
Chris Lattnerc4622a62003-10-13 00:37:13 +000084 void InsertUniqueBackedgeBlock(Loop *L);
85
86 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
87 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner61992f62002-09-26 16:17:31 +000088 };
89
Chris Lattner154e4d52003-10-12 21:43:28 +000090 RegisterOpt<LoopSimplify>
91 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner61992f62002-09-26 16:17:31 +000092}
93
94// Publically exposed interface to pass...
Chris Lattner7710f2f2003-12-10 17:20:35 +000095const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
Chris Lattner3e860842004-09-20 04:43:15 +000096FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner61992f62002-09-26 16:17:31 +000097
Chris Lattner61992f62002-09-26 16:17:31 +000098/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
99/// it in any convenient order) inserting preheaders...
100///
Chris Lattner154e4d52003-10-12 21:43:28 +0000101bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner61992f62002-09-26 16:17:31 +0000102 bool Changed = false;
103 LoopInfo &LI = getAnalysis<LoopInfo>();
Chris Lattner514e8432005-03-25 06:37:22 +0000104 AA = getAnalysisToUpdate<AliasAnalysis>();
Chris Lattner61992f62002-09-26 16:17:31 +0000105
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000106 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
107 Changed |= ProcessLoop(*I);
Chris Lattner61992f62002-09-26 16:17:31 +0000108
109 return Changed;
110}
111
112
113/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
114/// all loops have preheaders.
115///
Chris Lattner154e4d52003-10-12 21:43:28 +0000116bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000117 bool Changed = false;
118
Chris Lattnerd0788122004-03-14 03:59:22 +0000119 // Check to see that no blocks (other than the header) in the loop have
120 // predecessors that are not in the loop. This is not valid for natural
121 // loops, but can occur if the blocks are unreachable. Since they are
122 // unreachable we can just shamelessly destroy their terminators to make them
123 // not branch into the loop!
124 assert(L->getBlocks()[0] == L->getHeader() &&
125 "Header isn't first block in loop?");
126 for (unsigned i = 1, e = L->getBlocks().size(); i != e; ++i) {
127 BasicBlock *LoopBB = L->getBlocks()[i];
128 Retry:
129 for (pred_iterator PI = pred_begin(LoopBB), E = pred_end(LoopBB);
130 PI != E; ++PI)
131 if (!L->contains(*PI)) {
132 // This predecessor is not in the loop. Kill its terminator!
133 BasicBlock *DeadBlock = *PI;
134 for (succ_iterator SI = succ_begin(DeadBlock), E = succ_end(DeadBlock);
135 SI != E; ++SI)
136 (*SI)->removePredecessor(DeadBlock); // Remove PHI node entries
137
138 // Delete the dead terminator.
Chris Lattner514e8432005-03-25 06:37:22 +0000139 if (AA) AA->deleteValue(&DeadBlock->back());
Chris Lattnerd0788122004-03-14 03:59:22 +0000140 DeadBlock->getInstList().pop_back();
141
142 Value *RetVal = 0;
143 if (LoopBB->getParent()->getReturnType() != Type::VoidTy)
144 RetVal = Constant::getNullValue(LoopBB->getParent()->getReturnType());
145 new ReturnInst(RetVal, DeadBlock);
146 goto Retry; // We just invalidated the pred_iterator. Retry.
147 }
148 }
149
Chris Lattner61992f62002-09-26 16:17:31 +0000150 // Does the loop already have a preheader? If so, don't modify the loop...
151 if (L->getLoopPreheader() == 0) {
152 InsertPreheaderForLoop(L);
153 NumInserted++;
154 Changed = true;
155 }
156
Chris Lattner7710f2f2003-12-10 17:20:35 +0000157 // Next, check to make sure that all exit nodes of the loop only have
158 // predecessors that are inside of the loop. This check guarantees that the
159 // loop preheader/header will dominate the exit blocks. If the exit block has
160 // predecessors from outside of the loop, split the edge now.
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000161 std::vector<BasicBlock*> ExitBlocks;
162 L->getExitBlocks(ExitBlocks);
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000163
164 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
165 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
166 E = ExitBlockSet.end(); I != E; ++I) {
167 BasicBlock *ExitBlock = *I;
Chris Lattnerdaa12132004-07-15 05:36:31 +0000168 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
169 PI != PE; ++PI)
170 if (!L->contains(*PI)) {
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000171 RewriteLoopExitBlock(L, ExitBlock);
Chris Lattnerdaa12132004-07-15 05:36:31 +0000172 NumInserted++;
173 Changed = true;
174 break;
175 }
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000176 }
Chris Lattner650096a2003-02-27 20:27:08 +0000177
Chris Lattner84170522004-04-13 05:05:33 +0000178 // If the header has more than two predecessors at this point (from the
179 // preheader and from multiple backedges), we must adjust the loop.
Chris Lattnerc4622a62003-10-13 00:37:13 +0000180 if (L->getNumBackEdges() != 1) {
Chris Lattner84170522004-04-13 05:05:33 +0000181 // If this is really a nested loop, rip it out into a child loop.
182 if (Loop *NL = SeparateNestedLoop(L)) {
183 ++NumNested;
184 // This is a big restructuring change, reprocess the whole loop.
185 ProcessLoop(NL);
186 return true;
187 }
188
Chris Lattnerc4622a62003-10-13 00:37:13 +0000189 InsertUniqueBackedgeBlock(L);
190 NumInserted++;
191 Changed = true;
192 }
193
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000194 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
195 Changed |= ProcessLoop(*I);
Chris Lattner61992f62002-09-26 16:17:31 +0000196 return Changed;
197}
198
Chris Lattner650096a2003-02-27 20:27:08 +0000199/// SplitBlockPredecessors - Split the specified block into two blocks. We want
200/// to move the predecessors specified in the Preds list to point to the new
201/// block, leaving the remaining predecessors pointing to BB. This method
202/// updates the SSA PHINode's, but no other analyses.
203///
Chris Lattner154e4d52003-10-12 21:43:28 +0000204BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
205 const char *Suffix,
Chris Lattner650096a2003-02-27 20:27:08 +0000206 const std::vector<BasicBlock*> &Preds) {
207
208 // Create new basic block, insert right before the original block...
Chris Lattner8d414ad2004-02-04 03:58:28 +0000209 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattner650096a2003-02-27 20:27:08 +0000210
211 // The preheader first gets an unconditional branch to the loop header...
Chris Lattnera2960002003-11-21 16:52:05 +0000212 BranchInst *BI = new BranchInst(BB, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000213
214 // For every PHI node in the block, insert a PHI node into NewBB where the
215 // incoming values from the out of loop edges are moved to NewBB. We have two
216 // possible cases here. If the loop is dead, we just insert dummy entries
217 // into the PHI nodes for the new edge. If the loop is not dead, we move the
218 // incoming edges in BB into new PHI nodes in NewBB.
219 //
220 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner031a3f82003-12-19 06:27:08 +0000221 // Check to see if the values being merged into the new block need PHI
222 // nodes. If so, insert them.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000223 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
224 PHINode *PN = cast<PHINode>(I);
Chris Lattner84170522004-04-13 05:05:33 +0000225 ++I;
226
Chris Lattner031a3f82003-12-19 06:27:08 +0000227 // Check to see if all of the values coming in are the same. If so, we
228 // don't need to create a new PHI node.
229 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
230 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
231 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
232 InVal = 0;
233 break;
234 }
235
236 // If the values coming into the block are not the same, we need a PHI.
237 if (InVal == 0) {
Chris Lattner6c237bc2003-12-09 23:12:55 +0000238 // Create the new PHI node, insert it into NewBB at the end of the block
239 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
Chris Lattner514e8432005-03-25 06:37:22 +0000240 if (AA) AA->copyValue(PN, NewPHI);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000241
242 // Move all of the edges from blocks outside the loop to the new PHI
243 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Chris Lattner84170522004-04-13 05:05:33 +0000244 Value *V = PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000245 NewPHI->addIncoming(V, Preds[i]);
246 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000247 InVal = NewPHI;
248 } else {
249 // Remove all of the edges coming into the PHI nodes from outside of the
250 // block.
251 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
252 PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000253 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000254
255 // Add an incoming value to the PHI node in the loop for the preheader
256 // edge.
257 PN->addIncoming(InVal, NewBB);
Chris Lattner84170522004-04-13 05:05:33 +0000258
259 // Can we eliminate this phi node now?
260 if (Value *V = hasConstantValue(PN)) {
Chris Lattnere29d6342004-10-17 21:22:38 +0000261 if (!isa<Instruction>(V) ||
262 getAnalysis<DominatorSet>().dominates(cast<Instruction>(V), PN)) {
263 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000264 if (AA) AA->deleteValue(PN);
Chris Lattnere29d6342004-10-17 21:22:38 +0000265 BB->getInstList().erase(PN);
266 }
Chris Lattner84170522004-04-13 05:05:33 +0000267 }
Chris Lattner650096a2003-02-27 20:27:08 +0000268 }
269
270 // Now that the PHI nodes are updated, actually move the edges from
271 // Preds to point to NewBB instead of BB.
272 //
273 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
274 TerminatorInst *TI = Preds[i]->getTerminator();
275 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
276 if (TI->getSuccessor(s) == BB)
277 TI->setSuccessor(s, NewBB);
278 }
279
280 } else { // Otherwise the loop is dead...
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000281 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
282 PHINode *PN = cast<PHINode>(I);
Chris Lattner650096a2003-02-27 20:27:08 +0000283 // Insert dummy values as the incoming value...
284 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000285 }
Chris Lattner650096a2003-02-27 20:27:08 +0000286 }
287 return NewBB;
288}
289
Chris Lattner61992f62002-09-26 16:17:31 +0000290/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
291/// preheader, this method is called to insert one. This method has two phases:
292/// preheader insertion and analysis updating.
293///
Chris Lattner154e4d52003-10-12 21:43:28 +0000294void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000295 BasicBlock *Header = L->getHeader();
296
297 // Compute the set of predecessors of the loop that are not in the loop.
298 std::vector<BasicBlock*> OutsideBlocks;
299 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
300 PI != PE; ++PI)
301 if (!L->contains(*PI)) // Coming in from outside the loop?
302 OutsideBlocks.push_back(*PI); // Keep track of it...
303
Chris Lattner650096a2003-02-27 20:27:08 +0000304 // Split out the loop pre-header
305 BasicBlock *NewBB =
306 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner61992f62002-09-26 16:17:31 +0000307
Chris Lattner61992f62002-09-26 16:17:31 +0000308 //===--------------------------------------------------------------------===//
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000309 // Update analysis results now that we have performed the transformation
Chris Lattner61992f62002-09-26 16:17:31 +0000310 //
311
312 // We know that we have loop information to update... update it now.
313 if (Loop *Parent = L->getParentLoop())
314 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000315
316 // If the header for the loop used to be an exit node for another loop, then
317 // we need to update this to know that the loop-preheader is now the exit
318 // node. Note that the only loop that could have our header as an exit node
Chris Lattner08950252003-05-12 22:04:34 +0000319 // is a sibling loop, ie, one with the same parent loop, or one if it's
320 // children.
321 //
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000322 LoopInfo::iterator ParentLoops, ParentLoopsE;
323 if (Loop *Parent = L->getParentLoop()) {
324 ParentLoops = Parent->begin();
325 ParentLoopsE = Parent->end();
326 } else { // Must check top-level loops...
327 ParentLoops = getAnalysis<LoopInfo>().begin();
328 ParentLoopsE = getAnalysis<LoopInfo>().end();
329 }
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000330
Chris Lattner650096a2003-02-27 20:27:08 +0000331 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
Chris Lattner797cb2f2004-03-13 22:01:26 +0000332 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattnerdb5b8f42004-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 Lattner797cb2f2004-03-13 22:01:26 +0000343
Chris Lattner650096a2003-02-27 20:27:08 +0000344 {
Chris Lattner61992f62002-09-26 16:17:31 +0000345 // The blocks that dominate NewBB are the blocks that dominate Header,
346 // minus Header, plus NewBB.
Chris Lattner650096a2003-02-27 20:27:08 +0000347 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner61992f62002-09-26 16:17:31 +0000348 DomSet.erase(Header); // Header does not dominate us...
Chris Lattner650096a2003-02-27 20:27:08 +0000349 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner03a9e152002-09-29 21:41:38 +0000350
351 // The newly created basic block dominates all nodes dominated by Header.
Chris Lattnerdb5b8f42004-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 Lattner61992f62002-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 Lattner650096a2003-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 Brukman4ace48e2003-09-09 21:54:45 +0000377 // replacing occurrences of Header with NewBB in some cases. If a block
Chris Lattner650096a2003-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 Lattner84170522004-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 Lattner82782632004-04-18 22:27:10 +0000406BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattner650096a2003-02-27 20:27:08 +0000407 DominatorSet &DS = getAnalysis<DominatorSet>();
Chris Lattner650096a2003-02-27 20:27:08 +0000408
409 std::vector<BasicBlock*> LoopBlocks;
410 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
411 if (L->contains(*I))
412 LoopBlocks.push_back(*I);
413
Chris Lattner10b2b052003-02-27 22:31:07 +0000414 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
415 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
416
Chris Lattner4e2fbfb2003-02-27 21:50:19 +0000417 // Update Loop Information - we know that the new block will be in the parent
418 // loop of L.
419 if (Loop *Parent = L->getParentLoop())
420 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner32a39c22003-02-28 03:07:54 +0000421
Chris Lattnerc4622a62003-10-13 00:37:13 +0000422 // Update dominator information (set, immdom, domtree, and domfrontier)
423 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
Chris Lattner82782632004-04-18 22:27:10 +0000424 return NewBB;
Chris Lattnerc4622a62003-10-13 00:37:13 +0000425}
426
Chris Lattner84170522004-04-13 05:05:33 +0000427/// AddBlockAndPredsToSet - Add the specified block, and all of its
428/// predecessors, to the specified set, if it's not already in there. Stop
429/// predecessor traversal when we reach StopBlock.
430static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
431 std::set<BasicBlock*> &Blocks) {
432 if (!Blocks.insert(BB).second) return; // already processed.
433 if (BB == StopBlock) return; // Stop here!
434
435 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
436 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
437}
438
Chris Lattnera6e22812004-04-13 15:21:18 +0000439/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
440/// PHI node that tells us how to partition the loops.
Chris Lattner514e8432005-03-25 06:37:22 +0000441static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorSet &DS,
442 AliasAnalysis *AA) {
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000443 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
444 PHINode *PN = cast<PHINode>(I);
Chris Lattnera6e22812004-04-13 15:21:18 +0000445 ++I;
Chris Lattnere29d6342004-10-17 21:22:38 +0000446 if (Value *V = hasConstantValue(PN))
447 if (!isa<Instruction>(V) || DS.dominates(cast<Instruction>(V), PN)) {
448 // This is a degenerate PHI already, don't modify it!
449 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000450 if (AA) AA->deleteValue(PN);
Chris Lattnerdd3ec922005-03-06 21:35:38 +0000451 PN->eraseFromParent();
Chris Lattnere29d6342004-10-17 21:22:38 +0000452 continue;
453 }
454
455 // Scan this PHI node looking for a use of the PHI node by itself.
456 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
457 if (PN->getIncomingValue(i) == PN &&
458 L->contains(PN->getIncomingBlock(i)))
459 // We found something tasty to remove.
460 return PN;
Chris Lattnera6e22812004-04-13 15:21:18 +0000461 }
462 return 0;
463}
464
Chris Lattner84170522004-04-13 05:05:33 +0000465/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
466/// them out into a nested loop. This is important for code that looks like
467/// this:
468///
469/// Loop:
470/// ...
471/// br cond, Loop, Next
472/// ...
473/// br cond2, Loop, Out
474///
475/// To identify this common case, we look at the PHI nodes in the header of the
476/// loop. PHI nodes with unchanging values on one backedge correspond to values
477/// that change in the "outer" loop, but not in the "inner" loop.
478///
479/// If we are able to separate out a loop, return the new outer loop that was
480/// created.
481///
482Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
Chris Lattner514e8432005-03-25 06:37:22 +0000483 PHINode *PN = FindPHIToPartitionLoops(L, getAnalysis<DominatorSet>(), AA);
Chris Lattnera6e22812004-04-13 15:21:18 +0000484 if (PN == 0) return 0; // No known way to partition.
Chris Lattner84170522004-04-13 05:05:33 +0000485
Chris Lattnera6e22812004-04-13 15:21:18 +0000486 // Pull out all predecessors that have varying values in the loop. This
487 // handles the case when a PHI node has multiple instances of itself as
488 // arguments.
Chris Lattner84170522004-04-13 05:05:33 +0000489 std::vector<BasicBlock*> OuterLoopPreds;
Chris Lattnera6e22812004-04-13 15:21:18 +0000490 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
491 if (PN->getIncomingValue(i) != PN ||
492 !L->contains(PN->getIncomingBlock(i)))
493 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner84170522004-04-13 05:05:33 +0000494
Chris Lattner89e959b2004-04-13 16:23:25 +0000495 BasicBlock *Header = L->getHeader();
Chris Lattner84170522004-04-13 05:05:33 +0000496 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
497
498 // Update dominator information (set, immdom, domtree, and domfrontier)
499 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
500
501 // Create the new outer loop.
502 Loop *NewOuter = new Loop();
503
504 LoopInfo &LI = getAnalysis<LoopInfo>();
505
506 // Change the parent loop to use the outer loop as its child now.
507 if (Loop *Parent = L->getParentLoop())
508 Parent->replaceChildLoopWith(L, NewOuter);
509 else
510 LI.changeTopLevelLoop(L, NewOuter);
511
512 // This block is going to be our new header block: add it to this loop and all
513 // parent loops.
514 NewOuter->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
515
516 // L is now a subloop of our outer loop.
517 NewOuter->addChildLoop(L);
518
Chris Lattner84170522004-04-13 05:05:33 +0000519 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
520 NewOuter->addBlockEntry(L->getBlocks()[i]);
521
522 // Determine which blocks should stay in L and which should be moved out to
523 // the Outer loop now.
524 DominatorSet &DS = getAnalysis<DominatorSet>();
525 std::set<BasicBlock*> BlocksInL;
526 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
527 if (DS.dominates(Header, *PI))
528 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
529
530
531 // Scan all of the loop children of L, moving them to OuterLoop if they are
532 // not part of the inner loop.
533 for (Loop::iterator I = L->begin(); I != L->end(); )
534 if (BlocksInL.count((*I)->getHeader()))
535 ++I; // Loop remains in L
536 else
537 NewOuter->addChildLoop(L->removeChildLoop(I));
538
539 // Now that we know which blocks are in L and which need to be moved to
540 // OuterLoop, move any blocks that need it.
541 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
542 BasicBlock *BB = L->getBlocks()[i];
543 if (!BlocksInL.count(BB)) {
544 // Move this block to the parent, updating the exit blocks sets
545 L->removeBlockFromLoop(BB);
546 if (LI[BB] == L)
547 LI.changeLoopFor(BB, NewOuter);
548 --i;
549 }
550 }
551
Chris Lattner84170522004-04-13 05:05:33 +0000552 return NewOuter;
553}
554
555
556
Chris Lattnerc4622a62003-10-13 00:37:13 +0000557/// InsertUniqueBackedgeBlock - This method is called when the specified loop
558/// has more than one backedge in it. If this occurs, revector all of these
559/// backedges to target a new basic block and have that block branch to the loop
560/// header. This ensures that loops have exactly one backedge.
561///
562void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
563 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
564
565 // Get information about the loop
566 BasicBlock *Preheader = L->getLoopPreheader();
567 BasicBlock *Header = L->getHeader();
568 Function *F = Header->getParent();
569
570 // Figure out which basic blocks contain back-edges to the loop header.
571 std::vector<BasicBlock*> BackedgeBlocks;
572 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
573 if (*I != Preheader) BackedgeBlocks.push_back(*I);
574
575 // Create and insert the new backedge block...
576 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattnera2960002003-11-21 16:52:05 +0000577 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000578
579 // Move the new backedge block to right after the last backedge block.
580 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
581 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
582
583 // Now that the block has been inserted into the function, create PHI nodes in
584 // the backedge block which correspond to any PHI nodes in the header block.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000585 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
586 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000587 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
588 BETerminator);
Chris Lattnerd8e20182005-01-29 00:39:08 +0000589 NewPN->reserveOperandSpace(BackedgeBlocks.size());
Chris Lattner514e8432005-03-25 06:37:22 +0000590 if (AA) AA->copyValue(PN, NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000591
592 // Loop over the PHI node, moving all entries except the one for the
593 // preheader over to the new PHI node.
594 unsigned PreheaderIdx = ~0U;
595 bool HasUniqueIncomingValue = true;
596 Value *UniqueValue = 0;
597 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
598 BasicBlock *IBB = PN->getIncomingBlock(i);
599 Value *IV = PN->getIncomingValue(i);
600 if (IBB == Preheader) {
601 PreheaderIdx = i;
602 } else {
603 NewPN->addIncoming(IV, IBB);
604 if (HasUniqueIncomingValue) {
605 if (UniqueValue == 0)
606 UniqueValue = IV;
607 else if (UniqueValue != IV)
608 HasUniqueIncomingValue = false;
609 }
610 }
611 }
612
613 // Delete all of the incoming values from the old PN except the preheader's
614 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
615 if (PreheaderIdx != 0) {
616 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
617 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
618 }
Chris Lattnerd8e20182005-01-29 00:39:08 +0000619 // Nuke all entries except the zero'th.
620 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
621 PN->removeIncomingValue(e-i, false);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000622
623 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
624 PN->addIncoming(NewPN, BEBlock);
625
626 // As an optimization, if all incoming values in the new PhiNode (which is a
627 // subset of the incoming values of the old PHI node) have the same value,
628 // eliminate the PHI Node.
629 if (HasUniqueIncomingValue) {
630 NewPN->replaceAllUsesWith(UniqueValue);
Chris Lattner514e8432005-03-25 06:37:22 +0000631 if (AA) AA->deleteValue(NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000632 BEBlock->getInstList().erase(NewPN);
633 }
634 }
635
636 // Now that all of the PHI nodes have been inserted and adjusted, modify the
637 // backedge blocks to just to the BEBlock instead of the header.
638 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
639 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
640 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
641 if (TI->getSuccessor(Op) == Header)
642 TI->setSuccessor(Op, BEBlock);
643 }
644
645 //===--- Update all analyses which we must preserve now -----------------===//
646
647 // Update Loop Information - we know that this block is now in the current
648 // loop and all parent loops.
649 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
650
Chris Lattnerc4622a62003-10-13 00:37:13 +0000651 // Update dominator information (set, immdom, domtree, and domfrontier)
652 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
653}
654
655/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
656/// different kinds of dominator information (dominator sets, immediate
657/// dominators, dominator trees, and dominance frontiers) after a new block has
658/// been added to the CFG.
659///
Chris Lattner14ab84a2004-02-05 21:12:24 +0000660/// This only supports the case when an existing block (known as "NewBBSucc"),
661/// had some of its predecessors factored into a new basic block. This
Chris Lattnerc4622a62003-10-13 00:37:13 +0000662/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner14ab84a2004-02-05 21:12:24 +0000663/// unconditional branch to NewBBSucc, and moves some predecessors of
664/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
665/// PredBlocks, even though they are the same as
666/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattnerc4622a62003-10-13 00:37:13 +0000667///
668void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
669 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000670 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattnerc4622a62003-10-13 00:37:13 +0000671 assert(succ_begin(NewBB) != succ_end(NewBB) &&
672 ++succ_begin(NewBB) == succ_end(NewBB) &&
673 "NewBB should have a single successor!");
Chris Lattner14ab84a2004-02-05 21:12:24 +0000674 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000675 DominatorSet &DS = getAnalysis<DominatorSet>();
676
Chris Lattner146d0df2004-04-01 19:06:07 +0000677 // Update dominator information... The blocks that dominate NewBB are the
678 // intersection of the dominators of predecessors, plus the block itself.
679 //
680 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
681 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
682 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
683 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
684 DS.addBasicBlock(NewBB, NewBBDomSet);
685
Chris Lattner14ab84a2004-02-05 21:12:24 +0000686 // The newly inserted basic block will dominate existing basic blocks iff the
687 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
688 // the non-pred blocks, then they all must be the same block!
Chris Lattner146d0df2004-04-01 19:06:07 +0000689 //
Chris Lattner14ab84a2004-02-05 21:12:24 +0000690 bool NewBBDominatesNewBBSucc = true;
691 {
692 BasicBlock *OnePred = PredBlocks[0];
693 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
694 if (PredBlocks[i] != OnePred) {
695 NewBBDominatesNewBBSucc = false;
696 break;
697 }
698
699 if (NewBBDominatesNewBBSucc)
700 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
701 PI != E; ++PI)
Chris Lattner2dd1c8d2004-02-05 23:20:59 +0000702 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000703 NewBBDominatesNewBBSucc = false;
704 break;
705 }
706 }
707
Chris Lattner146d0df2004-04-01 19:06:07 +0000708 // The other scenario where the new block can dominate its successors are when
709 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
710 // already.
711 if (!NewBBDominatesNewBBSucc) {
712 NewBBDominatesNewBBSucc = true;
713 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
714 PI != E; ++PI)
715 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
716 NewBBDominatesNewBBSucc = false;
717 break;
718 }
719 }
Chris Lattner650096a2003-02-27 20:27:08 +0000720
Chris Lattner14ab84a2004-02-05 21:12:24 +0000721 // If NewBB dominates some blocks, then it will dominate all blocks that
Chris Lattnerc0c953f2004-02-05 22:33:26 +0000722 // NewBBSucc does.
Chris Lattner14ab84a2004-02-05 21:12:24 +0000723 if (NewBBDominatesNewBBSucc) {
724 BasicBlock *PredBlock = PredBlocks[0];
725 Function *F = NewBB->getParent();
726 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattnerc0c953f2004-02-05 22:33:26 +0000727 if (DS.dominates(NewBBSucc, I))
Chris Lattner14ab84a2004-02-05 21:12:24 +0000728 DS.addDominator(I, NewBB);
729 }
730
Chris Lattner650096a2003-02-27 20:27:08 +0000731 // Update immediate dominator information if we have it...
732 BasicBlock *NewBBIDom = 0;
733 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000734 // To find the immediate dominator of the new exit node, we trace up the
735 // immediate dominators of a predecessor until we find a basic block that
736 // dominates the exit block.
Chris Lattner650096a2003-02-27 20:27:08 +0000737 //
Chris Lattnerc4622a62003-10-13 00:37:13 +0000738 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
Chris Lattner650096a2003-02-27 20:27:08 +0000739 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
740 assert(Dom != 0 && "No shared dominator found???");
741 Dom = ID->get(Dom);
742 }
743
744 // Set the immediate dominator now...
745 ID->addNewBlock(NewBB, Dom);
746 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
Chris Lattner14ab84a2004-02-05 21:12:24 +0000747
748 // If NewBB strictly dominates other blocks, we need to update their idom's
749 // now. The only block that need adjustment is the NewBBSucc block, whose
750 // idom should currently be set to PredBlocks[0].
Chris Lattner59fdf742004-04-01 19:21:46 +0000751 if (NewBBDominatesNewBBSucc)
Chris Lattner14ab84a2004-02-05 21:12:24 +0000752 ID->setImmediateDominator(NewBBSucc, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000753 }
754
755 // Update DominatorTree information if it is active.
756 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000757 // If we don't have ImmediateDominator info around, calculate the idom as
758 // above.
Chris Lattner650096a2003-02-27 20:27:08 +0000759 DominatorTree::Node *NewBBIDomNode;
760 if (NewBBIDom) {
761 NewBBIDomNode = DT->getNode(NewBBIDom);
762 } else {
Chris Lattnerc4622a62003-10-13 00:37:13 +0000763 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
Chris Lattnerbb9d03b2003-09-11 16:26:13 +0000764 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
Chris Lattner650096a2003-02-27 20:27:08 +0000765 NewBBIDomNode = NewBBIDomNode->getIDom();
766 assert(NewBBIDomNode && "No shared dominator found??");
767 }
768 }
769
Chris Lattner14ab84a2004-02-05 21:12:24 +0000770 // Create the new dominator tree node... and set the idom of NewBB.
771 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
772
773 // If NewBB strictly dominates other blocks, then it is now the immediate
774 // dominator of NewBBSucc. Update the dominator tree as appropriate.
775 if (NewBBDominatesNewBBSucc) {
776 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
Chris Lattner14ab84a2004-02-05 21:12:24 +0000777 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
778 }
Chris Lattner650096a2003-02-27 20:27:08 +0000779 }
780
781 // Update dominance frontier information...
782 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
Chris Lattner89e959b2004-04-13 16:23:25 +0000783 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
784 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
785 // a predecessor of.
Chris Lattner14ab84a2004-02-05 21:12:24 +0000786 if (NewBBDominatesNewBBSucc) {
787 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
788 if (DFI != DF->end()) {
789 DominanceFrontier::DomSetType Set = DFI->second;
790 // Filter out stuff in Set that we do not dominate a predecessor of.
791 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
792 E = Set.end(); SetI != E;) {
793 bool DominatesPred = false;
794 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
795 PI != E; ++PI)
796 if (DS.dominates(NewBB, *PI))
797 DominatesPred = true;
798 if (!DominatesPred)
799 Set.erase(SetI++);
800 else
801 ++SetI;
802 }
Chris Lattner650096a2003-02-27 20:27:08 +0000803
Chris Lattner14ab84a2004-02-05 21:12:24 +0000804 DF->addBasicBlock(NewBB, Set);
805 }
806
807 } else {
808 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
809 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
810 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
811 DominanceFrontier::DomSetType NewDFSet;
812 NewDFSet.insert(NewBBSucc);
813 DF->addBasicBlock(NewBB, NewDFSet);
Chris Lattner89e959b2004-04-13 16:23:25 +0000814 }
Chris Lattnerc4622a62003-10-13 00:37:13 +0000815
Chris Lattner89e959b2004-04-13 16:23:25 +0000816 // Now we must loop over all of the dominance frontiers in the function,
817 // replacing occurrences of NewBBSucc with NewBB in some cases. All
818 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
819 // their dominance frontier must be updated to contain NewBB instead.
820 //
821 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
822 BasicBlock *Pred = PredBlocks[i];
823 // Get all of the dominators of the predecessor...
824 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
825 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
826 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
827 BasicBlock *PredDom = *PDI;
828
829 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
830 // dominate NewBBSucc but did dominate a predecessor of it. Now we
831 // change this entry to include NewBB in the DF instead of NewBBSucc.
832 DominanceFrontier::iterator DFI = DF->find(PredDom);
833 assert(DFI != DF->end() && "No dominance frontier for node?");
834 if (DFI->second.count(NewBBSucc)) {
835 // If NewBBSucc should not stay in our dominator frontier, remove it.
836 // We remove it unless there is a predecessor of NewBBSucc that we
837 // dominate, but we don't strictly dominate NewBBSucc.
838 bool ShouldRemove = true;
839 if (PredDom == NewBBSucc || !DS.dominates(PredDom, NewBBSucc)) {
840 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
841 // Check to see if it dominates any predecessors of NewBBSucc.
842 for (pred_iterator PI = pred_begin(NewBBSucc),
843 E = pred_end(NewBBSucc); PI != E; ++PI)
844 if (DS.dominates(PredDom, *PI)) {
845 ShouldRemove = false;
846 break;
847 }
Chris Lattner650096a2003-02-27 20:27:08 +0000848 }
Chris Lattner89e959b2004-04-13 16:23:25 +0000849
850 if (ShouldRemove)
851 DF->removeFromFrontier(DFI, NewBBSucc);
852 DF->addToFrontier(DFI, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000853 }
854 }
855 }
Chris Lattner650096a2003-02-27 20:27:08 +0000856 }
Chris Lattner61992f62002-09-26 16:17:31 +0000857}
Brian Gaeke960707c2003-11-11 22:41:34 +0000858