blob: 540940e4aec1d9dfd62439569dee8a2d1a279685 [file] [log] [blame]
Chris Lattner55d47882003-10-12 21:44:18 +00001//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
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"
Reid Spencer7c16caa2004-09-01 22:55:40 +000044#include "llvm/ADT/SetOperations.h"
45#include "llvm/ADT/SetVector.h"
46#include "llvm/ADT/Statistic.h"
47#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattner7710f2f2003-12-10 17:20:35 +000048using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000049
Chris Lattner61992f62002-09-26 16:17:31 +000050namespace {
Chris Lattner154e4d52003-10-12 21:43:28 +000051 Statistic<>
Chris Lattner7710f2f2003-12-10 17:20:35 +000052 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
Chris Lattner84170522004-04-13 05:05:33 +000053 Statistic<>
54 NumNested("loopsimplify", "Number of nested loops split out");
Chris Lattner61992f62002-09-26 16:17:31 +000055
Chris Lattner154e4d52003-10-12 21:43:28 +000056 struct LoopSimplify : public FunctionPass {
Chris Lattner514e8432005-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;
60
Chris Lattner61992f62002-09-26 16:17:31 +000061 virtual bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +000062
Chris Lattner61992f62002-09-26 16:17:31 +000063 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 // We need loop information to identify the loops...
65 AU.addRequired<LoopInfo>();
Chris Lattner650096a2003-02-27 20:27:08 +000066 AU.addRequired<DominatorSet>();
Chris Lattner797cb2f2004-03-13 22:01:26 +000067 AU.addRequired<DominatorTree>();
Chris Lattner61992f62002-09-26 16:17:31 +000068
69 AU.addPreserved<LoopInfo>();
70 AU.addPreserved<DominatorSet>();
71 AU.addPreserved<ImmediateDominators>();
Chris Lattnercda4aa62006-01-09 08:03:08 +000072 AU.addPreserved<ETForest>();
Chris Lattner61992f62002-09-26 16:17:31 +000073 AU.addPreserved<DominatorTree>();
Chris Lattner650096a2003-02-27 20:27:08 +000074 AU.addPreserved<DominanceFrontier>();
Chris Lattnerf83ce5f2005-08-10 02:07:32 +000075 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
Chris Lattner61992f62002-09-26 16:17:31 +000076 }
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 Lattnerf83ce5f2005-08-10 02:07:32 +0000194 // Scan over the PHI nodes in the loop header. Since they now have only two
195 // incoming values (the loop is canonicalized), we may have simplified the PHI
196 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
197 PHINode *PN;
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000198 for (BasicBlock::iterator I = L->getHeader()->begin();
199 (PN = dyn_cast<PHINode>(I++)); )
Chris Lattner62df7982005-08-10 17:15:20 +0000200 if (Value *V = PN->hasConstantValue()) {
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000201 PN->replaceAllUsesWith(V);
202 PN->eraseFromParent();
203 }
204
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000205 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
206 Changed |= ProcessLoop(*I);
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000207
Chris Lattner61992f62002-09-26 16:17:31 +0000208 return Changed;
209}
210
Chris Lattner650096a2003-02-27 20:27:08 +0000211/// SplitBlockPredecessors - Split the specified block into two blocks. We want
212/// to move the predecessors specified in the Preds list to point to the new
213/// block, leaving the remaining predecessors pointing to BB. This method
214/// updates the SSA PHINode's, but no other analyses.
215///
Chris Lattner154e4d52003-10-12 21:43:28 +0000216BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
217 const char *Suffix,
Chris Lattner650096a2003-02-27 20:27:08 +0000218 const std::vector<BasicBlock*> &Preds) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000219
Chris Lattner650096a2003-02-27 20:27:08 +0000220 // Create new basic block, insert right before the original block...
Chris Lattner8d414ad2004-02-04 03:58:28 +0000221 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattner650096a2003-02-27 20:27:08 +0000222
223 // The preheader first gets an unconditional branch to the loop header...
Chris Lattnera2960002003-11-21 16:52:05 +0000224 BranchInst *BI = new BranchInst(BB, NewBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000225
Chris Lattner650096a2003-02-27 20:27:08 +0000226 // For every PHI node in the block, insert a PHI node into NewBB where the
227 // incoming values from the out of loop edges are moved to NewBB. We have two
228 // possible cases here. If the loop is dead, we just insert dummy entries
229 // into the PHI nodes for the new edge. If the loop is not dead, we move the
230 // incoming edges in BB into new PHI nodes in NewBB.
231 //
232 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner031a3f82003-12-19 06:27:08 +0000233 // Check to see if the values being merged into the new block need PHI
234 // nodes. If so, insert them.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000235 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
236 PHINode *PN = cast<PHINode>(I);
Chris Lattner84170522004-04-13 05:05:33 +0000237 ++I;
238
Chris Lattner031a3f82003-12-19 06:27:08 +0000239 // Check to see if all of the values coming in are the same. If so, we
240 // don't need to create a new PHI node.
241 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
242 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
243 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
244 InVal = 0;
245 break;
246 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000247
Chris Lattner031a3f82003-12-19 06:27:08 +0000248 // If the values coming into the block are not the same, we need a PHI.
249 if (InVal == 0) {
Chris Lattner6c237bc2003-12-09 23:12:55 +0000250 // Create the new PHI node, insert it into NewBB at the end of the block
251 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
Chris Lattner514e8432005-03-25 06:37:22 +0000252 if (AA) AA->copyValue(PN, NewPHI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000253
Chris Lattner6c237bc2003-12-09 23:12:55 +0000254 // Move all of the edges from blocks outside the loop to the new PHI
255 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Chris Lattner84170522004-04-13 05:05:33 +0000256 Value *V = PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000257 NewPHI->addIncoming(V, Preds[i]);
258 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000259 InVal = NewPHI;
260 } else {
261 // Remove all of the edges coming into the PHI nodes from outside of the
262 // block.
263 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
264 PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000265 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000266
267 // Add an incoming value to the PHI node in the loop for the preheader
268 // edge.
269 PN->addIncoming(InVal, NewBB);
Chris Lattner84170522004-04-13 05:05:33 +0000270
271 // Can we eliminate this phi node now?
Chris Lattner257efb22005-08-05 00:57:45 +0000272 if (Value *V = PN->hasConstantValue(true)) {
Chris Lattnere29d6342004-10-17 21:22:38 +0000273 if (!isa<Instruction>(V) ||
274 getAnalysis<DominatorSet>().dominates(cast<Instruction>(V), PN)) {
275 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000276 if (AA) AA->deleteValue(PN);
Chris Lattnere29d6342004-10-17 21:22:38 +0000277 BB->getInstList().erase(PN);
278 }
Chris Lattner84170522004-04-13 05:05:33 +0000279 }
Chris Lattner650096a2003-02-27 20:27:08 +0000280 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000281
Chris Lattner650096a2003-02-27 20:27:08 +0000282 // Now that the PHI nodes are updated, actually move the edges from
283 // Preds to point to NewBB instead of BB.
284 //
285 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
286 TerminatorInst *TI = Preds[i]->getTerminator();
287 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
288 if (TI->getSuccessor(s) == BB)
289 TI->setSuccessor(s, NewBB);
290 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000291
Chris Lattner650096a2003-02-27 20:27:08 +0000292 } else { // Otherwise the loop is dead...
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000293 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
294 PHINode *PN = cast<PHINode>(I);
Chris Lattner650096a2003-02-27 20:27:08 +0000295 // Insert dummy values as the incoming value...
296 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000297 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000298 }
Chris Lattner650096a2003-02-27 20:27:08 +0000299 return NewBB;
300}
301
Chris Lattner61992f62002-09-26 16:17:31 +0000302/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
303/// preheader, this method is called to insert one. This method has two phases:
304/// preheader insertion and analysis updating.
305///
Chris Lattner154e4d52003-10-12 21:43:28 +0000306void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000307 BasicBlock *Header = L->getHeader();
308
309 // Compute the set of predecessors of the loop that are not in the loop.
310 std::vector<BasicBlock*> OutsideBlocks;
311 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
312 PI != PE; ++PI)
313 if (!L->contains(*PI)) // Coming in from outside the loop?
314 OutsideBlocks.push_back(*PI); // Keep track of it...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000315
Chris Lattner650096a2003-02-27 20:27:08 +0000316 // Split out the loop pre-header
317 BasicBlock *NewBB =
318 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000319
Chris Lattner61992f62002-09-26 16:17:31 +0000320 //===--------------------------------------------------------------------===//
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000321 // Update analysis results now that we have performed the transformation
Chris Lattner61992f62002-09-26 16:17:31 +0000322 //
Misha Brukmanb1c93172005-04-21 23:48:37 +0000323
Chris Lattner61992f62002-09-26 16:17:31 +0000324 // We know that we have loop information to update... update it now.
325 if (Loop *Parent = L->getParentLoop())
326 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000327
Chris Lattner650096a2003-02-27 20:27:08 +0000328 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
Chris Lattner797cb2f2004-03-13 22:01:26 +0000329 DominatorTree &DT = getAnalysis<DominatorTree>();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000330
Chris Lattnerdb5b8f42004-03-16 06:00:15 +0000331
332 // Update the dominator tree information.
333 // The immediate dominator of the preheader is the immediate dominator of
334 // the old header.
335 DominatorTree::Node *PHDomTreeNode =
336 DT.createNewNode(NewBB, DT.getNode(Header)->getIDom());
Chris Lattnercda4aa62006-01-09 08:03:08 +0000337 BasicBlock *oldHeaderIDom = DT.getNode(Header)->getIDom()->getBlock();
Chris Lattnerdb5b8f42004-03-16 06:00:15 +0000338
339 // Change the header node so that PNHode is the new immediate dominator
340 DT.changeImmediateDominator(DT.getNode(Header), PHDomTreeNode);
Chris Lattner797cb2f2004-03-13 22:01:26 +0000341
Chris Lattner650096a2003-02-27 20:27:08 +0000342 {
Chris Lattner61992f62002-09-26 16:17:31 +0000343 // The blocks that dominate NewBB are the blocks that dominate Header,
344 // minus Header, plus NewBB.
Chris Lattner650096a2003-02-27 20:27:08 +0000345 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner61992f62002-09-26 16:17:31 +0000346 DomSet.erase(Header); // Header does not dominate us...
Chris Lattner650096a2003-02-27 20:27:08 +0000347 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner03a9e152002-09-29 21:41:38 +0000348
349 // The newly created basic block dominates all nodes dominated by Header.
Chris Lattnerdb5b8f42004-03-16 06:00:15 +0000350 for (df_iterator<DominatorTree::Node*> DFI = df_begin(PHDomTreeNode),
351 E = df_end(PHDomTreeNode); DFI != E; ++DFI)
352 DS.addDominator((*DFI)->getBlock(), NewBB);
Chris Lattner61992f62002-09-26 16:17:31 +0000353 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000354
Chris Lattner61992f62002-09-26 16:17:31 +0000355 // Update immediate dominator information if we have it...
356 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
357 // Whatever i-dominated the header node now immediately dominates NewBB
358 ID->addNewBlock(NewBB, ID->get(Header));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000359
Chris Lattner61992f62002-09-26 16:17:31 +0000360 // The preheader now is the immediate dominator for the header node...
361 ID->setImmediateDominator(Header, NewBB);
362 }
Chris Lattnercda4aa62006-01-09 08:03:08 +0000363
364 // Update ET Forest information if we have it...
365 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
366 // Whatever i-dominated the header node now immediately dominates NewBB
367 EF->addNewBlock(NewBB, oldHeaderIDom);
368
369 // The preheader now is the immediate dominator for the header node...
370 EF->setImmediateDominator(Header, NewBB);
371 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000372
Chris Lattner650096a2003-02-27 20:27:08 +0000373 // Update dominance frontier information...
374 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
375 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
376 // everything that Header does, and it strictly dominates Header in
377 // addition.
378 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
379 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
380 NewDFSet.erase(Header);
381 DF->addBasicBlock(NewBB, NewDFSet);
382
383 // Now we must loop over all of the dominance frontiers in the function,
Misha Brukman4ace48e2003-09-09 21:54:45 +0000384 // replacing occurrences of Header with NewBB in some cases. If a block
Chris Lattner650096a2003-02-27 20:27:08 +0000385 // dominates a (now) predecessor of NewBB, but did not strictly dominate
386 // Header, it will have Header in it's DF set, but should now have NewBB in
387 // its set.
388 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
389 // Get all of the dominators of the predecessor...
390 const DominatorSet::DomSetType &PredDoms =
391 DS.getDominators(OutsideBlocks[i]);
392 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
393 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
394 BasicBlock *PredDom = *PDI;
395 // If the loop header is in DF(PredDom), then PredDom didn't dominate
396 // the header but did dominate a predecessor outside of the loop. Now
397 // we change this entry to include the preheader in the DF instead of
398 // the header.
399 DominanceFrontier::iterator DFI = DF->find(PredDom);
400 assert(DFI != DF->end() && "No dominance frontier for node?");
401 if (DFI->second.count(Header)) {
402 DF->removeFromFrontier(DFI, Header);
403 DF->addToFrontier(DFI, NewBB);
404 }
405 }
406 }
407 }
408}
409
Chris Lattner84170522004-04-13 05:05:33 +0000410/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
411/// blocks. This method is used to split exit blocks that have predecessors
412/// outside of the loop.
Chris Lattner82782632004-04-18 22:27:10 +0000413BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattner650096a2003-02-27 20:27:08 +0000414 DominatorSet &DS = getAnalysis<DominatorSet>();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000415
Chris Lattner650096a2003-02-27 20:27:08 +0000416 std::vector<BasicBlock*> LoopBlocks;
417 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
418 if (L->contains(*I))
419 LoopBlocks.push_back(*I);
420
Chris Lattner10b2b052003-02-27 22:31:07 +0000421 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
422 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
423
Chris Lattner4e2fbfb2003-02-27 21:50:19 +0000424 // Update Loop Information - we know that the new block will be in the parent
425 // loop of L.
426 if (Loop *Parent = L->getParentLoop())
427 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner32a39c22003-02-28 03:07:54 +0000428
Chris Lattnerc4622a62003-10-13 00:37:13 +0000429 // Update dominator information (set, immdom, domtree, and domfrontier)
430 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
Chris Lattner82782632004-04-18 22:27:10 +0000431 return NewBB;
Chris Lattnerc4622a62003-10-13 00:37:13 +0000432}
433
Chris Lattner84170522004-04-13 05:05:33 +0000434/// AddBlockAndPredsToSet - Add the specified block, and all of its
435/// predecessors, to the specified set, if it's not already in there. Stop
436/// predecessor traversal when we reach StopBlock.
437static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
438 std::set<BasicBlock*> &Blocks) {
439 if (!Blocks.insert(BB).second) return; // already processed.
440 if (BB == StopBlock) return; // Stop here!
441
442 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
443 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
444}
445
Chris Lattnera6e22812004-04-13 15:21:18 +0000446/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
447/// PHI node that tells us how to partition the loops.
Chris Lattner514e8432005-03-25 06:37:22 +0000448static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorSet &DS,
449 AliasAnalysis *AA) {
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000450 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
451 PHINode *PN = cast<PHINode>(I);
Chris Lattnera6e22812004-04-13 15:21:18 +0000452 ++I;
Nate Begemanb3923212005-08-04 23:24:19 +0000453 if (Value *V = PN->hasConstantValue())
Chris Lattnere29d6342004-10-17 21:22:38 +0000454 if (!isa<Instruction>(V) || DS.dominates(cast<Instruction>(V), PN)) {
455 // This is a degenerate PHI already, don't modify it!
456 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000457 if (AA) AA->deleteValue(PN);
Chris Lattnerdd3ec922005-03-06 21:35:38 +0000458 PN->eraseFromParent();
Chris Lattnere29d6342004-10-17 21:22:38 +0000459 continue;
460 }
461
462 // Scan this PHI node looking for a use of the PHI node by itself.
463 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
464 if (PN->getIncomingValue(i) == PN &&
465 L->contains(PN->getIncomingBlock(i)))
466 // We found something tasty to remove.
467 return PN;
Chris Lattnera6e22812004-04-13 15:21:18 +0000468 }
469 return 0;
470}
471
Chris Lattner84170522004-04-13 05:05:33 +0000472/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
473/// them out into a nested loop. This is important for code that looks like
474/// this:
475///
476/// Loop:
477/// ...
478/// br cond, Loop, Next
479/// ...
480/// br cond2, Loop, Out
481///
482/// To identify this common case, we look at the PHI nodes in the header of the
483/// loop. PHI nodes with unchanging values on one backedge correspond to values
484/// that change in the "outer" loop, but not in the "inner" loop.
485///
486/// If we are able to separate out a loop, return the new outer loop that was
487/// created.
488///
489Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
Chris Lattner514e8432005-03-25 06:37:22 +0000490 PHINode *PN = FindPHIToPartitionLoops(L, getAnalysis<DominatorSet>(), AA);
Chris Lattnera6e22812004-04-13 15:21:18 +0000491 if (PN == 0) return 0; // No known way to partition.
Chris Lattner84170522004-04-13 05:05:33 +0000492
Chris Lattnera6e22812004-04-13 15:21:18 +0000493 // Pull out all predecessors that have varying values in the loop. This
494 // handles the case when a PHI node has multiple instances of itself as
495 // arguments.
Chris Lattner84170522004-04-13 05:05:33 +0000496 std::vector<BasicBlock*> OuterLoopPreds;
Chris Lattnera6e22812004-04-13 15:21:18 +0000497 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
498 if (PN->getIncomingValue(i) != PN ||
499 !L->contains(PN->getIncomingBlock(i)))
500 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner84170522004-04-13 05:05:33 +0000501
Chris Lattner89e959b2004-04-13 16:23:25 +0000502 BasicBlock *Header = L->getHeader();
Chris Lattner84170522004-04-13 05:05:33 +0000503 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
504
505 // Update dominator information (set, immdom, domtree, and domfrontier)
506 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
507
508 // Create the new outer loop.
509 Loop *NewOuter = new Loop();
510
511 LoopInfo &LI = getAnalysis<LoopInfo>();
512
513 // Change the parent loop to use the outer loop as its child now.
514 if (Loop *Parent = L->getParentLoop())
515 Parent->replaceChildLoopWith(L, NewOuter);
516 else
517 LI.changeTopLevelLoop(L, NewOuter);
518
519 // This block is going to be our new header block: add it to this loop and all
520 // parent loops.
521 NewOuter->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
522
523 // L is now a subloop of our outer loop.
524 NewOuter->addChildLoop(L);
525
Chris Lattner84170522004-04-13 05:05:33 +0000526 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
527 NewOuter->addBlockEntry(L->getBlocks()[i]);
528
529 // Determine which blocks should stay in L and which should be moved out to
530 // the Outer loop now.
531 DominatorSet &DS = getAnalysis<DominatorSet>();
532 std::set<BasicBlock*> BlocksInL;
533 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
534 if (DS.dominates(Header, *PI))
535 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
536
537
538 // Scan all of the loop children of L, moving them to OuterLoop if they are
539 // not part of the inner loop.
540 for (Loop::iterator I = L->begin(); I != L->end(); )
541 if (BlocksInL.count((*I)->getHeader()))
542 ++I; // Loop remains in L
543 else
544 NewOuter->addChildLoop(L->removeChildLoop(I));
545
546 // Now that we know which blocks are in L and which need to be moved to
547 // OuterLoop, move any blocks that need it.
548 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
549 BasicBlock *BB = L->getBlocks()[i];
550 if (!BlocksInL.count(BB)) {
551 // Move this block to the parent, updating the exit blocks sets
552 L->removeBlockFromLoop(BB);
553 if (LI[BB] == L)
554 LI.changeLoopFor(BB, NewOuter);
555 --i;
556 }
557 }
558
Chris Lattner84170522004-04-13 05:05:33 +0000559 return NewOuter;
560}
561
562
563
Chris Lattnerc4622a62003-10-13 00:37:13 +0000564/// InsertUniqueBackedgeBlock - This method is called when the specified loop
565/// has more than one backedge in it. If this occurs, revector all of these
566/// backedges to target a new basic block and have that block branch to the loop
567/// header. This ensures that loops have exactly one backedge.
568///
569void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
570 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
571
572 // Get information about the loop
573 BasicBlock *Preheader = L->getLoopPreheader();
574 BasicBlock *Header = L->getHeader();
575 Function *F = Header->getParent();
576
577 // Figure out which basic blocks contain back-edges to the loop header.
578 std::vector<BasicBlock*> BackedgeBlocks;
579 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
580 if (*I != Preheader) BackedgeBlocks.push_back(*I);
581
582 // Create and insert the new backedge block...
583 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattnera2960002003-11-21 16:52:05 +0000584 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000585
586 // Move the new backedge block to right after the last backedge block.
587 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
588 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000589
Chris Lattnerc4622a62003-10-13 00:37:13 +0000590 // Now that the block has been inserted into the function, create PHI nodes in
591 // the backedge block which correspond to any PHI nodes in the header block.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000592 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
593 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000594 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
595 BETerminator);
Chris Lattnerd8e20182005-01-29 00:39:08 +0000596 NewPN->reserveOperandSpace(BackedgeBlocks.size());
Chris Lattner514e8432005-03-25 06:37:22 +0000597 if (AA) AA->copyValue(PN, NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000598
599 // Loop over the PHI node, moving all entries except the one for the
600 // preheader over to the new PHI node.
601 unsigned PreheaderIdx = ~0U;
602 bool HasUniqueIncomingValue = true;
603 Value *UniqueValue = 0;
604 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
605 BasicBlock *IBB = PN->getIncomingBlock(i);
606 Value *IV = PN->getIncomingValue(i);
607 if (IBB == Preheader) {
608 PreheaderIdx = i;
609 } else {
610 NewPN->addIncoming(IV, IBB);
611 if (HasUniqueIncomingValue) {
612 if (UniqueValue == 0)
613 UniqueValue = IV;
614 else if (UniqueValue != IV)
615 HasUniqueIncomingValue = false;
616 }
617 }
618 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000619
Chris Lattnerc4622a62003-10-13 00:37:13 +0000620 // Delete all of the incoming values from the old PN except the preheader's
621 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
622 if (PreheaderIdx != 0) {
623 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
624 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
625 }
Chris Lattnerd8e20182005-01-29 00:39:08 +0000626 // Nuke all entries except the zero'th.
627 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
628 PN->removeIncomingValue(e-i, false);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000629
630 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
631 PN->addIncoming(NewPN, BEBlock);
632
633 // As an optimization, if all incoming values in the new PhiNode (which is a
634 // subset of the incoming values of the old PHI node) have the same value,
635 // eliminate the PHI Node.
636 if (HasUniqueIncomingValue) {
637 NewPN->replaceAllUsesWith(UniqueValue);
Chris Lattner514e8432005-03-25 06:37:22 +0000638 if (AA) AA->deleteValue(NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000639 BEBlock->getInstList().erase(NewPN);
640 }
641 }
642
643 // Now that all of the PHI nodes have been inserted and adjusted, modify the
644 // backedge blocks to just to the BEBlock instead of the header.
645 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
646 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
647 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
648 if (TI->getSuccessor(Op) == Header)
649 TI->setSuccessor(Op, BEBlock);
650 }
651
652 //===--- Update all analyses which we must preserve now -----------------===//
653
654 // Update Loop Information - we know that this block is now in the current
655 // loop and all parent loops.
656 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
657
Chris Lattnerc4622a62003-10-13 00:37:13 +0000658 // Update dominator information (set, immdom, domtree, and domfrontier)
659 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
660}
661
662/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
663/// different kinds of dominator information (dominator sets, immediate
664/// dominators, dominator trees, and dominance frontiers) after a new block has
665/// been added to the CFG.
666///
Chris Lattner14ab84a2004-02-05 21:12:24 +0000667/// This only supports the case when an existing block (known as "NewBBSucc"),
668/// had some of its predecessors factored into a new basic block. This
Chris Lattnerc4622a62003-10-13 00:37:13 +0000669/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner14ab84a2004-02-05 21:12:24 +0000670/// unconditional branch to NewBBSucc, and moves some predecessors of
671/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
672/// PredBlocks, even though they are the same as
673/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattnerc4622a62003-10-13 00:37:13 +0000674///
675void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
676 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000677 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattnerc4622a62003-10-13 00:37:13 +0000678 assert(succ_begin(NewBB) != succ_end(NewBB) &&
679 ++succ_begin(NewBB) == succ_end(NewBB) &&
680 "NewBB should have a single successor!");
Chris Lattner14ab84a2004-02-05 21:12:24 +0000681 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000682 DominatorSet &DS = getAnalysis<DominatorSet>();
683
Chris Lattner146d0df2004-04-01 19:06:07 +0000684 // Update dominator information... The blocks that dominate NewBB are the
685 // intersection of the dominators of predecessors, plus the block itself.
686 //
687 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
688 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
689 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
690 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
691 DS.addBasicBlock(NewBB, NewBBDomSet);
692
Chris Lattner14ab84a2004-02-05 21:12:24 +0000693 // The newly inserted basic block will dominate existing basic blocks iff the
694 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
695 // the non-pred blocks, then they all must be the same block!
Chris Lattner146d0df2004-04-01 19:06:07 +0000696 //
Chris Lattner14ab84a2004-02-05 21:12:24 +0000697 bool NewBBDominatesNewBBSucc = true;
698 {
699 BasicBlock *OnePred = PredBlocks[0];
700 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
701 if (PredBlocks[i] != OnePred) {
702 NewBBDominatesNewBBSucc = false;
703 break;
704 }
705
706 if (NewBBDominatesNewBBSucc)
707 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
708 PI != E; ++PI)
Chris Lattner2dd1c8d2004-02-05 23:20:59 +0000709 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000710 NewBBDominatesNewBBSucc = false;
711 break;
712 }
713 }
714
Chris Lattner146d0df2004-04-01 19:06:07 +0000715 // The other scenario where the new block can dominate its successors are when
716 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
717 // already.
718 if (!NewBBDominatesNewBBSucc) {
719 NewBBDominatesNewBBSucc = true;
720 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
721 PI != E; ++PI)
722 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
723 NewBBDominatesNewBBSucc = false;
724 break;
725 }
726 }
Chris Lattner650096a2003-02-27 20:27:08 +0000727
Chris Lattner14ab84a2004-02-05 21:12:24 +0000728 // If NewBB dominates some blocks, then it will dominate all blocks that
Chris Lattnerc0c953f2004-02-05 22:33:26 +0000729 // NewBBSucc does.
Chris Lattner14ab84a2004-02-05 21:12:24 +0000730 if (NewBBDominatesNewBBSucc) {
731 BasicBlock *PredBlock = PredBlocks[0];
732 Function *F = NewBB->getParent();
733 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattnerc0c953f2004-02-05 22:33:26 +0000734 if (DS.dominates(NewBBSucc, I))
Chris Lattner14ab84a2004-02-05 21:12:24 +0000735 DS.addDominator(I, NewBB);
736 }
737
Chris Lattner650096a2003-02-27 20:27:08 +0000738 // Update immediate dominator information if we have it...
739 BasicBlock *NewBBIDom = 0;
740 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000741 // To find the immediate dominator of the new exit node, we trace up the
742 // immediate dominators of a predecessor until we find a basic block that
743 // dominates the exit block.
Chris Lattner650096a2003-02-27 20:27:08 +0000744 //
Chris Lattnerc4622a62003-10-13 00:37:13 +0000745 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
Chris Lattner650096a2003-02-27 20:27:08 +0000746 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
747 assert(Dom != 0 && "No shared dominator found???");
748 Dom = ID->get(Dom);
749 }
750
751 // Set the immediate dominator now...
752 ID->addNewBlock(NewBB, Dom);
753 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
Chris Lattner14ab84a2004-02-05 21:12:24 +0000754
755 // If NewBB strictly dominates other blocks, we need to update their idom's
756 // now. The only block that need adjustment is the NewBBSucc block, whose
757 // idom should currently be set to PredBlocks[0].
Chris Lattner59fdf742004-04-01 19:21:46 +0000758 if (NewBBDominatesNewBBSucc)
Chris Lattner14ab84a2004-02-05 21:12:24 +0000759 ID->setImmediateDominator(NewBBSucc, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000760 }
761
762 // Update DominatorTree information if it is active.
763 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000764 // If we don't have ImmediateDominator info around, calculate the idom as
765 // above.
Chris Lattner650096a2003-02-27 20:27:08 +0000766 DominatorTree::Node *NewBBIDomNode;
767 if (NewBBIDom) {
768 NewBBIDomNode = DT->getNode(NewBBIDom);
769 } else {
Chris Lattnerc4622a62003-10-13 00:37:13 +0000770 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
Chris Lattnerbb9d03b2003-09-11 16:26:13 +0000771 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
Chris Lattner650096a2003-02-27 20:27:08 +0000772 NewBBIDomNode = NewBBIDomNode->getIDom();
773 assert(NewBBIDomNode && "No shared dominator found??");
774 }
Chris Lattnercda4aa62006-01-09 08:03:08 +0000775 NewBBIDom = NewBBIDomNode->getBlock();
Chris Lattner650096a2003-02-27 20:27:08 +0000776 }
777
Chris Lattner14ab84a2004-02-05 21:12:24 +0000778 // Create the new dominator tree node... and set the idom of NewBB.
779 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
780
781 // If NewBB strictly dominates other blocks, then it is now the immediate
782 // dominator of NewBBSucc. Update the dominator tree as appropriate.
783 if (NewBBDominatesNewBBSucc) {
784 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
Chris Lattner14ab84a2004-02-05 21:12:24 +0000785 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
786 }
Chris Lattner650096a2003-02-27 20:27:08 +0000787 }
788
Chris Lattnercda4aa62006-01-09 08:03:08 +0000789 // Update ET-Forest information if it is active.
790 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
791 EF->addNewBlock(NewBB, NewBBIDom);
792 if (NewBBDominatesNewBBSucc)
793 EF->setImmediateDominator(NewBBSucc, NewBB);
794 }
795
Chris Lattner650096a2003-02-27 20:27:08 +0000796 // Update dominance frontier information...
797 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
Chris Lattner89e959b2004-04-13 16:23:25 +0000798 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
799 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
800 // a predecessor of.
Chris Lattner14ab84a2004-02-05 21:12:24 +0000801 if (NewBBDominatesNewBBSucc) {
802 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
803 if (DFI != DF->end()) {
804 DominanceFrontier::DomSetType Set = DFI->second;
805 // Filter out stuff in Set that we do not dominate a predecessor of.
806 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
807 E = Set.end(); SetI != E;) {
808 bool DominatesPred = false;
809 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
810 PI != E; ++PI)
811 if (DS.dominates(NewBB, *PI))
812 DominatesPred = true;
813 if (!DominatesPred)
814 Set.erase(SetI++);
815 else
816 ++SetI;
817 }
Chris Lattner650096a2003-02-27 20:27:08 +0000818
Chris Lattner14ab84a2004-02-05 21:12:24 +0000819 DF->addBasicBlock(NewBB, Set);
820 }
821
822 } else {
823 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
824 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
825 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
826 DominanceFrontier::DomSetType NewDFSet;
827 NewDFSet.insert(NewBBSucc);
828 DF->addBasicBlock(NewBB, NewDFSet);
Chris Lattner89e959b2004-04-13 16:23:25 +0000829 }
Chris Lattnerc4622a62003-10-13 00:37:13 +0000830
Chris Lattner89e959b2004-04-13 16:23:25 +0000831 // Now we must loop over all of the dominance frontiers in the function,
832 // replacing occurrences of NewBBSucc with NewBB in some cases. All
833 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
834 // their dominance frontier must be updated to contain NewBB instead.
835 //
836 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
837 BasicBlock *Pred = PredBlocks[i];
838 // Get all of the dominators of the predecessor...
839 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
840 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
841 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
842 BasicBlock *PredDom = *PDI;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000843
Chris Lattner89e959b2004-04-13 16:23:25 +0000844 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
845 // dominate NewBBSucc but did dominate a predecessor of it. Now we
846 // change this entry to include NewBB in the DF instead of NewBBSucc.
847 DominanceFrontier::iterator DFI = DF->find(PredDom);
848 assert(DFI != DF->end() && "No dominance frontier for node?");
849 if (DFI->second.count(NewBBSucc)) {
850 // If NewBBSucc should not stay in our dominator frontier, remove it.
851 // We remove it unless there is a predecessor of NewBBSucc that we
852 // dominate, but we don't strictly dominate NewBBSucc.
853 bool ShouldRemove = true;
854 if (PredDom == NewBBSucc || !DS.dominates(PredDom, NewBBSucc)) {
855 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
856 // Check to see if it dominates any predecessors of NewBBSucc.
857 for (pred_iterator PI = pred_begin(NewBBSucc),
858 E = pred_end(NewBBSucc); PI != E; ++PI)
859 if (DS.dominates(PredDom, *PI)) {
860 ShouldRemove = false;
861 break;
862 }
Chris Lattner650096a2003-02-27 20:27:08 +0000863 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000864
Chris Lattner89e959b2004-04-13 16:23:25 +0000865 if (ShouldRemove)
866 DF->removeFromFrontier(DFI, NewBBSucc);
867 DF->addToFrontier(DFI, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000868 }
869 }
870 }
Chris Lattner650096a2003-02-27 20:27:08 +0000871 }
Chris Lattner61992f62002-09-26 16:17:31 +0000872}
Brian Gaeke960707c2003-11-11 22:41:34 +0000873