blob: 6fbf261835a9e00e5ae41616b97d5e0a95518219 [file] [log] [blame]
Chris Lattner67a98012003-10-12 21:44:18 +00001//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
John Criswellb576c942003-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 Lattner38acf9e2002-09-26 16:17:31 +00009//
Chris Lattneree2c50c2003-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 Lattnerdbf3cd72003-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 Lattner66ea98e2003-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 Lattnerdbf3cd72003-02-27 20:27:08 +000023//
Chris Lattner2ab6a732003-10-13 00:37:13 +000024// This pass also guarantees that loops will have exactly one backedge.
25//
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000026// Note that the simplifycfg pass will clean up blocks which are split out but
Chris Lattneree2c50c2003-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 Lattner38acf9e2002-09-26 16:17:31 +000032//
33//===----------------------------------------------------------------------===//
34
35#include "llvm/Transforms/Scalar.h"
Chris Lattner2ef703e2004-03-14 03:59:22 +000036#include "llvm/Constant.h"
Chris Lattner38acf9e2002-09-26 16:17:31 +000037#include "llvm/iTerminators.h"
38#include "llvm/iPHINode.h"
Chris Lattner2ef703e2004-03-14 03:59:22 +000039#include "llvm/Function.h"
40#include "llvm/Type.h"
Chris Lattner0f98e752003-12-19 06:27:08 +000041#include "llvm/Analysis/Dominators.h"
42#include "llvm/Analysis/LoopInfo.h"
Chris Lattner38acf9e2002-09-26 16:17:31 +000043#include "llvm/Support/CFG.h"
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000044#include "Support/SetOperations.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000045#include "Support/Statistic.h"
Chris Lattner74cd04e2003-02-28 03:07:54 +000046#include "Support/DepthFirstIterator.h"
Chris Lattner66ea98e2003-12-10 17:20:35 +000047using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000048
Chris Lattner38acf9e2002-09-26 16:17:31 +000049namespace {
Chris Lattneree2c50c2003-10-12 21:43:28 +000050 Statistic<>
Chris Lattner66ea98e2003-12-10 17:20:35 +000051 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
Chris Lattner38acf9e2002-09-26 16:17:31 +000052
Chris Lattneree2c50c2003-10-12 21:43:28 +000053 struct LoopSimplify : public FunctionPass {
Chris Lattner38acf9e2002-09-26 16:17:31 +000054 virtual bool runOnFunction(Function &F);
55
56 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57 // We need loop information to identify the loops...
58 AU.addRequired<LoopInfo>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000059 AU.addRequired<DominatorSet>();
Chris Lattner786c5642004-03-13 22:01:26 +000060 AU.addRequired<DominatorTree>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000061
62 AU.addPreserved<LoopInfo>();
63 AU.addPreserved<DominatorSet>();
64 AU.addPreserved<ImmediateDominators>();
65 AU.addPreserved<DominatorTree>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000066 AU.addPreserved<DominanceFrontier>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000067 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
68 }
69 private:
70 bool ProcessLoop(Loop *L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000071 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
72 const std::vector<BasicBlock*> &Preds);
73 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner38acf9e2002-09-26 16:17:31 +000074 void InsertPreheaderForLoop(Loop *L);
Chris Lattner2ab6a732003-10-13 00:37:13 +000075 void InsertUniqueBackedgeBlock(Loop *L);
76
77 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
78 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner38acf9e2002-09-26 16:17:31 +000079 };
80
Chris Lattneree2c50c2003-10-12 21:43:28 +000081 RegisterOpt<LoopSimplify>
82 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner38acf9e2002-09-26 16:17:31 +000083}
84
85// Publically exposed interface to pass...
Chris Lattner66ea98e2003-12-10 17:20:35 +000086const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
87Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner38acf9e2002-09-26 16:17:31 +000088
Chris Lattner38acf9e2002-09-26 16:17:31 +000089/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
90/// it in any convenient order) inserting preheaders...
91///
Chris Lattneree2c50c2003-10-12 21:43:28 +000092bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner38acf9e2002-09-26 16:17:31 +000093 bool Changed = false;
94 LoopInfo &LI = getAnalysis<LoopInfo>();
95
Chris Lattner329c1c62004-01-08 00:09:44 +000096 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
97 Changed |= ProcessLoop(*I);
Chris Lattner38acf9e2002-09-26 16:17:31 +000098
99 return Changed;
100}
101
102
103/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
104/// all loops have preheaders.
105///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000106bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000107 bool Changed = false;
108
Chris Lattner2ef703e2004-03-14 03:59:22 +0000109 // Check to see that no blocks (other than the header) in the loop have
110 // predecessors that are not in the loop. This is not valid for natural
111 // loops, but can occur if the blocks are unreachable. Since they are
112 // unreachable we can just shamelessly destroy their terminators to make them
113 // not branch into the loop!
114 assert(L->getBlocks()[0] == L->getHeader() &&
115 "Header isn't first block in loop?");
116 for (unsigned i = 1, e = L->getBlocks().size(); i != e; ++i) {
117 BasicBlock *LoopBB = L->getBlocks()[i];
118 Retry:
119 for (pred_iterator PI = pred_begin(LoopBB), E = pred_end(LoopBB);
120 PI != E; ++PI)
121 if (!L->contains(*PI)) {
122 // This predecessor is not in the loop. Kill its terminator!
123 BasicBlock *DeadBlock = *PI;
124 for (succ_iterator SI = succ_begin(DeadBlock), E = succ_end(DeadBlock);
125 SI != E; ++SI)
126 (*SI)->removePredecessor(DeadBlock); // Remove PHI node entries
127
128 // Delete the dead terminator.
129 DeadBlock->getInstList().pop_back();
130
131 Value *RetVal = 0;
132 if (LoopBB->getParent()->getReturnType() != Type::VoidTy)
133 RetVal = Constant::getNullValue(LoopBB->getParent()->getReturnType());
134 new ReturnInst(RetVal, DeadBlock);
135 goto Retry; // We just invalidated the pred_iterator. Retry.
136 }
137 }
138
Chris Lattner38acf9e2002-09-26 16:17:31 +0000139 // Does the loop already have a preheader? If so, don't modify the loop...
140 if (L->getLoopPreheader() == 0) {
141 InsertPreheaderForLoop(L);
142 NumInserted++;
143 Changed = true;
144 }
145
Chris Lattner66ea98e2003-12-10 17:20:35 +0000146 // Next, check to make sure that all exit nodes of the loop only have
147 // predecessors that are inside of the loop. This check guarantees that the
148 // loop preheader/header will dominate the exit blocks. If the exit block has
149 // predecessors from outside of the loop, split the edge now.
150 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i) {
151 BasicBlock *ExitBlock = L->getExitBlocks()[i];
152 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
153 PI != PE; ++PI)
154 if (!L->contains(*PI)) {
155 RewriteLoopExitBlock(L, ExitBlock);
156 NumInserted++;
157 Changed = true;
158 break;
159 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000160 }
161
Chris Lattner2ab6a732003-10-13 00:37:13 +0000162 // The preheader may have more than two predecessors at this point (from the
163 // preheader and from the backedges). To simplify the loop more, insert an
164 // extra back-edge block in the loop so that there is exactly one backedge.
165 if (L->getNumBackEdges() != 1) {
166 InsertUniqueBackedgeBlock(L);
167 NumInserted++;
168 Changed = true;
169 }
170
Chris Lattner329c1c62004-01-08 00:09:44 +0000171 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
172 Changed |= ProcessLoop(*I);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000173 return Changed;
174}
175
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000176/// SplitBlockPredecessors - Split the specified block into two blocks. We want
177/// to move the predecessors specified in the Preds list to point to the new
178/// block, leaving the remaining predecessors pointing to BB. This method
179/// updates the SSA PHINode's, but no other analyses.
180///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000181BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
182 const char *Suffix,
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000183 const std::vector<BasicBlock*> &Preds) {
184
185 // Create new basic block, insert right before the original block...
Chris Lattnerc24a0762004-02-04 03:58:28 +0000186 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000187
188 // The preheader first gets an unconditional branch to the loop header...
Chris Lattner108e4ab2003-11-21 16:52:05 +0000189 BranchInst *BI = new BranchInst(BB, NewBB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000190
191 // For every PHI node in the block, insert a PHI node into NewBB where the
192 // incoming values from the out of loop edges are moved to NewBB. We have two
193 // possible cases here. If the loop is dead, we just insert dummy entries
194 // into the PHI nodes for the new edge. If the loop is not dead, we move the
195 // incoming edges in BB into new PHI nodes in NewBB.
196 //
197 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner0f98e752003-12-19 06:27:08 +0000198 // Check to see if the values being merged into the new block need PHI
199 // nodes. If so, insert them.
200 for (BasicBlock::iterator I = BB->begin();
201 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
202
203 // Check to see if all of the values coming in are the same. If so, we
204 // don't need to create a new PHI node.
205 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
206 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
207 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
208 InVal = 0;
209 break;
210 }
211
212 // If the values coming into the block are not the same, we need a PHI.
213 if (InVal == 0) {
Chris Lattner010ba102003-12-09 23:12:55 +0000214 // Create the new PHI node, insert it into NewBB at the end of the block
215 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
216
217 // Move all of the edges from blocks outside the loop to the new PHI
218 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
219 Value *V = PN->removeIncomingValue(Preds[i]);
220 NewPHI->addIncoming(V, Preds[i]);
221 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000222 InVal = NewPHI;
223 } else {
224 // Remove all of the edges coming into the PHI nodes from outside of the
225 // block.
226 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
227 PN->removeIncomingValue(Preds[i], false);
Chris Lattner010ba102003-12-09 23:12:55 +0000228 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000229
230 // Add an incoming value to the PHI node in the loop for the preheader
231 // edge.
232 PN->addIncoming(InVal, NewBB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000233 }
234
235 // Now that the PHI nodes are updated, actually move the edges from
236 // Preds to point to NewBB instead of BB.
237 //
238 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
239 TerminatorInst *TI = Preds[i]->getTerminator();
240 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
241 if (TI->getSuccessor(s) == BB)
242 TI->setSuccessor(s, NewBB);
243 }
244
245 } else { // Otherwise the loop is dead...
246 for (BasicBlock::iterator I = BB->begin();
Chris Lattnere408e252003-04-23 16:37:45 +0000247 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000248 // Insert dummy values as the incoming value...
249 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
250 }
251 return NewBB;
252}
253
Chris Lattner8f6396e2003-05-12 22:04:34 +0000254// ChangeExitBlock - This recursive function is used to change any exit blocks
255// that use OldExit to use NewExit instead. This is recursive because children
256// may need to be processed as well.
257//
258static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) {
259 if (L->hasExitBlock(OldExit)) {
260 L->changeExitBlock(OldExit, NewExit);
Chris Lattner329c1c62004-01-08 00:09:44 +0000261 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
262 ChangeExitBlock(*I, OldExit, NewExit);
Chris Lattner8f6396e2003-05-12 22:04:34 +0000263 }
264}
265
Chris Lattner38acf9e2002-09-26 16:17:31 +0000266
267/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
268/// preheader, this method is called to insert one. This method has two phases:
269/// preheader insertion and analysis updating.
270///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000271void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000272 BasicBlock *Header = L->getHeader();
273
274 // Compute the set of predecessors of the loop that are not in the loop.
275 std::vector<BasicBlock*> OutsideBlocks;
276 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
277 PI != PE; ++PI)
278 if (!L->contains(*PI)) // Coming in from outside the loop?
279 OutsideBlocks.push_back(*PI); // Keep track of it...
280
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000281 // Split out the loop pre-header
282 BasicBlock *NewBB =
283 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000284
Chris Lattner38acf9e2002-09-26 16:17:31 +0000285 //===--------------------------------------------------------------------===//
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000286 // Update analysis results now that we have performed the transformation
Chris Lattner38acf9e2002-09-26 16:17:31 +0000287 //
288
289 // We know that we have loop information to update... update it now.
290 if (Loop *Parent = L->getParentLoop())
291 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner9f879cf2003-02-27 22:48:57 +0000292
293 // If the header for the loop used to be an exit node for another loop, then
294 // we need to update this to know that the loop-preheader is now the exit
295 // node. Note that the only loop that could have our header as an exit node
Chris Lattner8f6396e2003-05-12 22:04:34 +0000296 // is a sibling loop, ie, one with the same parent loop, or one if it's
297 // children.
298 //
Chris Lattner329c1c62004-01-08 00:09:44 +0000299 LoopInfo::iterator ParentLoops, ParentLoopsE;
300 if (Loop *Parent = L->getParentLoop()) {
301 ParentLoops = Parent->begin();
302 ParentLoopsE = Parent->end();
303 } else { // Must check top-level loops...
304 ParentLoops = getAnalysis<LoopInfo>().begin();
305 ParentLoopsE = getAnalysis<LoopInfo>().end();
306 }
Chris Lattner9f879cf2003-02-27 22:48:57 +0000307
Chris Lattner8f6396e2003-05-12 22:04:34 +0000308 // Loop over all sibling loops, performing the substitution (recursively to
309 // include child loops)...
Chris Lattner329c1c62004-01-08 00:09:44 +0000310 for (; ParentLoops != ParentLoopsE; ++ParentLoops)
311 ChangeExitBlock(*ParentLoops, Header, NewBB);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000312
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000313 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
Chris Lattner786c5642004-03-13 22:01:26 +0000314 DominatorTree &DT = getAnalysis<DominatorTree>();
315 DominatorTree::Node *HeaderDTNode = DT.getNode(Header);
316
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000317 {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000318 // The blocks that dominate NewBB are the blocks that dominate Header,
319 // minus Header, plus NewBB.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000320 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner4d018922002-09-29 21:41:38 +0000321 DomSet.insert(NewBB); // We dominate ourself
Chris Lattner38acf9e2002-09-26 16:17:31 +0000322 DomSet.erase(Header); // Header does not dominate us...
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000323 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner4d018922002-09-29 21:41:38 +0000324
325 // The newly created basic block dominates all nodes dominated by Header.
Chris Lattner786c5642004-03-13 22:01:26 +0000326 for (DominatorTree::Node::iterator I = HeaderDTNode->begin(),
327 E = HeaderDTNode->end(); I != E; ++I)
328 DS.addDominator((*I)->getBlock(), NewBB);
329 }
330
331 { // Update the dominator tree information.
332 // The immediate dominator of the preheader is the immediate dominator of
333 // the old header.
334 //
335 DominatorTree::Node *PHNode =
336 DT.createNewNode(NewBB, HeaderDTNode->getIDom());
337
338 // Change the header node so that PNHode is the new immediate dominator
339 DT.changeImmediateDominator(HeaderDTNode, PHNode);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000340 }
341
342 // Update immediate dominator information if we have it...
343 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
344 // Whatever i-dominated the header node now immediately dominates NewBB
345 ID->addNewBlock(NewBB, ID->get(Header));
346
347 // The preheader now is the immediate dominator for the header node...
348 ID->setImmediateDominator(Header, NewBB);
349 }
350
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000351 // Update dominance frontier information...
352 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
353 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
354 // everything that Header does, and it strictly dominates Header in
355 // addition.
356 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
357 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
358 NewDFSet.erase(Header);
359 DF->addBasicBlock(NewBB, NewDFSet);
360
361 // Now we must loop over all of the dominance frontiers in the function,
Misha Brukmandfa5f832003-09-09 21:54:45 +0000362 // replacing occurrences of Header with NewBB in some cases. If a block
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000363 // dominates a (now) predecessor of NewBB, but did not strictly dominate
364 // Header, it will have Header in it's DF set, but should now have NewBB in
365 // its set.
366 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
367 // Get all of the dominators of the predecessor...
368 const DominatorSet::DomSetType &PredDoms =
369 DS.getDominators(OutsideBlocks[i]);
370 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
371 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
372 BasicBlock *PredDom = *PDI;
373 // If the loop header is in DF(PredDom), then PredDom didn't dominate
374 // the header but did dominate a predecessor outside of the loop. Now
375 // we change this entry to include the preheader in the DF instead of
376 // the header.
377 DominanceFrontier::iterator DFI = DF->find(PredDom);
378 assert(DFI != DF->end() && "No dominance frontier for node?");
379 if (DFI->second.count(Header)) {
380 DF->removeFromFrontier(DFI, Header);
381 DF->addToFrontier(DFI, NewBB);
382 }
383 }
384 }
385 }
386}
387
Chris Lattneree2c50c2003-10-12 21:43:28 +0000388void LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000389 DominatorSet &DS = getAnalysis<DominatorSet>();
Chris Lattner7e7ad492003-02-27 22:31:07 +0000390 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
391 != L->getExitBlocks().end() && "Not a current exit block!");
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000392
393 std::vector<BasicBlock*> LoopBlocks;
394 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
395 if (L->contains(*I))
396 LoopBlocks.push_back(*I);
397
Chris Lattner7e7ad492003-02-27 22:31:07 +0000398 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
399 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
400
Chris Lattner69269ac2003-02-27 21:50:19 +0000401 // Update Loop Information - we know that the new block will be in the parent
402 // loop of L.
403 if (Loop *Parent = L->getParentLoop())
404 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner74cd04e2003-02-28 03:07:54 +0000405
406 // Replace any instances of Exit with NewBB in this and any nested loops...
407 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
Chris Lattner63159382003-02-28 16:54:17 +0000408 if (I->hasExitBlock(Exit))
409 I->changeExitBlock(Exit, NewBB); // Update exit block information
Chris Lattner69269ac2003-02-27 21:50:19 +0000410
Chris Lattner2ab6a732003-10-13 00:37:13 +0000411 // Update dominator information (set, immdom, domtree, and domfrontier)
412 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
413}
414
415/// InsertUniqueBackedgeBlock - This method is called when the specified loop
416/// has more than one backedge in it. If this occurs, revector all of these
417/// backedges to target a new basic block and have that block branch to the loop
418/// header. This ensures that loops have exactly one backedge.
419///
420void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
421 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
422
423 // Get information about the loop
424 BasicBlock *Preheader = L->getLoopPreheader();
425 BasicBlock *Header = L->getHeader();
426 Function *F = Header->getParent();
427
428 // Figure out which basic blocks contain back-edges to the loop header.
429 std::vector<BasicBlock*> BackedgeBlocks;
430 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
431 if (*I != Preheader) BackedgeBlocks.push_back(*I);
432
433 // Create and insert the new backedge block...
434 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattner108e4ab2003-11-21 16:52:05 +0000435 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000436
437 // Move the new backedge block to right after the last backedge block.
438 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
439 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
440
441 // Now that the block has been inserted into the function, create PHI nodes in
442 // the backedge block which correspond to any PHI nodes in the header block.
443 for (BasicBlock::iterator I = Header->begin();
444 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
445 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
446 BETerminator);
447 NewPN->op_reserve(2*BackedgeBlocks.size());
448
449 // Loop over the PHI node, moving all entries except the one for the
450 // preheader over to the new PHI node.
451 unsigned PreheaderIdx = ~0U;
452 bool HasUniqueIncomingValue = true;
453 Value *UniqueValue = 0;
454 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
455 BasicBlock *IBB = PN->getIncomingBlock(i);
456 Value *IV = PN->getIncomingValue(i);
457 if (IBB == Preheader) {
458 PreheaderIdx = i;
459 } else {
460 NewPN->addIncoming(IV, IBB);
461 if (HasUniqueIncomingValue) {
462 if (UniqueValue == 0)
463 UniqueValue = IV;
464 else if (UniqueValue != IV)
465 HasUniqueIncomingValue = false;
466 }
467 }
468 }
469
470 // Delete all of the incoming values from the old PN except the preheader's
471 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
472 if (PreheaderIdx != 0) {
473 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
474 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
475 }
476 PN->op_erase(PN->op_begin()+2, PN->op_end());
477
478 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
479 PN->addIncoming(NewPN, BEBlock);
480
481 // As an optimization, if all incoming values in the new PhiNode (which is a
482 // subset of the incoming values of the old PHI node) have the same value,
483 // eliminate the PHI Node.
484 if (HasUniqueIncomingValue) {
485 NewPN->replaceAllUsesWith(UniqueValue);
486 BEBlock->getInstList().erase(NewPN);
487 }
488 }
489
490 // Now that all of the PHI nodes have been inserted and adjusted, modify the
491 // backedge blocks to just to the BEBlock instead of the header.
492 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
493 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
494 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
495 if (TI->getSuccessor(Op) == Header)
496 TI->setSuccessor(Op, BEBlock);
497 }
498
499 //===--- Update all analyses which we must preserve now -----------------===//
500
501 // Update Loop Information - we know that this block is now in the current
502 // loop and all parent loops.
503 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
504
505 // Replace any instances of Exit with NewBB in this and any nested loops...
506 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
507 if (I->hasExitBlock(Header))
508 I->changeExitBlock(Header, BEBlock); // Update exit block information
509
510 // Update dominator information (set, immdom, domtree, and domfrontier)
511 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
512}
513
514/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
515/// different kinds of dominator information (dominator sets, immediate
516/// dominators, dominator trees, and dominance frontiers) after a new block has
517/// been added to the CFG.
518///
Chris Lattner4f02fc22004-02-05 21:12:24 +0000519/// This only supports the case when an existing block (known as "NewBBSucc"),
520/// had some of its predecessors factored into a new basic block. This
Chris Lattner2ab6a732003-10-13 00:37:13 +0000521/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner4f02fc22004-02-05 21:12:24 +0000522/// unconditional branch to NewBBSucc, and moves some predecessors of
523/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
524/// PredBlocks, even though they are the same as
525/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattner2ab6a732003-10-13 00:37:13 +0000526///
527void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
528 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000529 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattner2ab6a732003-10-13 00:37:13 +0000530 assert(succ_begin(NewBB) != succ_end(NewBB) &&
531 ++succ_begin(NewBB) == succ_end(NewBB) &&
532 "NewBB should have a single successor!");
Chris Lattner4f02fc22004-02-05 21:12:24 +0000533 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000534 DominatorSet &DS = getAnalysis<DominatorSet>();
535
Chris Lattner4f02fc22004-02-05 21:12:24 +0000536 // The newly inserted basic block will dominate existing basic blocks iff the
537 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
538 // the non-pred blocks, then they all must be the same block!
539 bool NewBBDominatesNewBBSucc = true;
540 {
541 BasicBlock *OnePred = PredBlocks[0];
542 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
543 if (PredBlocks[i] != OnePred) {
544 NewBBDominatesNewBBSucc = false;
545 break;
546 }
547
548 if (NewBBDominatesNewBBSucc)
549 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
550 PI != E; ++PI)
Chris Lattner99dcc1d2004-02-05 23:20:59 +0000551 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000552 NewBBDominatesNewBBSucc = false;
553 break;
554 }
555 }
556
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000557 // Update dominator information... The blocks that dominate NewBB are the
558 // intersection of the dominators of predecessors, plus the block itself.
559 // The newly created basic block does not dominate anything except itself.
560 //
Chris Lattner2ab6a732003-10-13 00:37:13 +0000561 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
562 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
563 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000564 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
565 DS.addBasicBlock(NewBB, NewBBDomSet);
566
Chris Lattner4f02fc22004-02-05 21:12:24 +0000567 // If NewBB dominates some blocks, then it will dominate all blocks that
Chris Lattner3e0b8702004-02-05 22:33:26 +0000568 // NewBBSucc does.
Chris Lattner4f02fc22004-02-05 21:12:24 +0000569 if (NewBBDominatesNewBBSucc) {
570 BasicBlock *PredBlock = PredBlocks[0];
571 Function *F = NewBB->getParent();
572 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner3e0b8702004-02-05 22:33:26 +0000573 if (DS.dominates(NewBBSucc, I))
Chris Lattner4f02fc22004-02-05 21:12:24 +0000574 DS.addDominator(I, NewBB);
575 }
576
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000577 // Update immediate dominator information if we have it...
578 BasicBlock *NewBBIDom = 0;
579 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000580 // To find the immediate dominator of the new exit node, we trace up the
581 // immediate dominators of a predecessor until we find a basic block that
582 // dominates the exit block.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000583 //
Chris Lattner2ab6a732003-10-13 00:37:13 +0000584 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000585 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
586 assert(Dom != 0 && "No shared dominator found???");
587 Dom = ID->get(Dom);
588 }
589
590 // Set the immediate dominator now...
591 ID->addNewBlock(NewBB, Dom);
592 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
Chris Lattner4f02fc22004-02-05 21:12:24 +0000593
594 // If NewBB strictly dominates other blocks, we need to update their idom's
595 // now. The only block that need adjustment is the NewBBSucc block, whose
596 // idom should currently be set to PredBlocks[0].
597 if (NewBBDominatesNewBBSucc) {
598 assert(ID->get(NewBBSucc) == PredBlocks[0] &&
599 "Immediate dominator update code broken!");
600 ID->setImmediateDominator(NewBBSucc, NewBB);
601 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000602 }
603
604 // Update DominatorTree information if it is active.
605 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000606 // If we don't have ImmediateDominator info around, calculate the idom as
607 // above.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000608 DominatorTree::Node *NewBBIDomNode;
609 if (NewBBIDom) {
610 NewBBIDomNode = DT->getNode(NewBBIDom);
611 } else {
Chris Lattner2ab6a732003-10-13 00:37:13 +0000612 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
Chris Lattnerc444a422003-09-11 16:26:13 +0000613 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000614 NewBBIDomNode = NewBBIDomNode->getIDom();
615 assert(NewBBIDomNode && "No shared dominator found??");
616 }
617 }
618
Chris Lattner4f02fc22004-02-05 21:12:24 +0000619 // Create the new dominator tree node... and set the idom of NewBB.
620 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
621
622 // If NewBB strictly dominates other blocks, then it is now the immediate
623 // dominator of NewBBSucc. Update the dominator tree as appropriate.
624 if (NewBBDominatesNewBBSucc) {
625 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
626 assert(NewBBSuccNode->getIDom()->getBlock() == PredBlocks[0] &&
627 "Immediate tree update code broken!");
628 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
629 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000630 }
631
632 // Update dominance frontier information...
633 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000634 // If NewBB dominates NewBBSucc, then the global dominance frontiers are not
635 // changed. DF(NewBB) is now going to be the DF(PredBlocks[0]) without the
636 // stuff that the new block does not dominate a predecessor of.
637 if (NewBBDominatesNewBBSucc) {
638 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
639 if (DFI != DF->end()) {
640 DominanceFrontier::DomSetType Set = DFI->second;
641 // Filter out stuff in Set that we do not dominate a predecessor of.
642 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
643 E = Set.end(); SetI != E;) {
644 bool DominatesPred = false;
645 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
646 PI != E; ++PI)
647 if (DS.dominates(NewBB, *PI))
648 DominatesPred = true;
649 if (!DominatesPred)
650 Set.erase(SetI++);
651 else
652 ++SetI;
653 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000654
Chris Lattner4f02fc22004-02-05 21:12:24 +0000655 DF->addBasicBlock(NewBB, Set);
656 }
657
658 } else {
659 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
660 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
661 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
662 DominanceFrontier::DomSetType NewDFSet;
663 NewDFSet.insert(NewBBSucc);
664 DF->addBasicBlock(NewBB, NewDFSet);
665
666 // Now we must loop over all of the dominance frontiers in the function,
667 // replacing occurrences of NewBBSucc with NewBB in some cases. All
668 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
669 // their dominance frontier must be updated to contain NewBB instead.
670 //
Chris Lattner2ab6a732003-10-13 00:37:13 +0000671 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
672 BasicBlock *Pred = PredBlocks[i];
673 // Get all of the dominators of the predecessor...
674 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
675 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
676 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
677 BasicBlock *PredDom = *PDI;
678
Chris Lattner4f02fc22004-02-05 21:12:24 +0000679 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
680 // dominate NewBBSucc but did dominate a predecessor of it. Now we
681 // change this entry to include NewBB in the DF instead of NewBBSucc.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000682 DominanceFrontier::iterator DFI = DF->find(PredDom);
683 assert(DFI != DF->end() && "No dominance frontier for node?");
Chris Lattner4f02fc22004-02-05 21:12:24 +0000684 if (DFI->second.count(NewBBSucc)) {
685 DF->removeFromFrontier(DFI, NewBBSucc);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000686 DF->addToFrontier(DFI, NewBB);
687 }
688 }
689 }
690 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000691 }
Chris Lattner38acf9e2002-09-26 16:17:31 +0000692}
Brian Gaeked0fde302003-11-11 22:41:34 +0000693