blob: 64b0a7cc708dcce5d0e68e47084e9168c4eaf969 [file] [log] [blame]
Chris Lattner55d47882003-10-12 21:44:18 +00001//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner61992f62002-09-26 16:17:31 +00009//
Chris Lattner154e4d52003-10-12 21:43:28 +000010// This pass performs several transformations to transform natural loops into a
11// simpler form, which makes subsequent analyses and transformations simpler and
12// more effective.
Chris Lattner650096a2003-02-27 20:27:08 +000013//
14// Loop pre-header insertion guarantees that there is a single, non-critical
15// entry edge from outside of the loop to the loop header. This simplifies a
16// number of analyses and transformations, such as LICM.
17//
18// Loop exit-block insertion guarantees that all exit blocks from the loop
19// (blocks which are outside of the loop that have predecessors inside of the
Chris Lattner7710f2f2003-12-10 17:20:35 +000020// loop) only have predecessors from inside of the loop (and are thus dominated
21// by the loop header). This simplifies transformations such as store-sinking
22// that are built into LICM.
Chris Lattner650096a2003-02-27 20:27:08 +000023//
Chris Lattnerc4622a62003-10-13 00:37:13 +000024// This pass also guarantees that loops will have exactly one backedge.
25//
Chris Lattner650096a2003-02-27 20:27:08 +000026// Note that the simplifycfg pass will clean up blocks which are split out but
Chris Lattner154e4d52003-10-12 21:43:28 +000027// end up being unnecessary, so usage of this pass should not pessimize
28// generated code.
29//
30// This pass obviously modifies the CFG, but updates loop information and
31// dominator information.
Chris Lattner61992f62002-09-26 16:17:31 +000032//
33//===----------------------------------------------------------------------===//
34
35#include "llvm/Transforms/Scalar.h"
36#include "llvm/Analysis/Dominators.h"
37#include "llvm/Analysis/LoopInfo.h"
38#include "llvm/Function.h"
39#include "llvm/iTerminators.h"
40#include "llvm/iPHINode.h"
41#include "llvm/Constant.h"
42#include "llvm/Support/CFG.h"
Chris Lattner650096a2003-02-27 20:27:08 +000043#include "Support/SetOperations.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000044#include "Support/Statistic.h"
Chris Lattner32a39c22003-02-28 03:07:54 +000045#include "Support/DepthFirstIterator.h"
Chris Lattner7710f2f2003-12-10 17:20:35 +000046using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000047
Chris Lattner61992f62002-09-26 16:17:31 +000048namespace {
Chris Lattner154e4d52003-10-12 21:43:28 +000049 Statistic<>
Chris Lattner7710f2f2003-12-10 17:20:35 +000050 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
Chris Lattner61992f62002-09-26 16:17:31 +000051
Chris Lattner154e4d52003-10-12 21:43:28 +000052 struct LoopSimplify : public FunctionPass {
Chris Lattner61992f62002-09-26 16:17:31 +000053 virtual bool runOnFunction(Function &F);
54
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 // We need loop information to identify the loops...
57 AU.addRequired<LoopInfo>();
Chris Lattner650096a2003-02-27 20:27:08 +000058 AU.addRequired<DominatorSet>();
Chris Lattner61992f62002-09-26 16:17:31 +000059
60 AU.addPreserved<LoopInfo>();
61 AU.addPreserved<DominatorSet>();
62 AU.addPreserved<ImmediateDominators>();
63 AU.addPreserved<DominatorTree>();
Chris Lattner650096a2003-02-27 20:27:08 +000064 AU.addPreserved<DominanceFrontier>();
Chris Lattner61992f62002-09-26 16:17:31 +000065 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
66 }
67 private:
68 bool ProcessLoop(Loop *L);
Chris Lattner650096a2003-02-27 20:27:08 +000069 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
70 const std::vector<BasicBlock*> &Preds);
71 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner61992f62002-09-26 16:17:31 +000072 void InsertPreheaderForLoop(Loop *L);
Chris Lattnerc4622a62003-10-13 00:37:13 +000073 void InsertUniqueBackedgeBlock(Loop *L);
74
75 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
76 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner61992f62002-09-26 16:17:31 +000077 };
78
Chris Lattner154e4d52003-10-12 21:43:28 +000079 RegisterOpt<LoopSimplify>
80 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner61992f62002-09-26 16:17:31 +000081}
82
83// Publically exposed interface to pass...
Chris Lattner7710f2f2003-12-10 17:20:35 +000084const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
85Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner61992f62002-09-26 16:17:31 +000086
Chris Lattner61992f62002-09-26 16:17:31 +000087/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
88/// it in any convenient order) inserting preheaders...
89///
Chris Lattner154e4d52003-10-12 21:43:28 +000090bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner61992f62002-09-26 16:17:31 +000091 bool Changed = false;
92 LoopInfo &LI = getAnalysis<LoopInfo>();
93
94 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i)
95 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]);
96
97 return Changed;
98}
99
100
101/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
102/// all loops have preheaders.
103///
Chris Lattner154e4d52003-10-12 21:43:28 +0000104bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000105 bool Changed = false;
106
107 // Does the loop already have a preheader? If so, don't modify the loop...
108 if (L->getLoopPreheader() == 0) {
109 InsertPreheaderForLoop(L);
110 NumInserted++;
111 Changed = true;
112 }
113
Chris Lattner7710f2f2003-12-10 17:20:35 +0000114 // Next, check to make sure that all exit nodes of the loop only have
115 // predecessors that are inside of the loop. This check guarantees that the
116 // loop preheader/header will dominate the exit blocks. If the exit block has
117 // predecessors from outside of the loop, split the edge now.
118 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i) {
119 BasicBlock *ExitBlock = L->getExitBlocks()[i];
120 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
121 PI != PE; ++PI)
122 if (!L->contains(*PI)) {
123 RewriteLoopExitBlock(L, ExitBlock);
124 NumInserted++;
125 Changed = true;
126 break;
127 }
Chris Lattner650096a2003-02-27 20:27:08 +0000128 }
129
Chris Lattnerc4622a62003-10-13 00:37:13 +0000130 // The preheader may have more than two predecessors at this point (from the
131 // preheader and from the backedges). To simplify the loop more, insert an
132 // extra back-edge block in the loop so that there is exactly one backedge.
133 if (L->getNumBackEdges() != 1) {
134 InsertUniqueBackedgeBlock(L);
135 NumInserted++;
136 Changed = true;
137 }
138
Chris Lattner61992f62002-09-26 16:17:31 +0000139 const std::vector<Loop*> &SubLoops = L->getSubLoops();
140 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
141 Changed |= ProcessLoop(SubLoops[i]);
142 return Changed;
143}
144
Chris Lattner650096a2003-02-27 20:27:08 +0000145/// SplitBlockPredecessors - Split the specified block into two blocks. We want
146/// to move the predecessors specified in the Preds list to point to the new
147/// block, leaving the remaining predecessors pointing to BB. This method
148/// updates the SSA PHINode's, but no other analyses.
149///
Chris Lattner154e4d52003-10-12 21:43:28 +0000150BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
151 const char *Suffix,
Chris Lattner650096a2003-02-27 20:27:08 +0000152 const std::vector<BasicBlock*> &Preds) {
153
154 // Create new basic block, insert right before the original block...
155 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB);
156
157 // The preheader first gets an unconditional branch to the loop header...
Chris Lattnera2960002003-11-21 16:52:05 +0000158 BranchInst *BI = new BranchInst(BB, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000159
160 // For every PHI node in the block, insert a PHI node into NewBB where the
161 // incoming values from the out of loop edges are moved to NewBB. We have two
162 // possible cases here. If the loop is dead, we just insert dummy entries
163 // into the PHI nodes for the new edge. If the loop is not dead, we move the
164 // incoming edges in BB into new PHI nodes in NewBB.
165 //
166 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner6c237bc2003-12-09 23:12:55 +0000167 if (Preds.size() == 1) {
168 // No need to insert one operand PHI nodes! Instead, just update the
169 // incoming block ID's.
170 for (BasicBlock::iterator I = BB->begin();
171 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
172 unsigned i = PN->getBasicBlockIndex(Preds[0]);
173 PN->setIncomingBlock(i, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000174 }
Chris Lattner6c237bc2003-12-09 23:12:55 +0000175 } else {
176 for (BasicBlock::iterator I = BB->begin();
177 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
178
179 // Create the new PHI node, insert it into NewBB at the end of the block
180 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
181
182 // Move all of the edges from blocks outside the loop to the new PHI
183 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
184 Value *V = PN->removeIncomingValue(Preds[i]);
185 NewPHI->addIncoming(V, Preds[i]);
186 }
187
188 // Add an incoming value to the PHI node in the loop for the preheader
189 // edge.
190 PN->addIncoming(NewPHI, NewBB);
191 }
Chris Lattner650096a2003-02-27 20:27:08 +0000192 }
193
194 // Now that the PHI nodes are updated, actually move the edges from
195 // Preds to point to NewBB instead of BB.
196 //
197 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
198 TerminatorInst *TI = Preds[i]->getTerminator();
199 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
200 if (TI->getSuccessor(s) == BB)
201 TI->setSuccessor(s, NewBB);
202 }
203
204 } else { // Otherwise the loop is dead...
205 for (BasicBlock::iterator I = BB->begin();
Chris Lattner889f6202003-04-23 16:37:45 +0000206 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattner650096a2003-02-27 20:27:08 +0000207 // Insert dummy values as the incoming value...
208 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
209 }
210 return NewBB;
211}
212
Chris Lattner08950252003-05-12 22:04:34 +0000213// ChangeExitBlock - This recursive function is used to change any exit blocks
214// that use OldExit to use NewExit instead. This is recursive because children
215// may need to be processed as well.
216//
217static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) {
218 if (L->hasExitBlock(OldExit)) {
219 L->changeExitBlock(OldExit, NewExit);
220 const std::vector<Loop*> &SubLoops = L->getSubLoops();
221 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
222 ChangeExitBlock(SubLoops[i], OldExit, NewExit);
223 }
224}
225
Chris Lattner61992f62002-09-26 16:17:31 +0000226
227/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
228/// preheader, this method is called to insert one. This method has two phases:
229/// preheader insertion and analysis updating.
230///
Chris Lattner154e4d52003-10-12 21:43:28 +0000231void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000232 BasicBlock *Header = L->getHeader();
233
234 // Compute the set of predecessors of the loop that are not in the loop.
235 std::vector<BasicBlock*> OutsideBlocks;
236 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
237 PI != PE; ++PI)
238 if (!L->contains(*PI)) // Coming in from outside the loop?
239 OutsideBlocks.push_back(*PI); // Keep track of it...
240
Chris Lattner650096a2003-02-27 20:27:08 +0000241 // Split out the loop pre-header
242 BasicBlock *NewBB =
243 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner61992f62002-09-26 16:17:31 +0000244
Chris Lattner61992f62002-09-26 16:17:31 +0000245 //===--------------------------------------------------------------------===//
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000246 // Update analysis results now that we have performed the transformation
Chris Lattner61992f62002-09-26 16:17:31 +0000247 //
248
249 // We know that we have loop information to update... update it now.
250 if (Loop *Parent = L->getParentLoop())
251 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000252
253 // If the header for the loop used to be an exit node for another loop, then
254 // we need to update this to know that the loop-preheader is now the exit
255 // node. Note that the only loop that could have our header as an exit node
Chris Lattner08950252003-05-12 22:04:34 +0000256 // is a sibling loop, ie, one with the same parent loop, or one if it's
257 // children.
258 //
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000259 const std::vector<Loop*> *ParentSubLoops;
260 if (Loop *Parent = L->getParentLoop())
261 ParentSubLoops = &Parent->getSubLoops();
262 else // Must check top-level loops...
263 ParentSubLoops = &getAnalysis<LoopInfo>().getTopLevelLoops();
264
Chris Lattner08950252003-05-12 22:04:34 +0000265 // Loop over all sibling loops, performing the substitution (recursively to
266 // include child loops)...
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000267 for (unsigned i = 0, e = ParentSubLoops->size(); i != e; ++i)
Chris Lattner08950252003-05-12 22:04:34 +0000268 ChangeExitBlock((*ParentSubLoops)[i], Header, NewBB);
Chris Lattner61992f62002-09-26 16:17:31 +0000269
Chris Lattner650096a2003-02-27 20:27:08 +0000270 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
271 {
Chris Lattner61992f62002-09-26 16:17:31 +0000272 // The blocks that dominate NewBB are the blocks that dominate Header,
273 // minus Header, plus NewBB.
Chris Lattner650096a2003-02-27 20:27:08 +0000274 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner03a9e152002-09-29 21:41:38 +0000275 DomSet.insert(NewBB); // We dominate ourself
Chris Lattner61992f62002-09-26 16:17:31 +0000276 DomSet.erase(Header); // Header does not dominate us...
Chris Lattner650096a2003-02-27 20:27:08 +0000277 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner03a9e152002-09-29 21:41:38 +0000278
279 // The newly created basic block dominates all nodes dominated by Header.
280 for (Function::iterator I = Header->getParent()->begin(),
281 E = Header->getParent()->end(); I != E; ++I)
Chris Lattner650096a2003-02-27 20:27:08 +0000282 if (DS.dominates(Header, I))
283 DS.addDominator(I, NewBB);
Chris Lattner61992f62002-09-26 16:17:31 +0000284 }
285
286 // Update immediate dominator information if we have it...
287 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
288 // Whatever i-dominated the header node now immediately dominates NewBB
289 ID->addNewBlock(NewBB, ID->get(Header));
290
291 // The preheader now is the immediate dominator for the header node...
292 ID->setImmediateDominator(Header, NewBB);
293 }
294
295 // Update DominatorTree information if it is active.
296 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
297 // The immediate dominator of the preheader is the immediate dominator of
298 // the old header.
299 //
300 DominatorTree::Node *HeaderNode = DT->getNode(Header);
Chris Lattner03a9e152002-09-29 21:41:38 +0000301 DominatorTree::Node *PHNode = DT->createNewNode(NewBB,
302 HeaderNode->getIDom());
Chris Lattner61992f62002-09-26 16:17:31 +0000303
304 // Change the header node so that PNHode is the new immediate dominator
305 DT->changeImmediateDominator(HeaderNode, PHNode);
306 }
Chris Lattner650096a2003-02-27 20:27:08 +0000307
308 // Update dominance frontier information...
309 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
310 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
311 // everything that Header does, and it strictly dominates Header in
312 // addition.
313 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
314 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
315 NewDFSet.erase(Header);
316 DF->addBasicBlock(NewBB, NewDFSet);
317
318 // Now we must loop over all of the dominance frontiers in the function,
Misha Brukman4ace48e2003-09-09 21:54:45 +0000319 // replacing occurrences of Header with NewBB in some cases. If a block
Chris Lattner650096a2003-02-27 20:27:08 +0000320 // dominates a (now) predecessor of NewBB, but did not strictly dominate
321 // Header, it will have Header in it's DF set, but should now have NewBB in
322 // its set.
323 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
324 // Get all of the dominators of the predecessor...
325 const DominatorSet::DomSetType &PredDoms =
326 DS.getDominators(OutsideBlocks[i]);
327 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
328 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
329 BasicBlock *PredDom = *PDI;
330 // If the loop header is in DF(PredDom), then PredDom didn't dominate
331 // the header but did dominate a predecessor outside of the loop. Now
332 // we change this entry to include the preheader in the DF instead of
333 // the header.
334 DominanceFrontier::iterator DFI = DF->find(PredDom);
335 assert(DFI != DF->end() && "No dominance frontier for node?");
336 if (DFI->second.count(Header)) {
337 DF->removeFromFrontier(DFI, Header);
338 DF->addToFrontier(DFI, NewBB);
339 }
340 }
341 }
342 }
343}
344
Chris Lattner154e4d52003-10-12 21:43:28 +0000345void LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattner650096a2003-02-27 20:27:08 +0000346 DominatorSet &DS = getAnalysis<DominatorSet>();
Chris Lattner10b2b052003-02-27 22:31:07 +0000347 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
348 != L->getExitBlocks().end() && "Not a current exit block!");
Chris Lattner650096a2003-02-27 20:27:08 +0000349
350 std::vector<BasicBlock*> LoopBlocks;
351 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
352 if (L->contains(*I))
353 LoopBlocks.push_back(*I);
354
Chris Lattner10b2b052003-02-27 22:31:07 +0000355 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
356 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
357
Chris Lattner4e2fbfb2003-02-27 21:50:19 +0000358 // Update Loop Information - we know that the new block will be in the parent
359 // loop of L.
360 if (Loop *Parent = L->getParentLoop())
361 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner32a39c22003-02-28 03:07:54 +0000362
363 // Replace any instances of Exit with NewBB in this and any nested loops...
364 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
Chris Lattner49eb0e32003-02-28 16:54:17 +0000365 if (I->hasExitBlock(Exit))
366 I->changeExitBlock(Exit, NewBB); // Update exit block information
Chris Lattner4e2fbfb2003-02-27 21:50:19 +0000367
Chris Lattnerc4622a62003-10-13 00:37:13 +0000368 // Update dominator information (set, immdom, domtree, and domfrontier)
369 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
370}
371
372/// InsertUniqueBackedgeBlock - This method is called when the specified loop
373/// has more than one backedge in it. If this occurs, revector all of these
374/// backedges to target a new basic block and have that block branch to the loop
375/// header. This ensures that loops have exactly one backedge.
376///
377void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
378 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
379
380 // Get information about the loop
381 BasicBlock *Preheader = L->getLoopPreheader();
382 BasicBlock *Header = L->getHeader();
383 Function *F = Header->getParent();
384
385 // Figure out which basic blocks contain back-edges to the loop header.
386 std::vector<BasicBlock*> BackedgeBlocks;
387 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
388 if (*I != Preheader) BackedgeBlocks.push_back(*I);
389
390 // Create and insert the new backedge block...
391 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattnera2960002003-11-21 16:52:05 +0000392 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000393
394 // Move the new backedge block to right after the last backedge block.
395 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
396 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
397
398 // Now that the block has been inserted into the function, create PHI nodes in
399 // the backedge block which correspond to any PHI nodes in the header block.
400 for (BasicBlock::iterator I = Header->begin();
401 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
402 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
403 BETerminator);
404 NewPN->op_reserve(2*BackedgeBlocks.size());
405
406 // Loop over the PHI node, moving all entries except the one for the
407 // preheader over to the new PHI node.
408 unsigned PreheaderIdx = ~0U;
409 bool HasUniqueIncomingValue = true;
410 Value *UniqueValue = 0;
411 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
412 BasicBlock *IBB = PN->getIncomingBlock(i);
413 Value *IV = PN->getIncomingValue(i);
414 if (IBB == Preheader) {
415 PreheaderIdx = i;
416 } else {
417 NewPN->addIncoming(IV, IBB);
418 if (HasUniqueIncomingValue) {
419 if (UniqueValue == 0)
420 UniqueValue = IV;
421 else if (UniqueValue != IV)
422 HasUniqueIncomingValue = false;
423 }
424 }
425 }
426
427 // Delete all of the incoming values from the old PN except the preheader's
428 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
429 if (PreheaderIdx != 0) {
430 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
431 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
432 }
433 PN->op_erase(PN->op_begin()+2, PN->op_end());
434
435 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
436 PN->addIncoming(NewPN, BEBlock);
437
438 // As an optimization, if all incoming values in the new PhiNode (which is a
439 // subset of the incoming values of the old PHI node) have the same value,
440 // eliminate the PHI Node.
441 if (HasUniqueIncomingValue) {
442 NewPN->replaceAllUsesWith(UniqueValue);
443 BEBlock->getInstList().erase(NewPN);
444 }
445 }
446
447 // Now that all of the PHI nodes have been inserted and adjusted, modify the
448 // backedge blocks to just to the BEBlock instead of the header.
449 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
450 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
451 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
452 if (TI->getSuccessor(Op) == Header)
453 TI->setSuccessor(Op, BEBlock);
454 }
455
456 //===--- Update all analyses which we must preserve now -----------------===//
457
458 // Update Loop Information - we know that this block is now in the current
459 // loop and all parent loops.
460 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
461
462 // Replace any instances of Exit with NewBB in this and any nested loops...
463 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
464 if (I->hasExitBlock(Header))
465 I->changeExitBlock(Header, BEBlock); // Update exit block information
466
467 // Update dominator information (set, immdom, domtree, and domfrontier)
468 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
469}
470
471/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
472/// different kinds of dominator information (dominator sets, immediate
473/// dominators, dominator trees, and dominance frontiers) after a new block has
474/// been added to the CFG.
475///
476/// This only supports the case when an existing block (known as "Exit"), had
477/// some of its predecessors factored into a new basic block. This
478/// transformation inserts a new basic block ("NewBB"), with a single
479/// unconditional branch to Exit, and moves some predecessors of "Exit" to now
480/// branch to NewBB. These predecessors are listed in PredBlocks, even though
481/// they are the same as pred_begin(NewBB)/pred_end(NewBB).
482///
483void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
484 std::vector<BasicBlock*> &PredBlocks) {
485 assert(succ_begin(NewBB) != succ_end(NewBB) &&
486 ++succ_begin(NewBB) == succ_end(NewBB) &&
487 "NewBB should have a single successor!");
488 DominatorSet &DS = getAnalysis<DominatorSet>();
489
Chris Lattner650096a2003-02-27 20:27:08 +0000490 // Update dominator information... The blocks that dominate NewBB are the
491 // intersection of the dominators of predecessors, plus the block itself.
492 // The newly created basic block does not dominate anything except itself.
493 //
Chris Lattnerc4622a62003-10-13 00:37:13 +0000494 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
495 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
496 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
Chris Lattner650096a2003-02-27 20:27:08 +0000497 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
498 DS.addBasicBlock(NewBB, NewBBDomSet);
499
500 // Update immediate dominator information if we have it...
501 BasicBlock *NewBBIDom = 0;
502 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
503 // This block does not strictly dominate anything, so it is not an immediate
504 // dominator. To find the immediate dominator of the new exit node, we
505 // trace up the immediate dominators of a predecessor until we find a basic
506 // block that dominates the exit block.
507 //
Chris Lattnerc4622a62003-10-13 00:37:13 +0000508 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
Chris Lattner650096a2003-02-27 20:27:08 +0000509 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
510 assert(Dom != 0 && "No shared dominator found???");
511 Dom = ID->get(Dom);
512 }
513
514 // Set the immediate dominator now...
515 ID->addNewBlock(NewBB, Dom);
516 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
517 }
518
519 // Update DominatorTree information if it is active.
520 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
521 // NewBB doesn't dominate anything, so just create a node and link it into
522 // its immediate dominator. If we don't have ImmediateDominator info
523 // around, calculate the idom as above.
524 DominatorTree::Node *NewBBIDomNode;
525 if (NewBBIDom) {
526 NewBBIDomNode = DT->getNode(NewBBIDom);
527 } else {
Chris Lattnerc4622a62003-10-13 00:37:13 +0000528 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
Chris Lattnerbb9d03b2003-09-11 16:26:13 +0000529 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
Chris Lattner650096a2003-02-27 20:27:08 +0000530 NewBBIDomNode = NewBBIDomNode->getIDom();
531 assert(NewBBIDomNode && "No shared dominator found??");
532 }
533 }
534
535 // Create the new dominator tree node...
536 DT->createNewNode(NewBB, NewBBIDomNode);
537 }
538
539 // Update dominance frontier information...
540 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
541 // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it
Chris Lattnerc4622a62003-10-13 00:37:13 +0000542 // does dominate itself (and there is an edge (NewBB -> Exit)). Exit is the
543 // single successor of NewBB.
Chris Lattner650096a2003-02-27 20:27:08 +0000544 DominanceFrontier::DomSetType NewDFSet;
Chris Lattnerc4622a62003-10-13 00:37:13 +0000545 BasicBlock *Exit = *succ_begin(NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000546 NewDFSet.insert(Exit);
547 DF->addBasicBlock(NewBB, NewDFSet);
548
549 // Now we must loop over all of the dominance frontiers in the function,
Chris Lattnerc4622a62003-10-13 00:37:13 +0000550 // replacing occurrences of Exit with NewBB in some cases. All blocks that
551 // dominate a block in PredBlocks and contained Exit in their dominance
552 // frontier must be updated to contain NewBB instead. This only occurs if
553 // there is more than one block in PredBlocks.
554 //
555 if (PredBlocks.size() > 1) {
556 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
557 BasicBlock *Pred = PredBlocks[i];
558 // Get all of the dominators of the predecessor...
559 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
560 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
561 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
562 BasicBlock *PredDom = *PDI;
563
564 // If the Exit node is in DF(PredDom), then PredDom didn't dominate
565 // Exit but did dominate a predecessor of it. Now we change this
566 // entry to include NewBB in the DF instead of Exit.
Chris Lattner650096a2003-02-27 20:27:08 +0000567 DominanceFrontier::iterator DFI = DF->find(PredDom);
568 assert(DFI != DF->end() && "No dominance frontier for node?");
569 if (DFI->second.count(Exit)) {
570 DF->removeFromFrontier(DFI, Exit);
571 DF->addToFrontier(DFI, NewBB);
572 }
573 }
574 }
575 }
Chris Lattner650096a2003-02-27 20:27:08 +0000576 }
Chris Lattner61992f62002-09-26 16:17:31 +0000577}
Brian Gaeke960707c2003-11-11 22:41:34 +0000578