blob: f2ab0bdfa450fba5a98954dad0e3413236ff2e85 [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"
Chris Lattner3d27be12006-08-27 12:54:02 +000044#include "llvm/Support/Compiler.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 Lattner996795b2006-06-28 23:17:24 +000057 struct VISIBILITY_HIDDEN 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;
Chris Lattnercffbbee2006-02-14 22:34:08 +000061 LoopInfo *LI;
Chris Lattner514e8432005-03-25 06:37:22 +000062
Chris Lattner61992f62002-09-26 16:17:31 +000063 virtual bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +000064
Chris Lattner61992f62002-09-26 16:17:31 +000065 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 // We need loop information to identify the loops...
67 AU.addRequired<LoopInfo>();
Chris Lattner650096a2003-02-27 20:27:08 +000068 AU.addRequired<DominatorSet>();
Chris Lattner797cb2f2004-03-13 22:01:26 +000069 AU.addRequired<DominatorTree>();
Chris Lattner61992f62002-09-26 16:17:31 +000070
71 AU.addPreserved<LoopInfo>();
72 AU.addPreserved<DominatorSet>();
73 AU.addPreserved<ImmediateDominators>();
Chris Lattnercda4aa62006-01-09 08:03:08 +000074 AU.addPreserved<ETForest>();
Chris Lattner61992f62002-09-26 16:17:31 +000075 AU.addPreserved<DominatorTree>();
Chris Lattner650096a2003-02-27 20:27:08 +000076 AU.addPreserved<DominanceFrontier>();
Chris Lattnerf83ce5f2005-08-10 02:07:32 +000077 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
Chris Lattner61992f62002-09-26 16:17:31 +000078 }
79 private:
80 bool ProcessLoop(Loop *L);
Chris Lattner650096a2003-02-27 20:27:08 +000081 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
82 const std::vector<BasicBlock*> &Preds);
Chris Lattner82782632004-04-18 22:27:10 +000083 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner61992f62002-09-26 16:17:31 +000084 void InsertPreheaderForLoop(Loop *L);
Chris Lattner84170522004-04-13 05:05:33 +000085 Loop *SeparateNestedLoop(Loop *L);
Chris Lattnerc4622a62003-10-13 00:37:13 +000086 void InsertUniqueBackedgeBlock(Loop *L);
87
88 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
89 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner61992f62002-09-26 16:17:31 +000090 };
91
Chris Lattnerc2d3d312006-08-27 22:42:52 +000092 RegisterPass<LoopSimplify>
Chris Lattner154e4d52003-10-12 21:43:28 +000093 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner61992f62002-09-26 16:17:31 +000094}
95
96// Publically exposed interface to pass...
Chris Lattner7710f2f2003-12-10 17:20:35 +000097const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
Chris Lattner3e860842004-09-20 04:43:15 +000098FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner61992f62002-09-26 16:17:31 +000099
Chris Lattner61992f62002-09-26 16:17:31 +0000100/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
101/// it in any convenient order) inserting preheaders...
102///
Chris Lattner154e4d52003-10-12 21:43:28 +0000103bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner61992f62002-09-26 16:17:31 +0000104 bool Changed = false;
Chris Lattnercffbbee2006-02-14 22:34:08 +0000105 LI = &getAnalysis<LoopInfo>();
Chris Lattner514e8432005-03-25 06:37:22 +0000106 AA = getAnalysisToUpdate<AliasAnalysis>();
Chris Lattner61992f62002-09-26 16:17:31 +0000107
Chris Lattner85d99442006-08-12 04:51:20 +0000108 // Check to see that no blocks (other than the header) in loops have
109 // predecessors that are not in loops. This is not valid for natural loops,
110 // but can occur if the blocks are unreachable. Since they are unreachable we
111 // can just shamelessly destroy their terminators to make them not branch into
112 // the loop!
113 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
114 // This case can only occur for unreachable blocks. Blocks that are
115 // unreachable can't be in loops, so filter those blocks out.
116 if (LI->getLoopFor(BB)) continue;
117
118 bool BlockUnreachable = false;
119 TerminatorInst *TI = BB->getTerminator();
120
121 // Check to see if any successors of this block are non-loop-header loops
122 // that are not the header.
123 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
124 // If this successor is not in a loop, BB is clearly ok.
125 Loop *L = LI->getLoopFor(TI->getSuccessor(i));
126 if (!L) continue;
127
128 // If the succ is the loop header, and if L is a top-level loop, then this
129 // is an entrance into a loop through the header, which is also ok.
130 if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
131 continue;
132
133 // Otherwise, this is an entrance into a loop from some place invalid.
134 // Either the loop structure is invalid and this is not a natural loop (in
135 // which case the compiler is buggy somewhere else) or BB is unreachable.
136 BlockUnreachable = true;
137 break;
138 }
139
140 // If this block is ok, check the next one.
141 if (!BlockUnreachable) continue;
142
143 // Otherwise, this block is dead. To clean up the CFG and to allow later
144 // loop transformations to ignore this case, we delete the edges into the
145 // loop by replacing the terminator.
146
147 // Remove PHI entries from the successors.
148 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
149 TI->getSuccessor(i)->removePredecessor(BB);
150
151 // Add a new unreachable instruction.
152 new UnreachableInst(TI);
153
154 // Delete the dead terminator.
155 if (AA) AA->deleteValue(&BB->back());
156 BB->getInstList().pop_back();
157 Changed |= true;
158 }
159
Chris Lattnercffbbee2006-02-14 22:34:08 +0000160 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000161 Changed |= ProcessLoop(*I);
Chris Lattner61992f62002-09-26 16:17:31 +0000162
163 return Changed;
164}
165
Chris Lattner61992f62002-09-26 16:17:31 +0000166/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
167/// all loops have preheaders.
168///
Chris Lattner154e4d52003-10-12 21:43:28 +0000169bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000170 bool Changed = false;
Chris Lattnerf18b3962006-08-12 05:25:00 +0000171ReprocessLoop:
172
Chris Lattner9c5693f2006-02-14 23:06:02 +0000173 // Canonicalize inner loops before outer loops. Inner loop canonicalization
174 // can provide work for the outer loop to canonicalize.
175 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
176 Changed |= ProcessLoop(*I);
177
Chris Lattnerd0788122004-03-14 03:59:22 +0000178 assert(L->getBlocks()[0] == L->getHeader() &&
179 "Header isn't first block in loop?");
Chris Lattnerd0788122004-03-14 03:59:22 +0000180
Chris Lattner85d99442006-08-12 04:51:20 +0000181 // Does the loop already have a preheader? If so, don't insert one.
Chris Lattner61992f62002-09-26 16:17:31 +0000182 if (L->getLoopPreheader() == 0) {
183 InsertPreheaderForLoop(L);
184 NumInserted++;
185 Changed = true;
186 }
187
Chris Lattner7710f2f2003-12-10 17:20:35 +0000188 // Next, check to make sure that all exit nodes of the loop only have
189 // predecessors that are inside of the loop. This check guarantees that the
190 // loop preheader/header will dominate the exit blocks. If the exit block has
Chris Lattner02f53ad2006-02-12 01:59:10 +0000191 // predecessors from outside of the loop, split the edge now.
192 std::vector<BasicBlock*> ExitBlocks;
193 L->getExitBlocks(ExitBlocks);
Chris Lattnercffbbee2006-02-14 22:34:08 +0000194
Chris Lattner02f53ad2006-02-12 01:59:10 +0000195 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000196 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
197 E = ExitBlockSet.end(); I != E; ++I) {
198 BasicBlock *ExitBlock = *I;
Chris Lattnerdaa12132004-07-15 05:36:31 +0000199 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
200 PI != PE; ++PI)
Chris Lattner05bf90d2006-02-11 02:13:17 +0000201 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
202 // allowed.
Chris Lattner02f53ad2006-02-12 01:59:10 +0000203 if (!L->contains(*PI)) {
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000204 RewriteLoopExitBlock(L, ExitBlock);
Chris Lattnerdaa12132004-07-15 05:36:31 +0000205 NumInserted++;
206 Changed = true;
207 break;
208 }
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000209 }
Chris Lattner650096a2003-02-27 20:27:08 +0000210
Chris Lattner84170522004-04-13 05:05:33 +0000211 // If the header has more than two predecessors at this point (from the
212 // preheader and from multiple backedges), we must adjust the loop.
Chris Lattnerf18b3962006-08-12 05:25:00 +0000213 unsigned NumBackedges = L->getNumBackEdges();
214 if (NumBackedges != 1) {
215 // If this is really a nested loop, rip it out into a child loop. Don't do
216 // this for loops with a giant number of backedges, just factor them into a
217 // common backedge instead.
218 if (NumBackedges < 8) {
219 if (Loop *NL = SeparateNestedLoop(L)) {
220 ++NumNested;
221 // This is a big restructuring change, reprocess the whole loop.
222 ProcessLoop(NL);
223 Changed = true;
224 // GCC doesn't tail recursion eliminate this.
225 goto ReprocessLoop;
226 }
Chris Lattner84170522004-04-13 05:05:33 +0000227 }
228
Chris Lattnerf18b3962006-08-12 05:25:00 +0000229 // If we either couldn't, or didn't want to, identify nesting of the loops,
230 // insert a new block that all backedges target, then make it jump to the
231 // loop header.
Chris Lattnerc4622a62003-10-13 00:37:13 +0000232 InsertUniqueBackedgeBlock(L);
233 NumInserted++;
234 Changed = true;
235 }
236
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000237 // Scan over the PHI nodes in the loop header. Since they now have only two
238 // incoming values (the loop is canonicalized), we may have simplified the PHI
239 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
240 PHINode *PN;
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000241 for (BasicBlock::iterator I = L->getHeader()->begin();
242 (PN = dyn_cast<PHINode>(I++)); )
Chris Lattner62df7982005-08-10 17:15:20 +0000243 if (Value *V = PN->hasConstantValue()) {
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000244 PN->replaceAllUsesWith(V);
245 PN->eraseFromParent();
246 }
247
Chris Lattner61992f62002-09-26 16:17:31 +0000248 return Changed;
249}
250
Chris Lattner650096a2003-02-27 20:27:08 +0000251/// SplitBlockPredecessors - Split the specified block into two blocks. We want
252/// to move the predecessors specified in the Preds list to point to the new
253/// block, leaving the remaining predecessors pointing to BB. This method
254/// updates the SSA PHINode's, but no other analyses.
255///
Chris Lattner154e4d52003-10-12 21:43:28 +0000256BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
257 const char *Suffix,
Chris Lattner650096a2003-02-27 20:27:08 +0000258 const std::vector<BasicBlock*> &Preds) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000259
Chris Lattner650096a2003-02-27 20:27:08 +0000260 // Create new basic block, insert right before the original block...
Chris Lattner8d414ad2004-02-04 03:58:28 +0000261 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattner650096a2003-02-27 20:27:08 +0000262
263 // The preheader first gets an unconditional branch to the loop header...
Chris Lattnera2960002003-11-21 16:52:05 +0000264 BranchInst *BI = new BranchInst(BB, NewBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000265
Chris Lattner650096a2003-02-27 20:27:08 +0000266 // For every PHI node in the block, insert a PHI node into NewBB where the
267 // incoming values from the out of loop edges are moved to NewBB. We have two
268 // possible cases here. If the loop is dead, we just insert dummy entries
269 // into the PHI nodes for the new edge. If the loop is not dead, we move the
270 // incoming edges in BB into new PHI nodes in NewBB.
271 //
272 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner031a3f82003-12-19 06:27:08 +0000273 // Check to see if the values being merged into the new block need PHI
274 // nodes. If so, insert them.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000275 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
276 PHINode *PN = cast<PHINode>(I);
Chris Lattner84170522004-04-13 05:05:33 +0000277 ++I;
278
Chris Lattner031a3f82003-12-19 06:27:08 +0000279 // Check to see if all of the values coming in are the same. If so, we
280 // don't need to create a new PHI node.
281 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
282 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
283 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
284 InVal = 0;
285 break;
286 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000287
Chris Lattner031a3f82003-12-19 06:27:08 +0000288 // If the values coming into the block are not the same, we need a PHI.
289 if (InVal == 0) {
Chris Lattner6c237bc2003-12-09 23:12:55 +0000290 // Create the new PHI node, insert it into NewBB at the end of the block
291 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
Chris Lattner514e8432005-03-25 06:37:22 +0000292 if (AA) AA->copyValue(PN, NewPHI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000293
Chris Lattner6c237bc2003-12-09 23:12:55 +0000294 // Move all of the edges from blocks outside the loop to the new PHI
295 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Chris Lattner84170522004-04-13 05:05:33 +0000296 Value *V = PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000297 NewPHI->addIncoming(V, Preds[i]);
298 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000299 InVal = NewPHI;
300 } else {
301 // Remove all of the edges coming into the PHI nodes from outside of the
302 // block.
303 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
304 PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000305 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000306
307 // Add an incoming value to the PHI node in the loop for the preheader
308 // edge.
309 PN->addIncoming(InVal, NewBB);
Chris Lattner84170522004-04-13 05:05:33 +0000310
311 // Can we eliminate this phi node now?
Chris Lattner257efb22005-08-05 00:57:45 +0000312 if (Value *V = PN->hasConstantValue(true)) {
Chris Lattnere29d6342004-10-17 21:22:38 +0000313 if (!isa<Instruction>(V) ||
314 getAnalysis<DominatorSet>().dominates(cast<Instruction>(V), PN)) {
315 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000316 if (AA) AA->deleteValue(PN);
Chris Lattnere29d6342004-10-17 21:22:38 +0000317 BB->getInstList().erase(PN);
318 }
Chris Lattner84170522004-04-13 05:05:33 +0000319 }
Chris Lattner650096a2003-02-27 20:27:08 +0000320 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000321
Chris Lattner650096a2003-02-27 20:27:08 +0000322 // Now that the PHI nodes are updated, actually move the edges from
323 // Preds to point to NewBB instead of BB.
324 //
325 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
326 TerminatorInst *TI = Preds[i]->getTerminator();
327 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
328 if (TI->getSuccessor(s) == BB)
329 TI->setSuccessor(s, NewBB);
330 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000331
Chris Lattner650096a2003-02-27 20:27:08 +0000332 } else { // Otherwise the loop is dead...
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000333 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
334 PHINode *PN = cast<PHINode>(I);
Chris Lattner650096a2003-02-27 20:27:08 +0000335 // Insert dummy values as the incoming value...
336 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000337 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000338 }
Chris Lattner650096a2003-02-27 20:27:08 +0000339 return NewBB;
340}
341
Chris Lattner61992f62002-09-26 16:17:31 +0000342/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
343/// preheader, this method is called to insert one. This method has two phases:
344/// preheader insertion and analysis updating.
345///
Chris Lattner154e4d52003-10-12 21:43:28 +0000346void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000347 BasicBlock *Header = L->getHeader();
348
349 // Compute the set of predecessors of the loop that are not in the loop.
350 std::vector<BasicBlock*> OutsideBlocks;
351 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
352 PI != PE; ++PI)
Chris Lattner05bf90d2006-02-11 02:13:17 +0000353 if (!L->contains(*PI)) // Coming in from outside the loop?
354 OutsideBlocks.push_back(*PI); // Keep track of it...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000355
Chris Lattner608cd052006-09-23 07:40:52 +0000356 // Split out the loop pre-header.
Chris Lattner650096a2003-02-27 20:27:08 +0000357 BasicBlock *NewBB =
358 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner608cd052006-09-23 07:40:52 +0000359
Misha Brukmanb1c93172005-04-21 23:48:37 +0000360
Chris Lattner61992f62002-09-26 16:17:31 +0000361 //===--------------------------------------------------------------------===//
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000362 // Update analysis results now that we have performed the transformation
Chris Lattner61992f62002-09-26 16:17:31 +0000363 //
Misha Brukmanb1c93172005-04-21 23:48:37 +0000364
Chris Lattner61992f62002-09-26 16:17:31 +0000365 // We know that we have loop information to update... update it now.
366 if (Loop *Parent = L->getParentLoop())
Chris Lattnercffbbee2006-02-14 22:34:08 +0000367 Parent->addBasicBlockToLoop(NewBB, *LI);
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000368
Chris Lattner608cd052006-09-23 07:40:52 +0000369 UpdateDomInfoForRevectoredPreds(NewBB, OutsideBlocks);
Chris Lattner650096a2003-02-27 20:27:08 +0000370}
371
Chris Lattner84170522004-04-13 05:05:33 +0000372/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
373/// blocks. This method is used to split exit blocks that have predecessors
374/// outside of the loop.
Chris Lattner82782632004-04-18 22:27:10 +0000375BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattner650096a2003-02-27 20:27:08 +0000376 std::vector<BasicBlock*> LoopBlocks;
377 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
378 if (L->contains(*I))
379 LoopBlocks.push_back(*I);
380
Chris Lattner10b2b052003-02-27 22:31:07 +0000381 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
382 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
383
Chris Lattnercffbbee2006-02-14 22:34:08 +0000384 // Update Loop Information - we know that the new block will be in whichever
385 // loop the Exit block is in. Note that it may not be in that immediate loop,
386 // if the successor is some other loop header. In that case, we continue
387 // walking up the loop tree to find a loop that contains both the successor
388 // block and the predecessor block.
389 Loop *SuccLoop = LI->getLoopFor(Exit);
390 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
391 SuccLoop = SuccLoop->getParentLoop();
392 if (SuccLoop)
393 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner32a39c22003-02-28 03:07:54 +0000394
Chris Lattnerc4622a62003-10-13 00:37:13 +0000395 // Update dominator information (set, immdom, domtree, and domfrontier)
396 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
Chris Lattner82782632004-04-18 22:27:10 +0000397 return NewBB;
Chris Lattnerc4622a62003-10-13 00:37:13 +0000398}
399
Chris Lattner84170522004-04-13 05:05:33 +0000400/// AddBlockAndPredsToSet - Add the specified block, and all of its
401/// predecessors, to the specified set, if it's not already in there. Stop
402/// predecessor traversal when we reach StopBlock.
403static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
404 std::set<BasicBlock*> &Blocks) {
405 if (!Blocks.insert(BB).second) return; // already processed.
406 if (BB == StopBlock) return; // Stop here!
407
408 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
409 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
410}
411
Chris Lattnera6e22812004-04-13 15:21:18 +0000412/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
413/// PHI node that tells us how to partition the loops.
Chris Lattner514e8432005-03-25 06:37:22 +0000414static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorSet &DS,
415 AliasAnalysis *AA) {
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000416 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
417 PHINode *PN = cast<PHINode>(I);
Chris Lattnera6e22812004-04-13 15:21:18 +0000418 ++I;
Nate Begemanb3923212005-08-04 23:24:19 +0000419 if (Value *V = PN->hasConstantValue())
Chris Lattnere29d6342004-10-17 21:22:38 +0000420 if (!isa<Instruction>(V) || DS.dominates(cast<Instruction>(V), PN)) {
421 // This is a degenerate PHI already, don't modify it!
422 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000423 if (AA) AA->deleteValue(PN);
Chris Lattnerdd3ec922005-03-06 21:35:38 +0000424 PN->eraseFromParent();
Chris Lattnere29d6342004-10-17 21:22:38 +0000425 continue;
426 }
427
428 // Scan this PHI node looking for a use of the PHI node by itself.
429 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
430 if (PN->getIncomingValue(i) == PN &&
431 L->contains(PN->getIncomingBlock(i)))
432 // We found something tasty to remove.
433 return PN;
Chris Lattnera6e22812004-04-13 15:21:18 +0000434 }
435 return 0;
436}
437
Chris Lattner84170522004-04-13 05:05:33 +0000438/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
439/// them out into a nested loop. This is important for code that looks like
440/// this:
441///
442/// Loop:
443/// ...
444/// br cond, Loop, Next
445/// ...
446/// br cond2, Loop, Out
447///
448/// To identify this common case, we look at the PHI nodes in the header of the
449/// loop. PHI nodes with unchanging values on one backedge correspond to values
450/// that change in the "outer" loop, but not in the "inner" loop.
451///
452/// If we are able to separate out a loop, return the new outer loop that was
453/// created.
454///
455Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
Chris Lattner514e8432005-03-25 06:37:22 +0000456 PHINode *PN = FindPHIToPartitionLoops(L, getAnalysis<DominatorSet>(), AA);
Chris Lattnera6e22812004-04-13 15:21:18 +0000457 if (PN == 0) return 0; // No known way to partition.
Chris Lattner84170522004-04-13 05:05:33 +0000458
Chris Lattnera6e22812004-04-13 15:21:18 +0000459 // Pull out all predecessors that have varying values in the loop. This
460 // handles the case when a PHI node has multiple instances of itself as
461 // arguments.
Chris Lattner84170522004-04-13 05:05:33 +0000462 std::vector<BasicBlock*> OuterLoopPreds;
Chris Lattnera6e22812004-04-13 15:21:18 +0000463 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
464 if (PN->getIncomingValue(i) != PN ||
465 !L->contains(PN->getIncomingBlock(i)))
466 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner84170522004-04-13 05:05:33 +0000467
Chris Lattner89e959b2004-04-13 16:23:25 +0000468 BasicBlock *Header = L->getHeader();
Chris Lattner84170522004-04-13 05:05:33 +0000469 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
470
471 // Update dominator information (set, immdom, domtree, and domfrontier)
472 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
473
474 // Create the new outer loop.
475 Loop *NewOuter = new Loop();
476
Chris Lattner84170522004-04-13 05:05:33 +0000477 // Change the parent loop to use the outer loop as its child now.
478 if (Loop *Parent = L->getParentLoop())
479 Parent->replaceChildLoopWith(L, NewOuter);
480 else
Chris Lattnercffbbee2006-02-14 22:34:08 +0000481 LI->changeTopLevelLoop(L, NewOuter);
Chris Lattner84170522004-04-13 05:05:33 +0000482
483 // This block is going to be our new header block: add it to this loop and all
484 // parent loops.
Chris Lattnercffbbee2006-02-14 22:34:08 +0000485 NewOuter->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner84170522004-04-13 05:05:33 +0000486
487 // L is now a subloop of our outer loop.
488 NewOuter->addChildLoop(L);
489
Chris Lattner84170522004-04-13 05:05:33 +0000490 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
491 NewOuter->addBlockEntry(L->getBlocks()[i]);
492
493 // Determine which blocks should stay in L and which should be moved out to
494 // the Outer loop now.
495 DominatorSet &DS = getAnalysis<DominatorSet>();
496 std::set<BasicBlock*> BlocksInL;
497 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
498 if (DS.dominates(Header, *PI))
499 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
500
501
502 // Scan all of the loop children of L, moving them to OuterLoop if they are
503 // not part of the inner loop.
504 for (Loop::iterator I = L->begin(); I != L->end(); )
505 if (BlocksInL.count((*I)->getHeader()))
506 ++I; // Loop remains in L
507 else
508 NewOuter->addChildLoop(L->removeChildLoop(I));
509
510 // Now that we know which blocks are in L and which need to be moved to
511 // OuterLoop, move any blocks that need it.
512 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
513 BasicBlock *BB = L->getBlocks()[i];
514 if (!BlocksInL.count(BB)) {
515 // Move this block to the parent, updating the exit blocks sets
516 L->removeBlockFromLoop(BB);
Chris Lattnercffbbee2006-02-14 22:34:08 +0000517 if ((*LI)[BB] == L)
518 LI->changeLoopFor(BB, NewOuter);
Chris Lattner84170522004-04-13 05:05:33 +0000519 --i;
520 }
521 }
522
Chris Lattner84170522004-04-13 05:05:33 +0000523 return NewOuter;
524}
525
526
527
Chris Lattnerc4622a62003-10-13 00:37:13 +0000528/// InsertUniqueBackedgeBlock - This method is called when the specified loop
529/// has more than one backedge in it. If this occurs, revector all of these
530/// backedges to target a new basic block and have that block branch to the loop
531/// header. This ensures that loops have exactly one backedge.
532///
533void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
534 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
535
536 // Get information about the loop
537 BasicBlock *Preheader = L->getLoopPreheader();
538 BasicBlock *Header = L->getHeader();
539 Function *F = Header->getParent();
540
541 // Figure out which basic blocks contain back-edges to the loop header.
542 std::vector<BasicBlock*> BackedgeBlocks;
543 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
544 if (*I != Preheader) BackedgeBlocks.push_back(*I);
545
546 // Create and insert the new backedge block...
547 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattnera2960002003-11-21 16:52:05 +0000548 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000549
550 // Move the new backedge block to right after the last backedge block.
551 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
552 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000553
Chris Lattnerc4622a62003-10-13 00:37:13 +0000554 // Now that the block has been inserted into the function, create PHI nodes in
555 // the backedge block which correspond to any PHI nodes in the header block.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000556 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
557 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000558 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
559 BETerminator);
Chris Lattnerd8e20182005-01-29 00:39:08 +0000560 NewPN->reserveOperandSpace(BackedgeBlocks.size());
Chris Lattner514e8432005-03-25 06:37:22 +0000561 if (AA) AA->copyValue(PN, NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000562
563 // Loop over the PHI node, moving all entries except the one for the
564 // preheader over to the new PHI node.
565 unsigned PreheaderIdx = ~0U;
566 bool HasUniqueIncomingValue = true;
567 Value *UniqueValue = 0;
568 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
569 BasicBlock *IBB = PN->getIncomingBlock(i);
570 Value *IV = PN->getIncomingValue(i);
571 if (IBB == Preheader) {
572 PreheaderIdx = i;
573 } else {
574 NewPN->addIncoming(IV, IBB);
575 if (HasUniqueIncomingValue) {
576 if (UniqueValue == 0)
577 UniqueValue = IV;
578 else if (UniqueValue != IV)
579 HasUniqueIncomingValue = false;
580 }
581 }
582 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000583
Chris Lattnerc4622a62003-10-13 00:37:13 +0000584 // Delete all of the incoming values from the old PN except the preheader's
585 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
586 if (PreheaderIdx != 0) {
587 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
588 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
589 }
Chris Lattnerd8e20182005-01-29 00:39:08 +0000590 // Nuke all entries except the zero'th.
591 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
592 PN->removeIncomingValue(e-i, false);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000593
594 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
595 PN->addIncoming(NewPN, BEBlock);
596
597 // As an optimization, if all incoming values in the new PhiNode (which is a
598 // subset of the incoming values of the old PHI node) have the same value,
599 // eliminate the PHI Node.
600 if (HasUniqueIncomingValue) {
601 NewPN->replaceAllUsesWith(UniqueValue);
Chris Lattner514e8432005-03-25 06:37:22 +0000602 if (AA) AA->deleteValue(NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000603 BEBlock->getInstList().erase(NewPN);
604 }
605 }
606
607 // Now that all of the PHI nodes have been inserted and adjusted, modify the
608 // backedge blocks to just to the BEBlock instead of the header.
609 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
610 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
611 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
612 if (TI->getSuccessor(Op) == Header)
613 TI->setSuccessor(Op, BEBlock);
614 }
615
616 //===--- Update all analyses which we must preserve now -----------------===//
617
618 // Update Loop Information - we know that this block is now in the current
619 // loop and all parent loops.
Chris Lattnercffbbee2006-02-14 22:34:08 +0000620 L->addBasicBlockToLoop(BEBlock, *LI);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000621
Chris Lattnerc4622a62003-10-13 00:37:13 +0000622 // Update dominator information (set, immdom, domtree, and domfrontier)
623 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
624}
625
626/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
627/// different kinds of dominator information (dominator sets, immediate
628/// dominators, dominator trees, and dominance frontiers) after a new block has
629/// been added to the CFG.
630///
Chris Lattner14ab84a2004-02-05 21:12:24 +0000631/// This only supports the case when an existing block (known as "NewBBSucc"),
632/// had some of its predecessors factored into a new basic block. This
Chris Lattnerc4622a62003-10-13 00:37:13 +0000633/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner14ab84a2004-02-05 21:12:24 +0000634/// unconditional branch to NewBBSucc, and moves some predecessors of
635/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
636/// PredBlocks, even though they are the same as
637/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattnerc4622a62003-10-13 00:37:13 +0000638///
639void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
640 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000641 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattnerc4622a62003-10-13 00:37:13 +0000642 assert(succ_begin(NewBB) != succ_end(NewBB) &&
643 ++succ_begin(NewBB) == succ_end(NewBB) &&
644 "NewBB should have a single successor!");
Chris Lattner14ab84a2004-02-05 21:12:24 +0000645 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000646 DominatorSet &DS = getAnalysis<DominatorSet>();
647
Chris Lattner146d0df2004-04-01 19:06:07 +0000648 // Update dominator information... The blocks that dominate NewBB are the
649 // intersection of the dominators of predecessors, plus the block itself.
650 //
651 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
Chris Lattner608cd052006-09-23 07:40:52 +0000652 {
653 unsigned i, e = PredBlocks.size();
654 // It is possible for some preds to not be reachable, and thus have empty
655 // dominator sets (all blocks must dom themselves, so no domset would
656 // otherwise be empty). If we see any of these, don't intersect with them,
657 // as that would certainly leave the resultant set empty.
658 for (i = 1; NewBBDomSet.empty(); ++i) {
659 assert(i != e && "Didn't find reachable pred?");
660 NewBBDomSet = DS.getDominators(PredBlocks[i]);
661 }
662
663 // Intersect the rest of the non-empty sets.
664 for (; i != e; ++i) {
665 const DominatorSet::DomSetType &PredDS = DS.getDominators(PredBlocks[i]);
666 if (!PredDS.empty())
667 set_intersect(NewBBDomSet, PredDS);
668 }
669 NewBBDomSet.insert(NewBB); // All blocks dominate themselves.
670 DS.addBasicBlock(NewBB, NewBBDomSet);
671 }
Chris Lattner146d0df2004-04-01 19:06:07 +0000672
Chris Lattner14ab84a2004-02-05 21:12:24 +0000673 // The newly inserted basic block will dominate existing basic blocks iff the
674 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
675 // the non-pred blocks, then they all must be the same block!
Chris Lattner146d0df2004-04-01 19:06:07 +0000676 //
Chris Lattner14ab84a2004-02-05 21:12:24 +0000677 bool NewBBDominatesNewBBSucc = true;
678 {
679 BasicBlock *OnePred = PredBlocks[0];
Chris Lattner608cd052006-09-23 07:40:52 +0000680 unsigned i, e = PredBlocks.size();
681 for (i = 1; !DS.isReachable(OnePred); ++i) {
682 assert(i != e && "Didn't find reachable pred?");
683 OnePred = PredBlocks[i];
684 }
685
686 for (; i != e; ++i)
687 if (PredBlocks[i] != OnePred && DS.isReachable(PredBlocks[i])) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000688 NewBBDominatesNewBBSucc = false;
689 break;
690 }
691
692 if (NewBBDominatesNewBBSucc)
693 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
694 PI != E; ++PI)
Chris Lattner2dd1c8d2004-02-05 23:20:59 +0000695 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000696 NewBBDominatesNewBBSucc = false;
697 break;
698 }
699 }
700
Chris Lattner146d0df2004-04-01 19:06:07 +0000701 // The other scenario where the new block can dominate its successors are when
702 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
703 // already.
704 if (!NewBBDominatesNewBBSucc) {
705 NewBBDominatesNewBBSucc = true;
706 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
707 PI != E; ++PI)
708 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
709 NewBBDominatesNewBBSucc = false;
710 break;
711 }
712 }
Chris Lattner650096a2003-02-27 20:27:08 +0000713
Chris Lattner14ab84a2004-02-05 21:12:24 +0000714 // If NewBB dominates some blocks, then it will dominate all blocks that
Chris Lattnerc0c953f2004-02-05 22:33:26 +0000715 // NewBBSucc does.
Chris Lattner14ab84a2004-02-05 21:12:24 +0000716 if (NewBBDominatesNewBBSucc) {
717 BasicBlock *PredBlock = PredBlocks[0];
718 Function *F = NewBB->getParent();
719 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattnerc0c953f2004-02-05 22:33:26 +0000720 if (DS.dominates(NewBBSucc, I))
Chris Lattner14ab84a2004-02-05 21:12:24 +0000721 DS.addDominator(I, NewBB);
722 }
723
Chris Lattner608cd052006-09-23 07:40:52 +0000724 // Update immediate dominator information if we have it.
Chris Lattner650096a2003-02-27 20:27:08 +0000725 BasicBlock *NewBBIDom = 0;
726 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000727 // To find the immediate dominator of the new exit node, we trace up the
728 // immediate dominators of a predecessor until we find a basic block that
729 // dominates the exit block.
Chris Lattner650096a2003-02-27 20:27:08 +0000730 //
Chris Lattner608cd052006-09-23 07:40:52 +0000731 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor.
732
733 // Find a reachable pred.
734 for (unsigned i = 1; !DS.isReachable(Dom); ++i) {
735 assert(i != PredBlocks.size() && "Didn't find reachable pred!");
736 Dom = PredBlocks[i];
737 }
738
739 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator.
Chris Lattner650096a2003-02-27 20:27:08 +0000740 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 Lattner608cd052006-09-23 07:40:52 +0000763 // Scan all the pred blocks that were pulled out. Any individual one may
764 // actually be unreachable, which would mean it doesn't have dom info.
765 NewBBIDomNode = 0;
766 for (unsigned i = 0; !NewBBIDomNode; ++i) {
767 assert(i != PredBlocks.size() && "No reachable preds?");
768 NewBBIDomNode = DT->getNode(PredBlocks[i]);
769 }
770
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