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 #define DEBUG_TYPE "loopsimplify"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Constant.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/Function.h"
40 #include "llvm/Type.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/Analysis/Dominators.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Support/CFG.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/ADT/SetOperations.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/DepthFirstIterator.h"
52 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
53 STATISTIC(NumNested , "Number of nested loops split out");
56 struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass {
57 // AA - If we have an alias analysis object to update, this is it, otherwise
62 virtual bool runOnFunction(Function &F);
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 // We need loop information to identify the loops...
66 AU.addRequired<LoopInfo>();
67 AU.addRequired<DominatorTree>();
68 AU.addRequired<ETForest>();
70 AU.addPreserved<LoopInfo>();
71 AU.addPreserved<ETForest>();
72 AU.addPreserved<DominatorTree>();
73 AU.addPreserved<DominanceFrontier>();
74 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
77 bool ProcessLoop(Loop *L);
78 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
79 const std::vector<BasicBlock*> &Preds);
80 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
81 void InsertPreheaderForLoop(Loop *L);
82 Loop *SeparateNestedLoop(Loop *L);
83 void InsertUniqueBackedgeBlock(Loop *L);
84 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
85 std::vector<BasicBlock*> &SplitPreds,
88 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
89 std::vector<BasicBlock*> &PredBlocks);
92 RegisterPass<LoopSimplify>
93 X("loopsimplify", "Canonicalize natural loops", true);
96 // Publically exposed interface to pass...
97 const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
98 FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
100 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
101 /// it in any convenient order) inserting preheaders...
103 bool LoopSimplify::runOnFunction(Function &F) {
104 bool Changed = false;
105 LI = &getAnalysis<LoopInfo>();
106 AA = getAnalysisToUpdate<AliasAnalysis>();
108 // Check to see that no blocks (other than the header) in loops have
109 // predecessors that are not in loops. This is not valid for natural loops,
110 // but can occur if the blocks are unreachable. Since they are unreachable we
111 // can just shamelessly destroy their terminators to make them not branch into
113 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
114 // This case can only occur for unreachable blocks. Blocks that are
115 // unreachable can't be in loops, so filter those blocks out.
116 if (LI->getLoopFor(BB)) continue;
118 bool BlockUnreachable = false;
119 TerminatorInst *TI = BB->getTerminator();
121 // Check to see if any successors of this block are non-loop-header loops
122 // that are not the header.
123 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
124 // If this successor is not in a loop, BB is clearly ok.
125 Loop *L = LI->getLoopFor(TI->getSuccessor(i));
128 // If the succ is the loop header, and if L is a top-level loop, then this
129 // is an entrance into a loop through the header, which is also ok.
130 if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
133 // Otherwise, this is an entrance into a loop from some place invalid.
134 // Either the loop structure is invalid and this is not a natural loop (in
135 // which case the compiler is buggy somewhere else) or BB is unreachable.
136 BlockUnreachable = true;
140 // If this block is ok, check the next one.
141 if (!BlockUnreachable) continue;
143 // Otherwise, this block is dead. To clean up the CFG and to allow later
144 // loop transformations to ignore this case, we delete the edges into the
145 // loop by replacing the terminator.
147 // Remove PHI entries from the successors.
148 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
149 TI->getSuccessor(i)->removePredecessor(BB);
151 // Add a new unreachable instruction.
152 new UnreachableInst(TI);
154 // Delete the dead terminator.
155 if (AA) AA->deleteValue(&BB->back());
156 BB->getInstList().pop_back();
160 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
161 Changed |= ProcessLoop(*I);
166 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
167 /// all loops have preheaders.
169 bool LoopSimplify::ProcessLoop(Loop *L) {
170 bool Changed = false;
173 // Canonicalize inner loops before outer loops. Inner loop canonicalization
174 // can provide work for the outer loop to canonicalize.
175 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
176 Changed |= ProcessLoop(*I);
178 assert(L->getBlocks()[0] == L->getHeader() &&
179 "Header isn't first block in loop?");
181 // Does the loop already have a preheader? If so, don't insert one.
182 if (L->getLoopPreheader() == 0) {
183 InsertPreheaderForLoop(L);
188 // Next, check to make sure that all exit nodes of the loop only have
189 // predecessors that are inside of the loop. This check guarantees that the
190 // loop preheader/header will dominate the exit blocks. If the exit block has
191 // predecessors from outside of the loop, split the edge now.
192 std::vector<BasicBlock*> ExitBlocks;
193 L->getExitBlocks(ExitBlocks);
195 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
196 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
197 E = ExitBlockSet.end(); I != E; ++I) {
198 BasicBlock *ExitBlock = *I;
199 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
201 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
203 if (!L->contains(*PI)) {
204 RewriteLoopExitBlock(L, ExitBlock);
211 // If the header has more than two predecessors at this point (from the
212 // preheader and from multiple backedges), we must adjust the loop.
213 unsigned NumBackedges = L->getNumBackEdges();
214 if (NumBackedges != 1) {
215 // If this is really a nested loop, rip it out into a child loop. Don't do
216 // this for loops with a giant number of backedges, just factor them into a
217 // common backedge instead.
218 if (NumBackedges < 8) {
219 if (Loop *NL = SeparateNestedLoop(L)) {
221 // This is a big restructuring change, reprocess the whole loop.
224 // GCC doesn't tail recursion eliminate this.
229 // If we either couldn't, or didn't want to, identify nesting of the loops,
230 // insert a new block that all backedges target, then make it jump to the
232 InsertUniqueBackedgeBlock(L);
237 // Scan over the PHI nodes in the loop header. Since they now have only two
238 // incoming values (the loop is canonicalized), we may have simplified the PHI
239 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
241 for (BasicBlock::iterator I = L->getHeader()->begin();
242 (PN = dyn_cast<PHINode>(I++)); )
243 if (Value *V = PN->hasConstantValue()) {
244 PN->replaceAllUsesWith(V);
245 PN->eraseFromParent();
251 /// SplitBlockPredecessors - Split the specified block into two blocks. We want
252 /// to move the predecessors specified in the Preds list to point to the new
253 /// block, leaving the remaining predecessors pointing to BB. This method
254 /// updates the SSA PHINode's, but no other analyses.
256 BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
258 const std::vector<BasicBlock*> &Preds) {
260 // Create new basic block, insert right before the original block...
261 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
263 // The preheader first gets an unconditional branch to the loop header...
264 BranchInst *BI = new BranchInst(BB, NewBB);
266 // For every PHI node in the block, insert a PHI node into NewBB where the
267 // incoming values from the out of loop edges are moved to NewBB. We have two
268 // possible cases here. If the loop is dead, we just insert dummy entries
269 // into the PHI nodes for the new edge. If the loop is not dead, we move the
270 // incoming edges in BB into new PHI nodes in NewBB.
272 if (!Preds.empty()) { // Is the loop not obviously dead?
273 // Check to see if the values being merged into the new block need PHI
274 // nodes. If so, insert them.
275 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
276 PHINode *PN = cast<PHINode>(I);
279 // Check to see if all of the values coming in are the same. If so, we
280 // don't need to create a new PHI node.
281 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
282 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
283 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
288 // If the values coming into the block are not the same, we need a PHI.
290 // Create the new PHI node, insert it into NewBB at the end of the block
291 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
292 if (AA) AA->copyValue(PN, NewPHI);
294 // Move all of the edges from blocks outside the loop to the new PHI
295 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
296 Value *V = PN->removeIncomingValue(Preds[i], false);
297 NewPHI->addIncoming(V, Preds[i]);
301 // Remove all of the edges coming into the PHI nodes from outside of the
303 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
304 PN->removeIncomingValue(Preds[i], false);
307 // Add an incoming value to the PHI node in the loop for the preheader
309 PN->addIncoming(InVal, NewBB);
311 // Can we eliminate this phi node now?
312 if (Value *V = PN->hasConstantValue(true)) {
313 Instruction *I = dyn_cast<Instruction>(V);
314 // If I is in NewBB, the ETForest call will fail, because NewBB isn't
315 // registered in ETForest yet. Handle this case explicitly.
316 if (!I || (I->getParent() != NewBB &&
317 getAnalysis<ETForest>().dominates(I, PN))) {
318 PN->replaceAllUsesWith(V);
319 if (AA) AA->deleteValue(PN);
320 BB->getInstList().erase(PN);
325 // Now that the PHI nodes are updated, actually move the edges from
326 // Preds to point to NewBB instead of BB.
328 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
329 TerminatorInst *TI = Preds[i]->getTerminator();
330 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
331 if (TI->getSuccessor(s) == BB)
332 TI->setSuccessor(s, NewBB);
335 } else { // Otherwise the loop is dead...
336 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
337 PHINode *PN = cast<PHINode>(I);
338 // Insert dummy values as the incoming value...
339 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
345 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
346 /// preheader, this method is called to insert one. This method has two phases:
347 /// preheader insertion and analysis updating.
349 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
350 BasicBlock *Header = L->getHeader();
352 // Compute the set of predecessors of the loop that are not in the loop.
353 std::vector<BasicBlock*> OutsideBlocks;
354 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
356 if (!L->contains(*PI)) // Coming in from outside the loop?
357 OutsideBlocks.push_back(*PI); // Keep track of it...
359 // Split out the loop pre-header.
361 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
364 //===--------------------------------------------------------------------===//
365 // Update analysis results now that we have performed the transformation
368 // We know that we have loop information to update... update it now.
369 if (Loop *Parent = L->getParentLoop())
370 Parent->addBasicBlockToLoop(NewBB, *LI);
372 UpdateDomInfoForRevectoredPreds(NewBB, OutsideBlocks);
374 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
375 // code layout too horribly.
376 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
379 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
380 /// blocks. This method is used to split exit blocks that have predecessors
381 /// outside of the loop.
382 BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
383 std::vector<BasicBlock*> LoopBlocks;
384 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
386 LoopBlocks.push_back(*I);
388 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
389 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
391 // Update Loop Information - we know that the new block will be in whichever
392 // loop the Exit block is in. Note that it may not be in that immediate loop,
393 // if the successor is some other loop header. In that case, we continue
394 // walking up the loop tree to find a loop that contains both the successor
395 // block and the predecessor block.
396 Loop *SuccLoop = LI->getLoopFor(Exit);
397 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
398 SuccLoop = SuccLoop->getParentLoop();
400 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
402 // Update dominator information (set, immdom, domtree, and domfrontier)
403 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
407 /// AddBlockAndPredsToSet - Add the specified block, and all of its
408 /// predecessors, to the specified set, if it's not already in there. Stop
409 /// predecessor traversal when we reach StopBlock.
410 static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
411 std::set<BasicBlock*> &Blocks) {
412 if (!Blocks.insert(BB).second) return; // already processed.
413 if (BB == StopBlock) return; // Stop here!
415 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
416 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
419 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
420 /// PHI node that tells us how to partition the loops.
421 static PHINode *FindPHIToPartitionLoops(Loop *L, ETForest *EF,
423 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
424 PHINode *PN = cast<PHINode>(I);
426 if (Value *V = PN->hasConstantValue())
427 if (!isa<Instruction>(V) || EF->dominates(cast<Instruction>(V), PN)) {
428 // This is a degenerate PHI already, don't modify it!
429 PN->replaceAllUsesWith(V);
430 if (AA) AA->deleteValue(PN);
431 PN->eraseFromParent();
435 // Scan this PHI node looking for a use of the PHI node by itself.
436 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
437 if (PN->getIncomingValue(i) == PN &&
438 L->contains(PN->getIncomingBlock(i)))
439 // We found something tasty to remove.
445 // PlaceSplitBlockCarefully - If the block isn't already, move the new block to
446 // right after some 'outside block' block. This prevents the preheader from
447 // being placed inside the loop body, e.g. when the loop hasn't been rotated.
448 void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
449 std::vector<BasicBlock*>&SplitPreds,
451 // Check to see if NewBB is already well placed.
452 Function::iterator BBI = NewBB; --BBI;
453 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
454 if (&*BBI == SplitPreds[i])
458 // If it isn't already after an outside block, move it after one. This is
459 // always good as it makes the uncond branch from the outside block into a
462 // Figure out *which* outside block to put this after. Prefer an outside
463 // block that neighbors a BB actually in the loop.
464 BasicBlock *FoundBB = 0;
465 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
466 Function::iterator BBI = SplitPreds[i];
467 if (++BBI != NewBB->getParent()->end() &&
469 FoundBB = SplitPreds[i];
474 // If our heuristic for a *good* bb to place this after doesn't find
475 // anything, just pick something. It's likely better than leaving it within
478 FoundBB = SplitPreds[0];
479 NewBB->moveAfter(FoundBB);
483 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
484 /// them out into a nested loop. This is important for code that looks like
489 /// br cond, Loop, Next
491 /// br cond2, Loop, Out
493 /// To identify this common case, we look at the PHI nodes in the header of the
494 /// loop. PHI nodes with unchanging values on one backedge correspond to values
495 /// that change in the "outer" loop, but not in the "inner" loop.
497 /// If we are able to separate out a loop, return the new outer loop that was
500 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
501 ETForest *EF = getAnalysisToUpdate<ETForest>();
502 PHINode *PN = FindPHIToPartitionLoops(L, EF, AA);
503 if (PN == 0) return 0; // No known way to partition.
505 // Pull out all predecessors that have varying values in the loop. This
506 // handles the case when a PHI node has multiple instances of itself as
508 std::vector<BasicBlock*> OuterLoopPreds;
509 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
510 if (PN->getIncomingValue(i) != PN ||
511 !L->contains(PN->getIncomingBlock(i)))
512 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
514 BasicBlock *Header = L->getHeader();
515 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
517 // Update dominator information (set, immdom, domtree, and domfrontier)
518 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
520 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
521 // code layout too horribly.
522 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
524 // Create the new outer loop.
525 Loop *NewOuter = new Loop();
527 // Change the parent loop to use the outer loop as its child now.
528 if (Loop *Parent = L->getParentLoop())
529 Parent->replaceChildLoopWith(L, NewOuter);
531 LI->changeTopLevelLoop(L, NewOuter);
533 // This block is going to be our new header block: add it to this loop and all
535 NewOuter->addBasicBlockToLoop(NewBB, *LI);
537 // L is now a subloop of our outer loop.
538 NewOuter->addChildLoop(L);
540 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
541 NewOuter->addBlockEntry(L->getBlocks()[i]);
543 // Determine which blocks should stay in L and which should be moved out to
544 // the Outer loop now.
545 std::set<BasicBlock*> BlocksInL;
546 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
547 if (EF->dominates(Header, *PI))
548 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
551 // Scan all of the loop children of L, moving them to OuterLoop if they are
552 // not part of the inner loop.
553 for (Loop::iterator I = L->begin(); I != L->end(); )
554 if (BlocksInL.count((*I)->getHeader()))
555 ++I; // Loop remains in L
557 NewOuter->addChildLoop(L->removeChildLoop(I));
559 // Now that we know which blocks are in L and which need to be moved to
560 // OuterLoop, move any blocks that need it.
561 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
562 BasicBlock *BB = L->getBlocks()[i];
563 if (!BlocksInL.count(BB)) {
564 // Move this block to the parent, updating the exit blocks sets
565 L->removeBlockFromLoop(BB);
567 LI->changeLoopFor(BB, NewOuter);
577 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
578 /// has more than one backedge in it. If this occurs, revector all of these
579 /// backedges to target a new basic block and have that block branch to the loop
580 /// header. This ensures that loops have exactly one backedge.
582 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
583 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
585 // Get information about the loop
586 BasicBlock *Preheader = L->getLoopPreheader();
587 BasicBlock *Header = L->getHeader();
588 Function *F = Header->getParent();
590 // Figure out which basic blocks contain back-edges to the loop header.
591 std::vector<BasicBlock*> BackedgeBlocks;
592 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
593 if (*I != Preheader) BackedgeBlocks.push_back(*I);
595 // Create and insert the new backedge block...
596 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
597 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
599 // Move the new backedge block to right after the last backedge block.
600 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
601 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
603 // Now that the block has been inserted into the function, create PHI nodes in
604 // the backedge block which correspond to any PHI nodes in the header block.
605 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
606 PHINode *PN = cast<PHINode>(I);
607 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
609 NewPN->reserveOperandSpace(BackedgeBlocks.size());
610 if (AA) AA->copyValue(PN, NewPN);
612 // Loop over the PHI node, moving all entries except the one for the
613 // preheader over to the new PHI node.
614 unsigned PreheaderIdx = ~0U;
615 bool HasUniqueIncomingValue = true;
616 Value *UniqueValue = 0;
617 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
618 BasicBlock *IBB = PN->getIncomingBlock(i);
619 Value *IV = PN->getIncomingValue(i);
620 if (IBB == Preheader) {
623 NewPN->addIncoming(IV, IBB);
624 if (HasUniqueIncomingValue) {
625 if (UniqueValue == 0)
627 else if (UniqueValue != IV)
628 HasUniqueIncomingValue = false;
633 // Delete all of the incoming values from the old PN except the preheader's
634 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
635 if (PreheaderIdx != 0) {
636 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
637 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
639 // Nuke all entries except the zero'th.
640 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
641 PN->removeIncomingValue(e-i, false);
643 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
644 PN->addIncoming(NewPN, BEBlock);
646 // As an optimization, if all incoming values in the new PhiNode (which is a
647 // subset of the incoming values of the old PHI node) have the same value,
648 // eliminate the PHI Node.
649 if (HasUniqueIncomingValue) {
650 NewPN->replaceAllUsesWith(UniqueValue);
651 if (AA) AA->deleteValue(NewPN);
652 BEBlock->getInstList().erase(NewPN);
656 // Now that all of the PHI nodes have been inserted and adjusted, modify the
657 // backedge blocks to just to the BEBlock instead of the header.
658 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
659 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
660 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
661 if (TI->getSuccessor(Op) == Header)
662 TI->setSuccessor(Op, BEBlock);
665 //===--- Update all analyses which we must preserve now -----------------===//
667 // Update Loop Information - we know that this block is now in the current
668 // loop and all parent loops.
669 L->addBasicBlockToLoop(BEBlock, *LI);
671 // Update dominator information (set, immdom, domtree, and domfrontier)
672 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
675 // Returns true if BasicBlock A dominates at least one block in vector B
676 // Helper function for UpdateDomInfoForRevectoredPreds
677 static bool BlockDominatesAny(BasicBlock* A, const std::vector<BasicBlock*>& B,
679 for (std::vector<BasicBlock*>::const_iterator BI = B.begin(), BE = B.end();
681 if (ETF.dominates(A, *BI))
687 /// UpdateDomInfoForRevectoredPreds - This method is used to update the four
688 /// different kinds of dominator information (immediate dominators,
689 /// dominator trees, et-forest and dominance frontiers) after a new block has
690 /// been added to the CFG.
692 /// This only supports the case when an existing block (known as "NewBBSucc"),
693 /// had some of its predecessors factored into a new basic block. This
694 /// transformation inserts a new basic block ("NewBB"), with a single
695 /// unconditional branch to NewBBSucc, and moves some predecessors of
696 /// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
697 /// PredBlocks, even though they are the same as
698 /// pred_begin(NewBB)/pred_end(NewBB).
700 void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
701 std::vector<BasicBlock*> &PredBlocks) {
702 assert(!PredBlocks.empty() && "No predblocks??");
703 assert(succ_begin(NewBB) != succ_end(NewBB) &&
704 ++succ_begin(NewBB) == succ_end(NewBB) &&
705 "NewBB should have a single successor!");
706 BasicBlock *NewBBSucc = *succ_begin(NewBB);
707 ETForest& ETF = getAnalysis<ETForest>();
709 // The newly inserted basic block will dominate existing basic blocks iff the
710 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
711 // the non-pred blocks, then they all must be the same block!
713 bool NewBBDominatesNewBBSucc = true;
715 BasicBlock *OnePred = PredBlocks[0];
716 unsigned i = 1, e = PredBlocks.size();
717 for (i = 1; !ETF.isReachableFromEntry(OnePred); ++i) {
718 assert(i != e && "Didn't find reachable pred?");
719 OnePred = PredBlocks[i];
723 if (PredBlocks[i] != OnePred && ETF.isReachableFromEntry(OnePred)){
724 NewBBDominatesNewBBSucc = false;
728 if (NewBBDominatesNewBBSucc)
729 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
731 if (*PI != NewBB && !ETF.dominates(NewBBSucc, *PI)) {
732 NewBBDominatesNewBBSucc = false;
737 // The other scenario where the new block can dominate its successors are when
738 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
740 if (!NewBBDominatesNewBBSucc) {
741 NewBBDominatesNewBBSucc = true;
742 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
744 if (*PI != NewBB && !ETF.dominates(NewBBSucc, *PI)) {
745 NewBBDominatesNewBBSucc = false;
750 BasicBlock *NewBBIDom = 0;
752 // Update DominatorTree information if it is active.
753 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
754 // If we don't have ImmediateDominator info around, calculate the idom as
758 for (i = 0; i < PredBlocks.size(); ++i)
759 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i])) {
760 NewBBIDom = PredBlocks[i];
763 assert(i != PredBlocks.size() && "No reachable preds?");
764 for (i = i + 1; i < PredBlocks.size(); ++i) {
765 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i]))
766 NewBBIDom = ETF.nearestCommonDominator(NewBBIDom, PredBlocks[i]);
768 assert(NewBBIDom && "No immediate dominator found??");
770 DominatorTree::Node *NewBBIDomNode = DT->getNode(NewBBIDom);
772 // Create the new dominator tree node... and set the idom of NewBB.
773 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
775 // If NewBB strictly dominates other blocks, then it is now the immediate
776 // dominator of NewBBSucc. Update the dominator tree as appropriate.
777 if (NewBBDominatesNewBBSucc) {
778 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
779 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
783 // Update ET-Forest information if it is active.
784 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
785 EF->addNewBlock(NewBB, NewBBIDom);
786 if (NewBBDominatesNewBBSucc)
787 EF->setImmediateDominator(NewBBSucc, NewBB);
790 // Update dominance frontier information...
791 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
792 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
793 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
795 if (NewBBDominatesNewBBSucc) {
796 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
797 if (DFI != DF->end()) {
798 DominanceFrontier::DomSetType Set = DFI->second;
799 // Filter out stuff in Set that we do not dominate a predecessor of.
800 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
801 E = Set.end(); SetI != E;) {
802 bool DominatesPred = false;
803 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
805 if (ETF.dominates(NewBB, *PI))
806 DominatesPred = true;
813 DF->addBasicBlock(NewBB, Set);
817 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
818 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
819 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
820 DominanceFrontier::DomSetType NewDFSet;
821 NewDFSet.insert(NewBBSucc);
822 DF->addBasicBlock(NewBB, NewDFSet);
825 // Now we must loop over all of the dominance frontiers in the function,
826 // replacing occurrences of NewBBSucc with NewBB in some cases. All
827 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
828 // their dominance frontier must be updated to contain NewBB instead.
830 for (Function::iterator FI = NewBB->getParent()->begin(),
831 FE = NewBB->getParent()->end(); FI != FE; ++FI) {
832 DominanceFrontier::iterator DFI = DF->find(FI);
833 if (DFI == DF->end()) continue; // unreachable block.
835 // Only consider dominators of NewBBSucc
836 if (!DFI->second.count(NewBBSucc)) continue;
838 if (BlockDominatesAny(FI, PredBlocks, ETF)) {
839 // If NewBBSucc should not stay in our dominator frontier, remove it.
840 // We remove it unless there is a predecessor of NewBBSucc that we
841 // dominate, but we don't strictly dominate NewBBSucc.
842 bool ShouldRemove = true;
843 if ((BasicBlock*)FI == NewBBSucc || !ETF.dominates(FI, NewBBSucc)) {
844 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
845 // Check to see if it dominates any predecessors of NewBBSucc.
846 for (pred_iterator PI = pred_begin(NewBBSucc),
847 E = pred_end(NewBBSucc); PI != E; ++PI)
848 if (ETF.dominates(FI, *PI)) {
849 ShouldRemove = false;
854 DF->removeFromFrontier(DFI, NewBBSucc);
855 DF->addToFrontier(DFI, NewBB);