blob: 044ca5b0fc33bf1825b15c5dba4506ebf5631ca0 [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
Chris Lattner45f966d2006-12-19 22:17:40 +000035#define DEBUG_TYPE "loopsimplify"
Chris Lattner61992f62002-09-26 16:17:31 +000036#include "llvm/Transforms/Scalar.h"
Chris Lattnerd0788122004-03-14 03:59:22 +000037#include "llvm/Constant.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000038#include "llvm/Instructions.h"
Chris Lattnerd0788122004-03-14 03:59:22 +000039#include "llvm/Function.h"
40#include "llvm/Type.h"
Chris Lattner514e8432005-03-25 06:37:22 +000041#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner031a3f82003-12-19 06:27:08 +000042#include "llvm/Analysis/Dominators.h"
43#include "llvm/Analysis/LoopInfo.h"
Chris Lattner61992f62002-09-26 16:17:31 +000044#include "llvm/Support/CFG.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000045#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000046#include "llvm/ADT/SetOperations.h"
47#include "llvm/ADT/SetVector.h"
48#include "llvm/ADT/Statistic.h"
49#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattner7710f2f2003-12-10 17:20:35 +000050using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000051
Chris Lattner45f966d2006-12-19 22:17:40 +000052STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
53STATISTIC(NumNested , "Number of nested loops split out");
Chris Lattner61992f62002-09-26 16:17:31 +000054
Chris Lattner45f966d2006-12-19 22:17:40 +000055namespace {
Chris Lattner996795b2006-06-28 23:17:24 +000056 struct VISIBILITY_HIDDEN 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;
Chris Lattnercffbbee2006-02-14 22:34:08 +000060 LoopInfo *LI;
Chris Lattner514e8432005-03-25 06:37:22 +000061
Chris Lattner61992f62002-09-26 16:17:31 +000062 virtual bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +000063
Chris Lattner61992f62002-09-26 16:17:31 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 // We need loop information to identify the loops...
66 AU.addRequired<LoopInfo>();
Owen Andersonf7ebea12007-04-07 18:23:27 +000067 AU.addRequired<DominatorSet>();
Chris Lattner797cb2f2004-03-13 22:01:26 +000068 AU.addRequired<DominatorTree>();
Devang Patel1758cb52007-03-20 20:18:12 +000069 AU.addRequired<ETForest>();
Chris Lattner61992f62002-09-26 16:17:31 +000070
71 AU.addPreserved<LoopInfo>();
Owen Andersonf7ebea12007-04-07 18:23:27 +000072 AU.addPreserved<DominatorSet>();
Chris Lattner61992f62002-09-26 16:17:31 +000073 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);
Chris Lattner6bd6da42006-09-23 08:19:21 +000087 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
88 std::vector<BasicBlock*> &SplitPreds,
89 Loop *L);
90
Chris Lattnerc4622a62003-10-13 00:37:13 +000091 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
92 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner61992f62002-09-26 16:17:31 +000093 };
94
Chris Lattnerc2d3d312006-08-27 22:42:52 +000095 RegisterPass<LoopSimplify>
Chris Lattner154e4d52003-10-12 21:43:28 +000096 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner61992f62002-09-26 16:17:31 +000097}
98
99// Publically exposed interface to pass...
Chris Lattner7710f2f2003-12-10 17:20:35 +0000100const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
Chris Lattner3e860842004-09-20 04:43:15 +0000101FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner61992f62002-09-26 16:17:31 +0000102
Chris Lattner61992f62002-09-26 16:17:31 +0000103/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
104/// it in any convenient order) inserting preheaders...
105///
Chris Lattner154e4d52003-10-12 21:43:28 +0000106bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner61992f62002-09-26 16:17:31 +0000107 bool Changed = false;
Chris Lattnercffbbee2006-02-14 22:34:08 +0000108 LI = &getAnalysis<LoopInfo>();
Chris Lattner514e8432005-03-25 06:37:22 +0000109 AA = getAnalysisToUpdate<AliasAnalysis>();
Chris Lattner61992f62002-09-26 16:17:31 +0000110
Chris Lattner85d99442006-08-12 04:51:20 +0000111 // Check to see that no blocks (other than the header) in loops have
112 // predecessors that are not in loops. This is not valid for natural loops,
113 // but can occur if the blocks are unreachable. Since they are unreachable we
114 // can just shamelessly destroy their terminators to make them not branch into
115 // the loop!
116 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
117 // This case can only occur for unreachable blocks. Blocks that are
118 // unreachable can't be in loops, so filter those blocks out.
119 if (LI->getLoopFor(BB)) continue;
120
121 bool BlockUnreachable = false;
122 TerminatorInst *TI = BB->getTerminator();
123
124 // Check to see if any successors of this block are non-loop-header loops
125 // that are not the header.
126 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
127 // If this successor is not in a loop, BB is clearly ok.
128 Loop *L = LI->getLoopFor(TI->getSuccessor(i));
129 if (!L) continue;
130
131 // If the succ is the loop header, and if L is a top-level loop, then this
132 // is an entrance into a loop through the header, which is also ok.
133 if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
134 continue;
135
136 // Otherwise, this is an entrance into a loop from some place invalid.
137 // Either the loop structure is invalid and this is not a natural loop (in
138 // which case the compiler is buggy somewhere else) or BB is unreachable.
139 BlockUnreachable = true;
140 break;
141 }
142
143 // If this block is ok, check the next one.
144 if (!BlockUnreachable) continue;
145
146 // Otherwise, this block is dead. To clean up the CFG and to allow later
147 // loop transformations to ignore this case, we delete the edges into the
148 // loop by replacing the terminator.
149
150 // Remove PHI entries from the successors.
151 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
152 TI->getSuccessor(i)->removePredecessor(BB);
153
154 // Add a new unreachable instruction.
155 new UnreachableInst(TI);
156
157 // Delete the dead terminator.
158 if (AA) AA->deleteValue(&BB->back());
159 BB->getInstList().pop_back();
160 Changed |= true;
161 }
162
Chris Lattnercffbbee2006-02-14 22:34:08 +0000163 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000164 Changed |= ProcessLoop(*I);
Chris Lattner61992f62002-09-26 16:17:31 +0000165
166 return Changed;
167}
168
Chris Lattner61992f62002-09-26 16:17:31 +0000169/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
170/// all loops have preheaders.
171///
Chris Lattner154e4d52003-10-12 21:43:28 +0000172bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000173 bool Changed = false;
Chris Lattnerf18b3962006-08-12 05:25:00 +0000174ReprocessLoop:
175
Chris Lattner9c5693f2006-02-14 23:06:02 +0000176 // Canonicalize inner loops before outer loops. Inner loop canonicalization
177 // can provide work for the outer loop to canonicalize.
178 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
179 Changed |= ProcessLoop(*I);
180
Chris Lattnerd0788122004-03-14 03:59:22 +0000181 assert(L->getBlocks()[0] == L->getHeader() &&
182 "Header isn't first block in loop?");
Chris Lattnerd0788122004-03-14 03:59:22 +0000183
Chris Lattner85d99442006-08-12 04:51:20 +0000184 // Does the loop already have a preheader? If so, don't insert one.
Chris Lattner61992f62002-09-26 16:17:31 +0000185 if (L->getLoopPreheader() == 0) {
186 InsertPreheaderForLoop(L);
187 NumInserted++;
188 Changed = true;
189 }
190
Chris Lattner7710f2f2003-12-10 17:20:35 +0000191 // Next, check to make sure that all exit nodes of the loop only have
192 // predecessors that are inside of the loop. This check guarantees that the
193 // loop preheader/header will dominate the exit blocks. If the exit block has
Chris Lattner02f53ad2006-02-12 01:59:10 +0000194 // predecessors from outside of the loop, split the edge now.
195 std::vector<BasicBlock*> ExitBlocks;
196 L->getExitBlocks(ExitBlocks);
Chris Lattnercffbbee2006-02-14 22:34:08 +0000197
Chris Lattner02f53ad2006-02-12 01:59:10 +0000198 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000199 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
200 E = ExitBlockSet.end(); I != E; ++I) {
201 BasicBlock *ExitBlock = *I;
Chris Lattnerdaa12132004-07-15 05:36:31 +0000202 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
203 PI != PE; ++PI)
Chris Lattner05bf90d2006-02-11 02:13:17 +0000204 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
205 // allowed.
Chris Lattner02f53ad2006-02-12 01:59:10 +0000206 if (!L->contains(*PI)) {
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000207 RewriteLoopExitBlock(L, ExitBlock);
Chris Lattnerdaa12132004-07-15 05:36:31 +0000208 NumInserted++;
209 Changed = true;
210 break;
211 }
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000212 }
Chris Lattner650096a2003-02-27 20:27:08 +0000213
Chris Lattner84170522004-04-13 05:05:33 +0000214 // If the header has more than two predecessors at this point (from the
215 // preheader and from multiple backedges), we must adjust the loop.
Chris Lattnerf18b3962006-08-12 05:25:00 +0000216 unsigned NumBackedges = L->getNumBackEdges();
217 if (NumBackedges != 1) {
218 // If this is really a nested loop, rip it out into a child loop. Don't do
219 // this for loops with a giant number of backedges, just factor them into a
220 // common backedge instead.
221 if (NumBackedges < 8) {
222 if (Loop *NL = SeparateNestedLoop(L)) {
223 ++NumNested;
224 // This is a big restructuring change, reprocess the whole loop.
225 ProcessLoop(NL);
226 Changed = true;
227 // GCC doesn't tail recursion eliminate this.
228 goto ReprocessLoop;
229 }
Chris Lattner84170522004-04-13 05:05:33 +0000230 }
231
Chris Lattnerf18b3962006-08-12 05:25:00 +0000232 // If we either couldn't, or didn't want to, identify nesting of the loops,
233 // insert a new block that all backedges target, then make it jump to the
234 // loop header.
Chris Lattnerc4622a62003-10-13 00:37:13 +0000235 InsertUniqueBackedgeBlock(L);
236 NumInserted++;
237 Changed = true;
238 }
239
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000240 // Scan over the PHI nodes in the loop header. Since they now have only two
241 // incoming values (the loop is canonicalized), we may have simplified the PHI
242 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
243 PHINode *PN;
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000244 for (BasicBlock::iterator I = L->getHeader()->begin();
245 (PN = dyn_cast<PHINode>(I++)); )
Chris Lattner62df7982005-08-10 17:15:20 +0000246 if (Value *V = PN->hasConstantValue()) {
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000247 PN->replaceAllUsesWith(V);
248 PN->eraseFromParent();
249 }
250
Chris Lattner61992f62002-09-26 16:17:31 +0000251 return Changed;
252}
253
Chris Lattner650096a2003-02-27 20:27:08 +0000254/// SplitBlockPredecessors - Split the specified block into two blocks. We want
255/// to move the predecessors specified in the Preds list to point to the new
256/// block, leaving the remaining predecessors pointing to BB. This method
257/// updates the SSA PHINode's, but no other analyses.
258///
Chris Lattner154e4d52003-10-12 21:43:28 +0000259BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
260 const char *Suffix,
Chris Lattner650096a2003-02-27 20:27:08 +0000261 const std::vector<BasicBlock*> &Preds) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000262
Chris Lattner650096a2003-02-27 20:27:08 +0000263 // Create new basic block, insert right before the original block...
Chris Lattner8d414ad2004-02-04 03:58:28 +0000264 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattner650096a2003-02-27 20:27:08 +0000265
266 // The preheader first gets an unconditional branch to the loop header...
Chris Lattnera2960002003-11-21 16:52:05 +0000267 BranchInst *BI = new BranchInst(BB, NewBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000268
Chris Lattner650096a2003-02-27 20:27:08 +0000269 // For every PHI node in the block, insert a PHI node into NewBB where the
270 // incoming values from the out of loop edges are moved to NewBB. We have two
271 // possible cases here. If the loop is dead, we just insert dummy entries
272 // into the PHI nodes for the new edge. If the loop is not dead, we move the
273 // incoming edges in BB into new PHI nodes in NewBB.
274 //
275 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner031a3f82003-12-19 06:27:08 +0000276 // Check to see if the values being merged into the new block need PHI
277 // nodes. If so, insert them.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000278 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
279 PHINode *PN = cast<PHINode>(I);
Chris Lattner84170522004-04-13 05:05:33 +0000280 ++I;
281
Chris Lattner031a3f82003-12-19 06:27:08 +0000282 // Check to see if all of the values coming in are the same. If so, we
283 // don't need to create a new PHI node.
284 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
285 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
286 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
287 InVal = 0;
288 break;
289 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000290
Chris Lattner031a3f82003-12-19 06:27:08 +0000291 // If the values coming into the block are not the same, we need a PHI.
292 if (InVal == 0) {
Chris Lattner6c237bc2003-12-09 23:12:55 +0000293 // Create the new PHI node, insert it into NewBB at the end of the block
294 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
Chris Lattner514e8432005-03-25 06:37:22 +0000295 if (AA) AA->copyValue(PN, NewPHI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000296
Chris Lattner6c237bc2003-12-09 23:12:55 +0000297 // Move all of the edges from blocks outside the loop to the new PHI
298 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Chris Lattner84170522004-04-13 05:05:33 +0000299 Value *V = PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000300 NewPHI->addIncoming(V, Preds[i]);
301 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000302 InVal = NewPHI;
303 } else {
304 // Remove all of the edges coming into the PHI nodes from outside of the
305 // block.
306 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
307 PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000308 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000309
310 // Add an incoming value to the PHI node in the loop for the preheader
311 // edge.
312 PN->addIncoming(InVal, NewBB);
Chris Lattner84170522004-04-13 05:05:33 +0000313
314 // Can we eliminate this phi node now?
Chris Lattner257efb22005-08-05 00:57:45 +0000315 if (Value *V = PN->hasConstantValue(true)) {
Chris Lattnere29d6342004-10-17 21:22:38 +0000316 if (!isa<Instruction>(V) ||
Owen Andersonf7ebea12007-04-07 18:23:27 +0000317 getAnalysis<DominatorSet>().dominates(cast<Instruction>(V), PN)) {
Chris Lattnere29d6342004-10-17 21:22:38 +0000318 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000319 if (AA) AA->deleteValue(PN);
Chris Lattnere29d6342004-10-17 21:22:38 +0000320 BB->getInstList().erase(PN);
321 }
Chris Lattner84170522004-04-13 05:05:33 +0000322 }
Chris Lattner650096a2003-02-27 20:27:08 +0000323 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000324
Chris Lattner650096a2003-02-27 20:27:08 +0000325 // Now that the PHI nodes are updated, actually move the edges from
326 // Preds to point to NewBB instead of BB.
327 //
328 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
329 TerminatorInst *TI = Preds[i]->getTerminator();
330 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
331 if (TI->getSuccessor(s) == BB)
332 TI->setSuccessor(s, NewBB);
333 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000334
Chris Lattner650096a2003-02-27 20:27:08 +0000335 } else { // Otherwise the loop is dead...
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000336 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
337 PHINode *PN = cast<PHINode>(I);
Chris Lattner650096a2003-02-27 20:27:08 +0000338 // Insert dummy values as the incoming value...
339 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000340 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000341 }
Chris Lattner650096a2003-02-27 20:27:08 +0000342 return NewBB;
343}
344
Chris Lattner61992f62002-09-26 16:17:31 +0000345/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
346/// preheader, this method is called to insert one. This method has two phases:
347/// preheader insertion and analysis updating.
348///
Chris Lattner154e4d52003-10-12 21:43:28 +0000349void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000350 BasicBlock *Header = L->getHeader();
351
352 // Compute the set of predecessors of the loop that are not in the loop.
353 std::vector<BasicBlock*> OutsideBlocks;
354 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
355 PI != PE; ++PI)
Chris Lattner05bf90d2006-02-11 02:13:17 +0000356 if (!L->contains(*PI)) // Coming in from outside the loop?
357 OutsideBlocks.push_back(*PI); // Keep track of it...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000358
Chris Lattner608cd052006-09-23 07:40:52 +0000359 // Split out the loop pre-header.
Chris Lattner650096a2003-02-27 20:27:08 +0000360 BasicBlock *NewBB =
361 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner608cd052006-09-23 07:40:52 +0000362
Misha Brukmanb1c93172005-04-21 23:48:37 +0000363
Chris Lattner61992f62002-09-26 16:17:31 +0000364 //===--------------------------------------------------------------------===//
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000365 // Update analysis results now that we have performed the transformation
Chris Lattner61992f62002-09-26 16:17:31 +0000366 //
Misha Brukmanb1c93172005-04-21 23:48:37 +0000367
Chris Lattner61992f62002-09-26 16:17:31 +0000368 // We know that we have loop information to update... update it now.
369 if (Loop *Parent = L->getParentLoop())
Chris Lattnercffbbee2006-02-14 22:34:08 +0000370 Parent->addBasicBlockToLoop(NewBB, *LI);
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000371
Chris Lattner608cd052006-09-23 07:40:52 +0000372 UpdateDomInfoForRevectoredPreds(NewBB, OutsideBlocks);
Chris Lattner6bd6da42006-09-23 08:19:21 +0000373
374 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
375 // code layout too horribly.
376 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
Chris Lattner650096a2003-02-27 20:27:08 +0000377}
378
Chris Lattner84170522004-04-13 05:05:33 +0000379/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
380/// blocks. This method is used to split exit blocks that have predecessors
381/// outside of the loop.
Chris Lattner82782632004-04-18 22:27:10 +0000382BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattner650096a2003-02-27 20:27:08 +0000383 std::vector<BasicBlock*> LoopBlocks;
384 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
385 if (L->contains(*I))
386 LoopBlocks.push_back(*I);
387
Chris Lattner10b2b052003-02-27 22:31:07 +0000388 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
389 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
390
Chris Lattnercffbbee2006-02-14 22:34:08 +0000391 // Update Loop Information - we know that the new block will be in whichever
392 // loop the Exit block is in. Note that it may not be in that immediate loop,
393 // if the successor is some other loop header. In that case, we continue
394 // walking up the loop tree to find a loop that contains both the successor
395 // block and the predecessor block.
396 Loop *SuccLoop = LI->getLoopFor(Exit);
397 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
398 SuccLoop = SuccLoop->getParentLoop();
399 if (SuccLoop)
400 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner32a39c22003-02-28 03:07:54 +0000401
Chris Lattnerc4622a62003-10-13 00:37:13 +0000402 // Update dominator information (set, immdom, domtree, and domfrontier)
403 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
Chris Lattner82782632004-04-18 22:27:10 +0000404 return NewBB;
Chris Lattnerc4622a62003-10-13 00:37:13 +0000405}
406
Chris Lattner84170522004-04-13 05:05:33 +0000407/// AddBlockAndPredsToSet - Add the specified block, and all of its
408/// predecessors, to the specified set, if it's not already in there. Stop
409/// predecessor traversal when we reach StopBlock.
410static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
411 std::set<BasicBlock*> &Blocks) {
412 if (!Blocks.insert(BB).second) return; // already processed.
413 if (BB == StopBlock) return; // Stop here!
414
415 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
416 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
417}
418
Chris Lattnera6e22812004-04-13 15:21:18 +0000419/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
420/// PHI node that tells us how to partition the loops.
Devang Patel1758cb52007-03-20 20:18:12 +0000421static PHINode *FindPHIToPartitionLoops(Loop *L, ETForest *EF,
422 AliasAnalysis *AA) {
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000423 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
424 PHINode *PN = cast<PHINode>(I);
Chris Lattnera6e22812004-04-13 15:21:18 +0000425 ++I;
Nate Begemanb3923212005-08-04 23:24:19 +0000426 if (Value *V = PN->hasConstantValue())
Devang Patel1758cb52007-03-20 20:18:12 +0000427 if (!isa<Instruction>(V) || EF->dominates(cast<Instruction>(V), PN)) {
Chris Lattnere29d6342004-10-17 21:22:38 +0000428 // This is a degenerate PHI already, don't modify it!
429 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000430 if (AA) AA->deleteValue(PN);
Chris Lattnerdd3ec922005-03-06 21:35:38 +0000431 PN->eraseFromParent();
Chris Lattnere29d6342004-10-17 21:22:38 +0000432 continue;
433 }
434
435 // Scan this PHI node looking for a use of the PHI node by itself.
436 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
437 if (PN->getIncomingValue(i) == PN &&
438 L->contains(PN->getIncomingBlock(i)))
439 // We found something tasty to remove.
440 return PN;
Chris Lattnera6e22812004-04-13 15:21:18 +0000441 }
442 return 0;
443}
444
Chris Lattner6bd6da42006-09-23 08:19:21 +0000445// PlaceSplitBlockCarefully - If the block isn't already, move the new block to
446// right after some 'outside block' block. This prevents the preheader from
447// being placed inside the loop body, e.g. when the loop hasn't been rotated.
448void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
449 std::vector<BasicBlock*>&SplitPreds,
450 Loop *L) {
451 // Check to see if NewBB is already well placed.
452 Function::iterator BBI = NewBB; --BBI;
453 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
454 if (&*BBI == SplitPreds[i])
455 return;
456 }
457
458 // If it isn't already after an outside block, move it after one. This is
459 // always good as it makes the uncond branch from the outside block into a
460 // fall-through.
461
462 // Figure out *which* outside block to put this after. Prefer an outside
463 // block that neighbors a BB actually in the loop.
464 BasicBlock *FoundBB = 0;
465 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
466 Function::iterator BBI = SplitPreds[i];
467 if (++BBI != NewBB->getParent()->end() &&
468 L->contains(BBI)) {
469 FoundBB = SplitPreds[i];
470 break;
471 }
472 }
473
474 // If our heuristic for a *good* bb to place this after doesn't find
475 // anything, just pick something. It's likely better than leaving it within
476 // the loop.
477 if (!FoundBB)
478 FoundBB = SplitPreds[0];
479 NewBB->moveAfter(FoundBB);
480}
481
482
Chris Lattner84170522004-04-13 05:05:33 +0000483/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
484/// them out into a nested loop. This is important for code that looks like
485/// this:
486///
487/// Loop:
488/// ...
489/// br cond, Loop, Next
490/// ...
491/// br cond2, Loop, Out
492///
493/// To identify this common case, we look at the PHI nodes in the header of the
494/// loop. PHI nodes with unchanging values on one backedge correspond to values
495/// that change in the "outer" loop, but not in the "inner" loop.
496///
497/// If we are able to separate out a loop, return the new outer loop that was
498/// created.
499///
500Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
Devang Patel1758cb52007-03-20 20:18:12 +0000501 ETForest *EF = getAnalysisToUpdate<ETForest>();
502 PHINode *PN = FindPHIToPartitionLoops(L, EF, AA);
Chris Lattnera6e22812004-04-13 15:21:18 +0000503 if (PN == 0) return 0; // No known way to partition.
Chris Lattner84170522004-04-13 05:05:33 +0000504
Chris Lattnera6e22812004-04-13 15:21:18 +0000505 // Pull out all predecessors that have varying values in the loop. This
506 // handles the case when a PHI node has multiple instances of itself as
507 // arguments.
Chris Lattner84170522004-04-13 05:05:33 +0000508 std::vector<BasicBlock*> OuterLoopPreds;
Chris Lattnera6e22812004-04-13 15:21:18 +0000509 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
510 if (PN->getIncomingValue(i) != PN ||
511 !L->contains(PN->getIncomingBlock(i)))
512 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner84170522004-04-13 05:05:33 +0000513
Chris Lattner89e959b2004-04-13 16:23:25 +0000514 BasicBlock *Header = L->getHeader();
Chris Lattner84170522004-04-13 05:05:33 +0000515 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
516
517 // Update dominator information (set, immdom, domtree, and domfrontier)
518 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
519
Chris Lattner6bd6da42006-09-23 08:19:21 +0000520 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
521 // code layout too horribly.
522 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
523
Chris Lattner84170522004-04-13 05:05:33 +0000524 // Create the new outer loop.
525 Loop *NewOuter = new Loop();
526
Chris Lattner84170522004-04-13 05:05:33 +0000527 // Change the parent loop to use the outer loop as its child now.
528 if (Loop *Parent = L->getParentLoop())
529 Parent->replaceChildLoopWith(L, NewOuter);
530 else
Chris Lattnercffbbee2006-02-14 22:34:08 +0000531 LI->changeTopLevelLoop(L, NewOuter);
Chris Lattner84170522004-04-13 05:05:33 +0000532
533 // This block is going to be our new header block: add it to this loop and all
534 // parent loops.
Chris Lattnercffbbee2006-02-14 22:34:08 +0000535 NewOuter->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner84170522004-04-13 05:05:33 +0000536
537 // L is now a subloop of our outer loop.
538 NewOuter->addChildLoop(L);
539
Chris Lattner84170522004-04-13 05:05:33 +0000540 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
541 NewOuter->addBlockEntry(L->getBlocks()[i]);
542
543 // Determine which blocks should stay in L and which should be moved out to
544 // the Outer loop now.
Owen Andersonf7ebea12007-04-07 18:23:27 +0000545 DominatorSet &DS = getAnalysis<DominatorSet>();
Chris Lattner84170522004-04-13 05:05:33 +0000546 std::set<BasicBlock*> BlocksInL;
547 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
Owen Andersonf7ebea12007-04-07 18:23:27 +0000548 if (DS.dominates(Header, *PI))
Chris Lattner84170522004-04-13 05:05:33 +0000549 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
550
551
552 // Scan all of the loop children of L, moving them to OuterLoop if they are
553 // not part of the inner loop.
554 for (Loop::iterator I = L->begin(); I != L->end(); )
555 if (BlocksInL.count((*I)->getHeader()))
556 ++I; // Loop remains in L
557 else
558 NewOuter->addChildLoop(L->removeChildLoop(I));
559
560 // Now that we know which blocks are in L and which need to be moved to
561 // OuterLoop, move any blocks that need it.
562 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
563 BasicBlock *BB = L->getBlocks()[i];
564 if (!BlocksInL.count(BB)) {
565 // Move this block to the parent, updating the exit blocks sets
566 L->removeBlockFromLoop(BB);
Chris Lattnercffbbee2006-02-14 22:34:08 +0000567 if ((*LI)[BB] == L)
568 LI->changeLoopFor(BB, NewOuter);
Chris Lattner84170522004-04-13 05:05:33 +0000569 --i;
570 }
571 }
572
Chris Lattner84170522004-04-13 05:05:33 +0000573 return NewOuter;
574}
575
576
577
Chris Lattnerc4622a62003-10-13 00:37:13 +0000578/// InsertUniqueBackedgeBlock - This method is called when the specified loop
579/// has more than one backedge in it. If this occurs, revector all of these
580/// backedges to target a new basic block and have that block branch to the loop
581/// header. This ensures that loops have exactly one backedge.
582///
583void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
584 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
585
586 // Get information about the loop
587 BasicBlock *Preheader = L->getLoopPreheader();
588 BasicBlock *Header = L->getHeader();
589 Function *F = Header->getParent();
590
591 // Figure out which basic blocks contain back-edges to the loop header.
592 std::vector<BasicBlock*> BackedgeBlocks;
593 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
594 if (*I != Preheader) BackedgeBlocks.push_back(*I);
595
596 // Create and insert the new backedge block...
597 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattnera2960002003-11-21 16:52:05 +0000598 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000599
600 // Move the new backedge block to right after the last backedge block.
601 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
602 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000603
Chris Lattnerc4622a62003-10-13 00:37:13 +0000604 // Now that the block has been inserted into the function, create PHI nodes in
605 // the backedge block which correspond to any PHI nodes in the header block.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000606 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
607 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000608 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
609 BETerminator);
Chris Lattnerd8e20182005-01-29 00:39:08 +0000610 NewPN->reserveOperandSpace(BackedgeBlocks.size());
Chris Lattner514e8432005-03-25 06:37:22 +0000611 if (AA) AA->copyValue(PN, NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000612
613 // Loop over the PHI node, moving all entries except the one for the
614 // preheader over to the new PHI node.
615 unsigned PreheaderIdx = ~0U;
616 bool HasUniqueIncomingValue = true;
617 Value *UniqueValue = 0;
618 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
619 BasicBlock *IBB = PN->getIncomingBlock(i);
620 Value *IV = PN->getIncomingValue(i);
621 if (IBB == Preheader) {
622 PreheaderIdx = i;
623 } else {
624 NewPN->addIncoming(IV, IBB);
625 if (HasUniqueIncomingValue) {
626 if (UniqueValue == 0)
627 UniqueValue = IV;
628 else if (UniqueValue != IV)
629 HasUniqueIncomingValue = false;
630 }
631 }
632 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000633
Chris Lattnerc4622a62003-10-13 00:37:13 +0000634 // Delete all of the incoming values from the old PN except the preheader's
635 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
636 if (PreheaderIdx != 0) {
637 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
638 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
639 }
Chris Lattnerd8e20182005-01-29 00:39:08 +0000640 // Nuke all entries except the zero'th.
641 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
642 PN->removeIncomingValue(e-i, false);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000643
644 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
645 PN->addIncoming(NewPN, BEBlock);
646
647 // As an optimization, if all incoming values in the new PhiNode (which is a
648 // subset of the incoming values of the old PHI node) have the same value,
649 // eliminate the PHI Node.
650 if (HasUniqueIncomingValue) {
651 NewPN->replaceAllUsesWith(UniqueValue);
Chris Lattner514e8432005-03-25 06:37:22 +0000652 if (AA) AA->deleteValue(NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000653 BEBlock->getInstList().erase(NewPN);
654 }
655 }
656
657 // Now that all of the PHI nodes have been inserted and adjusted, modify the
658 // backedge blocks to just to the BEBlock instead of the header.
659 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
660 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
661 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
662 if (TI->getSuccessor(Op) == Header)
663 TI->setSuccessor(Op, BEBlock);
664 }
665
666 //===--- Update all analyses which we must preserve now -----------------===//
667
668 // Update Loop Information - we know that this block is now in the current
669 // loop and all parent loops.
Chris Lattnercffbbee2006-02-14 22:34:08 +0000670 L->addBasicBlockToLoop(BEBlock, *LI);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000671
Chris Lattnerc4622a62003-10-13 00:37:13 +0000672 // Update dominator information (set, immdom, domtree, and domfrontier)
673 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
674}
675
676/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
677/// different kinds of dominator information (dominator sets, immediate
678/// dominators, dominator trees, and dominance frontiers) after a new block has
679/// been added to the CFG.
680///
Chris Lattner14ab84a2004-02-05 21:12:24 +0000681/// This only supports the case when an existing block (known as "NewBBSucc"),
682/// had some of its predecessors factored into a new basic block. This
Chris Lattnerc4622a62003-10-13 00:37:13 +0000683/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner14ab84a2004-02-05 21:12:24 +0000684/// unconditional branch to NewBBSucc, and moves some predecessors of
685/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
686/// PredBlocks, even though they are the same as
687/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattnerc4622a62003-10-13 00:37:13 +0000688///
689void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
690 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000691 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattnerc4622a62003-10-13 00:37:13 +0000692 assert(succ_begin(NewBB) != succ_end(NewBB) &&
693 ++succ_begin(NewBB) == succ_end(NewBB) &&
694 "NewBB should have a single successor!");
Chris Lattner14ab84a2004-02-05 21:12:24 +0000695 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Owen Andersonf7ebea12007-04-07 18:23:27 +0000696 DominatorSet &DS = getAnalysis<DominatorSet>();
697
698 // Update dominator information... The blocks that dominate NewBB are the
699 // intersection of the dominators of predecessors, plus the block itself.
700 //
701 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
702 {
703 unsigned i, e = PredBlocks.size();
704 // It is possible for some preds to not be reachable, and thus have empty
705 // dominator sets (all blocks must dom themselves, so no domset would
706 // otherwise be empty). If we see any of these, don't intersect with them,
707 // as that would certainly leave the resultant set empty.
708 for (i = 1; NewBBDomSet.empty(); ++i) {
709 assert(i != e && "Didn't find reachable pred?");
710 NewBBDomSet = DS.getDominators(PredBlocks[i]);
711 }
712
713 // Intersect the rest of the non-empty sets.
714 for (; i != e; ++i) {
715 const DominatorSet::DomSetType &PredDS = DS.getDominators(PredBlocks[i]);
716 if (!PredDS.empty())
717 set_intersect(NewBBDomSet, PredDS);
718 }
719 NewBBDomSet.insert(NewBB); // All blocks dominate themselves.
720 DS.addBasicBlock(NewBB, NewBBDomSet);
721 }
722
Chris Lattner14ab84a2004-02-05 21:12:24 +0000723 // The newly inserted basic block will dominate existing basic blocks iff the
724 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
725 // the non-pred blocks, then they all must be the same block!
Chris Lattner146d0df2004-04-01 19:06:07 +0000726 //
Chris Lattner14ab84a2004-02-05 21:12:24 +0000727 bool NewBBDominatesNewBBSucc = true;
728 {
729 BasicBlock *OnePred = PredBlocks[0];
Chris Lattner608cd052006-09-23 07:40:52 +0000730 unsigned i, e = PredBlocks.size();
Owen Andersonf7ebea12007-04-07 18:23:27 +0000731 for (i = 1; !DS.isReachable(OnePred); ++i) {
Chris Lattner608cd052006-09-23 07:40:52 +0000732 assert(i != e && "Didn't find reachable pred?");
733 OnePred = PredBlocks[i];
734 }
735
736 for (; i != e; ++i)
Owen Andersonf7ebea12007-04-07 18:23:27 +0000737 if (PredBlocks[i] != OnePred && DS.isReachable(PredBlocks[i])) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000738 NewBBDominatesNewBBSucc = false;
739 break;
740 }
741
742 if (NewBBDominatesNewBBSucc)
743 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
744 PI != E; ++PI)
Owen Andersonf7ebea12007-04-07 18:23:27 +0000745 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000746 NewBBDominatesNewBBSucc = false;
747 break;
748 }
749 }
750
Chris Lattner146d0df2004-04-01 19:06:07 +0000751 // The other scenario where the new block can dominate its successors are when
752 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
753 // already.
754 if (!NewBBDominatesNewBBSucc) {
755 NewBBDominatesNewBBSucc = true;
756 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
757 PI != E; ++PI)
Owen Andersonf7ebea12007-04-07 18:23:27 +0000758 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
Chris Lattner146d0df2004-04-01 19:06:07 +0000759 NewBBDominatesNewBBSucc = false;
760 break;
761 }
762 }
Chris Lattner650096a2003-02-27 20:27:08 +0000763
Owen Andersonf7ebea12007-04-07 18:23:27 +0000764 // If NewBB dominates some blocks, then it will dominate all blocks that
765 // NewBBSucc does.
766 if (NewBBDominatesNewBBSucc) {
767 Function *F = NewBB->getParent();
768 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
769 if (DS.dominates(NewBBSucc, I))
770 DS.addDominator(I, NewBB);
771 }
772
Owen Anderson706e9702007-04-07 06:56:47 +0000773 // Update immediate dominator information if we have it.
Owen Andersonf7ebea12007-04-07 18:23:27 +0000774 BasicBlock *NewBBIDom = 0;
Chris Lattner650096a2003-02-27 20:27:08 +0000775 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
Owen Andersonf7ebea12007-04-07 18:23:27 +0000776 // To find the immediate dominator of the new exit node, we trace up the
777 // immediate dominators of a predecessor until we find a basic block that
778 // dominates the exit block.
779 //
780 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor.
781
782 // Find a reachable pred.
783 for (unsigned i = 1; !DS.isReachable(Dom); ++i) {
784 assert(i != PredBlocks.size() && "Didn't find reachable pred!");
785 Dom = PredBlocks[i];
Chris Lattner608cd052006-09-23 07:40:52 +0000786 }
Owen Andersonf7ebea12007-04-07 18:23:27 +0000787
788 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator.
789 assert(Dom != 0 && "No shared dominator found???");
790 Dom = ID->get(Dom);
791 }
792
Chris Lattner650096a2003-02-27 20:27:08 +0000793 // Set the immediate dominator now...
Owen Andersonf7ebea12007-04-07 18:23:27 +0000794 ID->addNewBlock(NewBB, Dom);
795 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
Chris Lattner14ab84a2004-02-05 21:12:24 +0000796
797 // If NewBB strictly dominates other blocks, we need to update their idom's
798 // now. The only block that need adjustment is the NewBBSucc block, whose
799 // idom should currently be set to PredBlocks[0].
Chris Lattner59fdf742004-04-01 19:21:46 +0000800 if (NewBBDominatesNewBBSucc)
Chris Lattner14ab84a2004-02-05 21:12:24 +0000801 ID->setImmediateDominator(NewBBSucc, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000802 }
803
804 // Update DominatorTree information if it is active.
805 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000806 // If we don't have ImmediateDominator info around, calculate the idom as
807 // above.
Owen Andersonf7ebea12007-04-07 18:23:27 +0000808 DominatorTree::Node *NewBBIDomNode;
809 if (NewBBIDom) {
810 NewBBIDomNode = DT->getNode(NewBBIDom);
811 } else {
812 // Scan all the pred blocks that were pulled out. Any individual one may
813 // actually be unreachable, which would mean it doesn't have dom info.
814 NewBBIDomNode = 0;
815 for (unsigned i = 0; !NewBBIDomNode; ++i) {
816 assert(i != PredBlocks.size() && "No reachable preds?");
817 NewBBIDomNode = DT->getNode(PredBlocks[i]);
Chris Lattner608cd052006-09-23 07:40:52 +0000818 }
Owen Andersonf7ebea12007-04-07 18:23:27 +0000819
820 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
821 NewBBIDomNode = NewBBIDomNode->getIDom();
822 assert(NewBBIDomNode && "No shared dominator found??");
823 }
824 NewBBIDom = NewBBIDomNode->getBlock();
Chris Lattner650096a2003-02-27 20:27:08 +0000825 }
826
Chris Lattner14ab84a2004-02-05 21:12:24 +0000827 // Create the new dominator tree node... and set the idom of NewBB.
828 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
829
830 // If NewBB strictly dominates other blocks, then it is now the immediate
831 // dominator of NewBBSucc. Update the dominator tree as appropriate.
832 if (NewBBDominatesNewBBSucc) {
833 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
Chris Lattner14ab84a2004-02-05 21:12:24 +0000834 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
835 }
Chris Lattner650096a2003-02-27 20:27:08 +0000836 }
837
Chris Lattnercda4aa62006-01-09 08:03:08 +0000838 // Update ET-Forest information if it is active.
839 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
840 EF->addNewBlock(NewBB, NewBBIDom);
841 if (NewBBDominatesNewBBSucc)
842 EF->setImmediateDominator(NewBBSucc, NewBB);
843 }
844
Chris Lattner650096a2003-02-27 20:27:08 +0000845 // Update dominance frontier information...
846 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
Chris Lattner89e959b2004-04-13 16:23:25 +0000847 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
848 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
849 // a predecessor of.
Chris Lattner14ab84a2004-02-05 21:12:24 +0000850 if (NewBBDominatesNewBBSucc) {
851 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
852 if (DFI != DF->end()) {
853 DominanceFrontier::DomSetType Set = DFI->second;
854 // Filter out stuff in Set that we do not dominate a predecessor of.
855 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
856 E = Set.end(); SetI != E;) {
857 bool DominatesPred = false;
858 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
859 PI != E; ++PI)
Owen Andersonf7ebea12007-04-07 18:23:27 +0000860 if (DS.dominates(NewBB, *PI))
Chris Lattner14ab84a2004-02-05 21:12:24 +0000861 DominatesPred = true;
862 if (!DominatesPred)
863 Set.erase(SetI++);
864 else
865 ++SetI;
866 }
Chris Lattner650096a2003-02-27 20:27:08 +0000867
Chris Lattner14ab84a2004-02-05 21:12:24 +0000868 DF->addBasicBlock(NewBB, Set);
869 }
870
871 } else {
872 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
873 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
874 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
875 DominanceFrontier::DomSetType NewDFSet;
876 NewDFSet.insert(NewBBSucc);
877 DF->addBasicBlock(NewBB, NewDFSet);
Chris Lattner89e959b2004-04-13 16:23:25 +0000878 }
Chris Lattnerc4622a62003-10-13 00:37:13 +0000879
Chris Lattner89e959b2004-04-13 16:23:25 +0000880 // Now we must loop over all of the dominance frontiers in the function,
881 // replacing occurrences of NewBBSucc with NewBB in some cases. All
882 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
883 // their dominance frontier must be updated to contain NewBB instead.
884 //
885 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
886 BasicBlock *Pred = PredBlocks[i];
887 // Get all of the dominators of the predecessor...
Owen Andersonf7ebea12007-04-07 18:23:27 +0000888 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
889 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
Chris Lattner89e959b2004-04-13 16:23:25 +0000890 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
891 BasicBlock *PredDom = *PDI;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000892
Chris Lattner89e959b2004-04-13 16:23:25 +0000893 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
894 // dominate NewBBSucc but did dominate a predecessor of it. Now we
895 // change this entry to include NewBB in the DF instead of NewBBSucc.
896 DominanceFrontier::iterator DFI = DF->find(PredDom);
897 assert(DFI != DF->end() && "No dominance frontier for node?");
898 if (DFI->second.count(NewBBSucc)) {
899 // If NewBBSucc should not stay in our dominator frontier, remove it.
900 // We remove it unless there is a predecessor of NewBBSucc that we
901 // dominate, but we don't strictly dominate NewBBSucc.
902 bool ShouldRemove = true;
Owen Andersonf7ebea12007-04-07 18:23:27 +0000903 if (PredDom == NewBBSucc || !DS.dominates(PredDom, NewBBSucc)) {
Chris Lattner89e959b2004-04-13 16:23:25 +0000904 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
905 // Check to see if it dominates any predecessors of NewBBSucc.
906 for (pred_iterator PI = pred_begin(NewBBSucc),
907 E = pred_end(NewBBSucc); PI != E; ++PI)
Owen Andersonf7ebea12007-04-07 18:23:27 +0000908 if (DS.dominates(PredDom, *PI)) {
Chris Lattner89e959b2004-04-13 16:23:25 +0000909 ShouldRemove = false;
910 break;
911 }
Chris Lattner650096a2003-02-27 20:27:08 +0000912 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000913
Chris Lattner89e959b2004-04-13 16:23:25 +0000914 if (ShouldRemove)
915 DF->removeFromFrontier(DFI, NewBBSucc);
916 DF->addToFrontier(DFI, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000917 }
918 }
919 }
Chris Lattner650096a2003-02-27 20:27:08 +0000920 }
Chris Lattner61992f62002-09-26 16:17:31 +0000921}
Brian Gaeke960707c2003-11-11 22:41:34 +0000922