1 //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This pass performs several transformations to transform natural loops into a
11 // simpler form, which makes subsequent analyses and transformations simpler and
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.
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
20 // 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.
24 // This pass also guarantees that loops will have exactly one backedge.
26 // Note that the simplifycfg pass will clean up blocks which are split out but
27 // end up being unnecessary, so usage of this pass should not pessimize
30 // This pass obviously modifies the CFG, but updates loop information and
31 // dominator information.
33 //===----------------------------------------------------------------------===//
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Constant.h"
37 #include "llvm/Instructions.h"
38 #include "llvm/Function.h"
39 #include "llvm/Type.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Analysis/LoopInfo.h"
42 #include "llvm/Support/CFG.h"
43 #include "llvm/Transforms/Utils/Local.h"
44 #include "llvm/ADT/SetOperations.h"
45 #include "llvm/ADT/SetVector.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/ADT/DepthFirstIterator.h"
52 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
54 NumNested("loopsimplify", "Number of nested loops split out");
56 struct LoopSimplify : public FunctionPass {
57 virtual bool runOnFunction(Function &F);
59 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60 // We need loop information to identify the loops...
61 AU.addRequired<LoopInfo>();
62 AU.addRequired<DominatorSet>();
63 AU.addRequired<DominatorTree>();
65 AU.addPreserved<LoopInfo>();
66 AU.addPreserved<DominatorSet>();
67 AU.addPreserved<ImmediateDominators>();
68 AU.addPreserved<DominatorTree>();
69 AU.addPreserved<DominanceFrontier>();
70 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
73 bool ProcessLoop(Loop *L);
74 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
75 const std::vector<BasicBlock*> &Preds);
76 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
77 void InsertPreheaderForLoop(Loop *L);
78 Loop *SeparateNestedLoop(Loop *L);
79 void InsertUniqueBackedgeBlock(Loop *L);
81 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
82 std::vector<BasicBlock*> &PredBlocks);
85 RegisterOpt<LoopSimplify>
86 X("loopsimplify", "Canonicalize natural loops", true);
89 // Publically exposed interface to pass...
90 const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
91 FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
93 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
94 /// it in any convenient order) inserting preheaders...
96 bool LoopSimplify::runOnFunction(Function &F) {
98 LoopInfo &LI = getAnalysis<LoopInfo>();
100 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
101 Changed |= ProcessLoop(*I);
107 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
108 /// all loops have preheaders.
110 bool LoopSimplify::ProcessLoop(Loop *L) {
111 bool Changed = false;
113 // Check to see that no blocks (other than the header) in the loop have
114 // predecessors that are not in the loop. This is not valid for natural
115 // loops, but can occur if the blocks are unreachable. Since they are
116 // unreachable we can just shamelessly destroy their terminators to make them
117 // not branch into the loop!
118 assert(L->getBlocks()[0] == L->getHeader() &&
119 "Header isn't first block in loop?");
120 for (unsigned i = 1, e = L->getBlocks().size(); i != e; ++i) {
121 BasicBlock *LoopBB = L->getBlocks()[i];
123 for (pred_iterator PI = pred_begin(LoopBB), E = pred_end(LoopBB);
125 if (!L->contains(*PI)) {
126 // This predecessor is not in the loop. Kill its terminator!
127 BasicBlock *DeadBlock = *PI;
128 for (succ_iterator SI = succ_begin(DeadBlock), E = succ_end(DeadBlock);
130 (*SI)->removePredecessor(DeadBlock); // Remove PHI node entries
132 // Delete the dead terminator.
133 DeadBlock->getInstList().pop_back();
136 if (LoopBB->getParent()->getReturnType() != Type::VoidTy)
137 RetVal = Constant::getNullValue(LoopBB->getParent()->getReturnType());
138 new ReturnInst(RetVal, DeadBlock);
139 goto Retry; // We just invalidated the pred_iterator. Retry.
143 // Does the loop already have a preheader? If so, don't modify the loop...
144 if (L->getLoopPreheader() == 0) {
145 InsertPreheaderForLoop(L);
150 // Next, check to make sure that all exit nodes of the loop only have
151 // predecessors that are inside of the loop. This check guarantees that the
152 // loop preheader/header will dominate the exit blocks. If the exit block has
153 // predecessors from outside of the loop, split the edge now.
154 std::vector<BasicBlock*> ExitBlocks;
155 L->getExitBlocks(ExitBlocks);
157 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
158 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
159 E = ExitBlockSet.end(); I != E; ++I) {
160 BasicBlock *ExitBlock = *I;
161 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
163 if (!L->contains(*PI)) {
164 RewriteLoopExitBlock(L, ExitBlock);
171 // If the header has more than two predecessors at this point (from the
172 // preheader and from multiple backedges), we must adjust the loop.
173 if (L->getNumBackEdges() != 1) {
174 // If this is really a nested loop, rip it out into a child loop.
175 if (Loop *NL = SeparateNestedLoop(L)) {
177 // This is a big restructuring change, reprocess the whole loop.
182 InsertUniqueBackedgeBlock(L);
187 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
188 Changed |= ProcessLoop(*I);
192 /// SplitBlockPredecessors - Split the specified block into two blocks. We want
193 /// to move the predecessors specified in the Preds list to point to the new
194 /// block, leaving the remaining predecessors pointing to BB. This method
195 /// updates the SSA PHINode's, but no other analyses.
197 BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
199 const std::vector<BasicBlock*> &Preds) {
201 // Create new basic block, insert right before the original block...
202 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
204 // The preheader first gets an unconditional branch to the loop header...
205 BranchInst *BI = new BranchInst(BB, NewBB);
207 // For every PHI node in the block, insert a PHI node into NewBB where the
208 // incoming values from the out of loop edges are moved to NewBB. We have two
209 // possible cases here. If the loop is dead, we just insert dummy entries
210 // into the PHI nodes for the new edge. If the loop is not dead, we move the
211 // incoming edges in BB into new PHI nodes in NewBB.
213 if (!Preds.empty()) { // Is the loop not obviously dead?
214 // Check to see if the values being merged into the new block need PHI
215 // nodes. If so, insert them.
216 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
217 PHINode *PN = cast<PHINode>(I);
220 // Check to see if all of the values coming in are the same. If so, we
221 // don't need to create a new PHI node.
222 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
223 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
224 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
229 // If the values coming into the block are not the same, we need a PHI.
231 // Create the new PHI node, insert it into NewBB at the end of the block
232 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
234 // Move all of the edges from blocks outside the loop to the new PHI
235 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
236 Value *V = PN->removeIncomingValue(Preds[i], false);
237 NewPHI->addIncoming(V, Preds[i]);
241 // Remove all of the edges coming into the PHI nodes from outside of the
243 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
244 PN->removeIncomingValue(Preds[i], false);
247 // Add an incoming value to the PHI node in the loop for the preheader
249 PN->addIncoming(InVal, NewBB);
251 // Can we eliminate this phi node now?
252 if (Value *V = hasConstantValue(PN)) {
253 if (!isa<Instruction>(V) ||
254 getAnalysis<DominatorSet>().dominates(cast<Instruction>(V), PN)) {
255 PN->replaceAllUsesWith(V);
256 BB->getInstList().erase(PN);
261 // Now that the PHI nodes are updated, actually move the edges from
262 // Preds to point to NewBB instead of BB.
264 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
265 TerminatorInst *TI = Preds[i]->getTerminator();
266 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
267 if (TI->getSuccessor(s) == BB)
268 TI->setSuccessor(s, NewBB);
271 } else { // Otherwise the loop is dead...
272 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
273 PHINode *PN = cast<PHINode>(I);
274 // Insert dummy values as the incoming value...
275 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
281 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
282 /// preheader, this method is called to insert one. This method has two phases:
283 /// preheader insertion and analysis updating.
285 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
286 BasicBlock *Header = L->getHeader();
288 // Compute the set of predecessors of the loop that are not in the loop.
289 std::vector<BasicBlock*> OutsideBlocks;
290 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
292 if (!L->contains(*PI)) // Coming in from outside the loop?
293 OutsideBlocks.push_back(*PI); // Keep track of it...
295 // Split out the loop pre-header
297 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
299 //===--------------------------------------------------------------------===//
300 // Update analysis results now that we have performed the transformation
303 // We know that we have loop information to update... update it now.
304 if (Loop *Parent = L->getParentLoop())
305 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
307 // If the header for the loop used to be an exit node for another loop, then
308 // we need to update this to know that the loop-preheader is now the exit
309 // node. Note that the only loop that could have our header as an exit node
310 // is a sibling loop, ie, one with the same parent loop, or one if it's
313 LoopInfo::iterator ParentLoops, ParentLoopsE;
314 if (Loop *Parent = L->getParentLoop()) {
315 ParentLoops = Parent->begin();
316 ParentLoopsE = Parent->end();
317 } else { // Must check top-level loops...
318 ParentLoops = getAnalysis<LoopInfo>().begin();
319 ParentLoopsE = getAnalysis<LoopInfo>().end();
322 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
323 DominatorTree &DT = getAnalysis<DominatorTree>();
326 // Update the dominator tree information.
327 // The immediate dominator of the preheader is the immediate dominator of
329 DominatorTree::Node *PHDomTreeNode =
330 DT.createNewNode(NewBB, DT.getNode(Header)->getIDom());
332 // Change the header node so that PNHode is the new immediate dominator
333 DT.changeImmediateDominator(DT.getNode(Header), PHDomTreeNode);
336 // The blocks that dominate NewBB are the blocks that dominate Header,
337 // minus Header, plus NewBB.
338 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
339 DomSet.erase(Header); // Header does not dominate us...
340 DS.addBasicBlock(NewBB, DomSet);
342 // The newly created basic block dominates all nodes dominated by Header.
343 for (df_iterator<DominatorTree::Node*> DFI = df_begin(PHDomTreeNode),
344 E = df_end(PHDomTreeNode); DFI != E; ++DFI)
345 DS.addDominator((*DFI)->getBlock(), NewBB);
348 // Update immediate dominator information if we have it...
349 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
350 // Whatever i-dominated the header node now immediately dominates NewBB
351 ID->addNewBlock(NewBB, ID->get(Header));
353 // The preheader now is the immediate dominator for the header node...
354 ID->setImmediateDominator(Header, NewBB);
357 // Update dominance frontier information...
358 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
359 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
360 // everything that Header does, and it strictly dominates Header in
362 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
363 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
364 NewDFSet.erase(Header);
365 DF->addBasicBlock(NewBB, NewDFSet);
367 // Now we must loop over all of the dominance frontiers in the function,
368 // replacing occurrences of Header with NewBB in some cases. If a block
369 // dominates a (now) predecessor of NewBB, but did not strictly dominate
370 // Header, it will have Header in it's DF set, but should now have NewBB in
372 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
373 // Get all of the dominators of the predecessor...
374 const DominatorSet::DomSetType &PredDoms =
375 DS.getDominators(OutsideBlocks[i]);
376 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
377 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
378 BasicBlock *PredDom = *PDI;
379 // If the loop header is in DF(PredDom), then PredDom didn't dominate
380 // the header but did dominate a predecessor outside of the loop. Now
381 // we change this entry to include the preheader in the DF instead of
383 DominanceFrontier::iterator DFI = DF->find(PredDom);
384 assert(DFI != DF->end() && "No dominance frontier for node?");
385 if (DFI->second.count(Header)) {
386 DF->removeFromFrontier(DFI, Header);
387 DF->addToFrontier(DFI, NewBB);
394 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
395 /// blocks. This method is used to split exit blocks that have predecessors
396 /// outside of the loop.
397 BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
398 DominatorSet &DS = getAnalysis<DominatorSet>();
400 std::vector<BasicBlock*> LoopBlocks;
401 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
403 LoopBlocks.push_back(*I);
405 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
406 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
408 // Update Loop Information - we know that the new block will be in the parent
410 if (Loop *Parent = L->getParentLoop())
411 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
413 // Update dominator information (set, immdom, domtree, and domfrontier)
414 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
418 /// AddBlockAndPredsToSet - Add the specified block, and all of its
419 /// predecessors, to the specified set, if it's not already in there. Stop
420 /// predecessor traversal when we reach StopBlock.
421 static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
422 std::set<BasicBlock*> &Blocks) {
423 if (!Blocks.insert(BB).second) return; // already processed.
424 if (BB == StopBlock) return; // Stop here!
426 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
427 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
430 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
431 /// PHI node that tells us how to partition the loops.
432 static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorSet &DS) {
433 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
434 PHINode *PN = cast<PHINode>(I);
436 if (Value *V = hasConstantValue(PN))
437 if (!isa<Instruction>(V) || DS.dominates(cast<Instruction>(V), PN)) {
438 // This is a degenerate PHI already, don't modify it!
439 PN->replaceAllUsesWith(V);
440 PN->getParent()->getInstList().erase(PN);
444 // Scan this PHI node looking for a use of the PHI node by itself.
445 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
446 if (PN->getIncomingValue(i) == PN &&
447 L->contains(PN->getIncomingBlock(i)))
448 // We found something tasty to remove.
454 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
455 /// them out into a nested loop. This is important for code that looks like
460 /// br cond, Loop, Next
462 /// br cond2, Loop, Out
464 /// To identify this common case, we look at the PHI nodes in the header of the
465 /// loop. PHI nodes with unchanging values on one backedge correspond to values
466 /// that change in the "outer" loop, but not in the "inner" loop.
468 /// If we are able to separate out a loop, return the new outer loop that was
471 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
472 PHINode *PN = FindPHIToPartitionLoops(L, getAnalysis<DominatorSet>());
473 if (PN == 0) return 0; // No known way to partition.
475 // Pull out all predecessors that have varying values in the loop. This
476 // handles the case when a PHI node has multiple instances of itself as
478 std::vector<BasicBlock*> OuterLoopPreds;
479 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
480 if (PN->getIncomingValue(i) != PN ||
481 !L->contains(PN->getIncomingBlock(i)))
482 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
484 BasicBlock *Header = L->getHeader();
485 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
487 // Update dominator information (set, immdom, domtree, and domfrontier)
488 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
490 // Create the new outer loop.
491 Loop *NewOuter = new Loop();
493 LoopInfo &LI = getAnalysis<LoopInfo>();
495 // Change the parent loop to use the outer loop as its child now.
496 if (Loop *Parent = L->getParentLoop())
497 Parent->replaceChildLoopWith(L, NewOuter);
499 LI.changeTopLevelLoop(L, NewOuter);
501 // This block is going to be our new header block: add it to this loop and all
503 NewOuter->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
505 // L is now a subloop of our outer loop.
506 NewOuter->addChildLoop(L);
508 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
509 NewOuter->addBlockEntry(L->getBlocks()[i]);
511 // Determine which blocks should stay in L and which should be moved out to
512 // the Outer loop now.
513 DominatorSet &DS = getAnalysis<DominatorSet>();
514 std::set<BasicBlock*> BlocksInL;
515 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
516 if (DS.dominates(Header, *PI))
517 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
520 // Scan all of the loop children of L, moving them to OuterLoop if they are
521 // not part of the inner loop.
522 for (Loop::iterator I = L->begin(); I != L->end(); )
523 if (BlocksInL.count((*I)->getHeader()))
524 ++I; // Loop remains in L
526 NewOuter->addChildLoop(L->removeChildLoop(I));
528 // Now that we know which blocks are in L and which need to be moved to
529 // OuterLoop, move any blocks that need it.
530 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
531 BasicBlock *BB = L->getBlocks()[i];
532 if (!BlocksInL.count(BB)) {
533 // Move this block to the parent, updating the exit blocks sets
534 L->removeBlockFromLoop(BB);
536 LI.changeLoopFor(BB, NewOuter);
546 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
547 /// has more than one backedge in it. If this occurs, revector all of these
548 /// backedges to target a new basic block and have that block branch to the loop
549 /// header. This ensures that loops have exactly one backedge.
551 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
552 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
554 // Get information about the loop
555 BasicBlock *Preheader = L->getLoopPreheader();
556 BasicBlock *Header = L->getHeader();
557 Function *F = Header->getParent();
559 // Figure out which basic blocks contain back-edges to the loop header.
560 std::vector<BasicBlock*> BackedgeBlocks;
561 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
562 if (*I != Preheader) BackedgeBlocks.push_back(*I);
564 // Create and insert the new backedge block...
565 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
566 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
568 // Move the new backedge block to right after the last backedge block.
569 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
570 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
572 // Now that the block has been inserted into the function, create PHI nodes in
573 // the backedge block which correspond to any PHI nodes in the header block.
574 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
575 PHINode *PN = cast<PHINode>(I);
576 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
578 NewPN->op_reserve(2*BackedgeBlocks.size());
580 // Loop over the PHI node, moving all entries except the one for the
581 // preheader over to the new PHI node.
582 unsigned PreheaderIdx = ~0U;
583 bool HasUniqueIncomingValue = true;
584 Value *UniqueValue = 0;
585 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
586 BasicBlock *IBB = PN->getIncomingBlock(i);
587 Value *IV = PN->getIncomingValue(i);
588 if (IBB == Preheader) {
591 NewPN->addIncoming(IV, IBB);
592 if (HasUniqueIncomingValue) {
593 if (UniqueValue == 0)
595 else if (UniqueValue != IV)
596 HasUniqueIncomingValue = false;
601 // Delete all of the incoming values from the old PN except the preheader's
602 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
603 if (PreheaderIdx != 0) {
604 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
605 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
607 PN->op_erase(PN->op_begin()+2, PN->op_end());
609 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
610 PN->addIncoming(NewPN, BEBlock);
612 // As an optimization, if all incoming values in the new PhiNode (which is a
613 // subset of the incoming values of the old PHI node) have the same value,
614 // eliminate the PHI Node.
615 if (HasUniqueIncomingValue) {
616 NewPN->replaceAllUsesWith(UniqueValue);
617 BEBlock->getInstList().erase(NewPN);
621 // Now that all of the PHI nodes have been inserted and adjusted, modify the
622 // backedge blocks to just to the BEBlock instead of the header.
623 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
624 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
625 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
626 if (TI->getSuccessor(Op) == Header)
627 TI->setSuccessor(Op, BEBlock);
630 //===--- Update all analyses which we must preserve now -----------------===//
632 // Update Loop Information - we know that this block is now in the current
633 // loop and all parent loops.
634 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
636 // Update dominator information (set, immdom, domtree, and domfrontier)
637 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
640 /// UpdateDomInfoForRevectoredPreds - This method is used to update the four
641 /// different kinds of dominator information (dominator sets, immediate
642 /// dominators, dominator trees, and dominance frontiers) after a new block has
643 /// been added to the CFG.
645 /// This only supports the case when an existing block (known as "NewBBSucc"),
646 /// had some of its predecessors factored into a new basic block. This
647 /// transformation inserts a new basic block ("NewBB"), with a single
648 /// unconditional branch to NewBBSucc, and moves some predecessors of
649 /// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
650 /// PredBlocks, even though they are the same as
651 /// pred_begin(NewBB)/pred_end(NewBB).
653 void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
654 std::vector<BasicBlock*> &PredBlocks) {
655 assert(!PredBlocks.empty() && "No predblocks??");
656 assert(succ_begin(NewBB) != succ_end(NewBB) &&
657 ++succ_begin(NewBB) == succ_end(NewBB) &&
658 "NewBB should have a single successor!");
659 BasicBlock *NewBBSucc = *succ_begin(NewBB);
660 DominatorSet &DS = getAnalysis<DominatorSet>();
662 // Update dominator information... The blocks that dominate NewBB are the
663 // intersection of the dominators of predecessors, plus the block itself.
665 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
666 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
667 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
668 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
669 DS.addBasicBlock(NewBB, NewBBDomSet);
671 // The newly inserted basic block will dominate existing basic blocks iff the
672 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
673 // the non-pred blocks, then they all must be the same block!
675 bool NewBBDominatesNewBBSucc = true;
677 BasicBlock *OnePred = PredBlocks[0];
678 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
679 if (PredBlocks[i] != OnePred) {
680 NewBBDominatesNewBBSucc = false;
684 if (NewBBDominatesNewBBSucc)
685 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
687 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
688 NewBBDominatesNewBBSucc = false;
693 // The other scenario where the new block can dominate its successors are when
694 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
696 if (!NewBBDominatesNewBBSucc) {
697 NewBBDominatesNewBBSucc = true;
698 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
700 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
701 NewBBDominatesNewBBSucc = false;
706 // If NewBB dominates some blocks, then it will dominate all blocks that
708 if (NewBBDominatesNewBBSucc) {
709 BasicBlock *PredBlock = PredBlocks[0];
710 Function *F = NewBB->getParent();
711 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
712 if (DS.dominates(NewBBSucc, I))
713 DS.addDominator(I, NewBB);
716 // Update immediate dominator information if we have it...
717 BasicBlock *NewBBIDom = 0;
718 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
719 // To find the immediate dominator of the new exit node, we trace up the
720 // immediate dominators of a predecessor until we find a basic block that
721 // dominates the exit block.
723 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
724 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
725 assert(Dom != 0 && "No shared dominator found???");
729 // Set the immediate dominator now...
730 ID->addNewBlock(NewBB, Dom);
731 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
733 // If NewBB strictly dominates other blocks, we need to update their idom's
734 // now. The only block that need adjustment is the NewBBSucc block, whose
735 // idom should currently be set to PredBlocks[0].
736 if (NewBBDominatesNewBBSucc)
737 ID->setImmediateDominator(NewBBSucc, NewBB);
740 // Update DominatorTree information if it is active.
741 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
742 // If we don't have ImmediateDominator info around, calculate the idom as
744 DominatorTree::Node *NewBBIDomNode;
746 NewBBIDomNode = DT->getNode(NewBBIDom);
748 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
749 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
750 NewBBIDomNode = NewBBIDomNode->getIDom();
751 assert(NewBBIDomNode && "No shared dominator found??");
755 // Create the new dominator tree node... and set the idom of NewBB.
756 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
758 // If NewBB strictly dominates other blocks, then it is now the immediate
759 // dominator of NewBBSucc. Update the dominator tree as appropriate.
760 if (NewBBDominatesNewBBSucc) {
761 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
762 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
766 // Update dominance frontier information...
767 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
768 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
769 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
771 if (NewBBDominatesNewBBSucc) {
772 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
773 if (DFI != DF->end()) {
774 DominanceFrontier::DomSetType Set = DFI->second;
775 // Filter out stuff in Set that we do not dominate a predecessor of.
776 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
777 E = Set.end(); SetI != E;) {
778 bool DominatesPred = false;
779 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
781 if (DS.dominates(NewBB, *PI))
782 DominatesPred = true;
789 DF->addBasicBlock(NewBB, Set);
793 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
794 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
795 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
796 DominanceFrontier::DomSetType NewDFSet;
797 NewDFSet.insert(NewBBSucc);
798 DF->addBasicBlock(NewBB, NewDFSet);
801 // Now we must loop over all of the dominance frontiers in the function,
802 // replacing occurrences of NewBBSucc with NewBB in some cases. All
803 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
804 // their dominance frontier must be updated to contain NewBB instead.
806 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
807 BasicBlock *Pred = PredBlocks[i];
808 // Get all of the dominators of the predecessor...
809 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
810 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
811 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
812 BasicBlock *PredDom = *PDI;
814 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
815 // dominate NewBBSucc but did dominate a predecessor of it. Now we
816 // change this entry to include NewBB in the DF instead of NewBBSucc.
817 DominanceFrontier::iterator DFI = DF->find(PredDom);
818 assert(DFI != DF->end() && "No dominance frontier for node?");
819 if (DFI->second.count(NewBBSucc)) {
820 // If NewBBSucc should not stay in our dominator frontier, remove it.
821 // We remove it unless there is a predecessor of NewBBSucc that we
822 // dominate, but we don't strictly dominate NewBBSucc.
823 bool ShouldRemove = true;
824 if (PredDom == NewBBSucc || !DS.dominates(PredDom, NewBBSucc)) {
825 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
826 // Check to see if it dominates any predecessors of NewBBSucc.
827 for (pred_iterator PI = pred_begin(NewBBSucc),
828 E = pred_end(NewBBSucc); PI != E; ++PI)
829 if (DS.dominates(PredDom, *PI)) {
830 ShouldRemove = false;
836 DF->removeFromFrontier(DFI, NewBBSucc);
837 DF->addToFrontier(DFI, NewBB);