1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
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 transforms loops that contain branches on loop-invariant conditions
11 // to have multiple loops. For example, it turns the left into the right code:
20 // This can increase the size of the code exponentially (doubling it every time
21 // a loop is unswitched) so we only unswitch if the resultant code will be
22 // smaller than a threshold.
24 // This pass expects LICM to be run before it to hoist invariant conditions out
25 // of the loop, to make the unswitching opportunity obvious.
27 //===----------------------------------------------------------------------===//
29 #define DEBUG_TYPE "loop-unswitch"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Constants.h"
32 #include "llvm/DerivedTypes.h"
33 #include "llvm/Function.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Analysis/ConstantFolding.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Transforms/Utils/Cloning.h"
39 #include "llvm/Transforms/Utils/Local.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/PostOrderIterator.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
51 STATISTIC(NumBranches, "Number of branches unswitched");
52 STATISTIC(NumSwitches, "Number of switches unswitched");
53 STATISTIC(NumSelects , "Number of selects unswitched");
54 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
55 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
59 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
60 cl::init(10), cl::Hidden);
62 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
63 LoopInfo *LI; // Loop information
66 // LoopProcessWorklist - Used to check if second loop needs processing
67 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
68 std::vector<Loop*> LoopProcessWorklist;
69 SmallPtrSet<Value *,8> UnswitchedVals;
73 static char ID; // Pass ID, replacement for typeid
74 LoopUnswitch(bool Os = false) :
75 LoopPass((intptr_t)&ID), OptimizeForSize(Os) {}
77 bool runOnLoop(Loop *L, LPPassManager &LPM);
79 /// This transformation requires natural loop information & requires that
80 /// loop preheaders be inserted into the CFG...
82 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83 AU.addRequiredID(LoopSimplifyID);
84 AU.addPreservedID(LoopSimplifyID);
85 AU.addRequired<LoopInfo>();
86 AU.addPreserved<LoopInfo>();
87 AU.addRequiredID(LCSSAID);
88 AU.addPreservedID(LCSSAID);
92 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
94 void RemoveLoopFromWorklist(Loop *L) {
95 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
96 LoopProcessWorklist.end(), L);
97 if (I != LoopProcessWorklist.end())
98 LoopProcessWorklist.erase(I);
101 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
102 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
103 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
104 BasicBlock *ExitBlock);
105 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
106 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
107 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
109 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
110 Constant *Val, bool isEqual);
112 void SimplifyCode(std::vector<Instruction*> &Worklist);
113 void RemoveBlockIfDead(BasicBlock *BB,
114 std::vector<Instruction*> &Worklist);
115 void RemoveLoopFromHierarchy(Loop *L);
117 char LoopUnswitch::ID = 0;
118 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
121 LoopPass *llvm::createLoopUnswitchPass(bool Os) {
122 return new LoopUnswitch(Os);
125 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
126 /// invariant in the loop, or has an invariant piece, return the invariant.
127 /// Otherwise, return null.
128 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
129 // Constants should be folded, not unswitched on!
130 if (isa<Constant>(Cond)) return false;
132 // If cond is not in loop then it is not suitable.
133 if (Instruction *I = dyn_cast<Instruction>(Cond))
134 if (!L->contains(I->getParent()))
136 if (isa<Argument>(Cond))
139 // TODO: Handle: br (VARIANT|INVARIANT).
140 // TODO: Hoist simple expressions out of loops.
141 if (L->isLoopInvariant(Cond)) return Cond;
143 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
144 if (BO->getOpcode() == Instruction::And ||
145 BO->getOpcode() == Instruction::Or) {
146 // If either the left or right side is invariant, we can unswitch on this,
147 // which will cause the branch to go away in one loop and the condition to
148 // simplify in the other one.
149 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
151 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
158 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
159 assert(L->isLCSSAForm());
160 LI = &getAnalysis<LoopInfo>();
162 bool Changed = false;
164 // Loop over all of the basic blocks in the loop. If we find an interior
165 // block that is branching on a loop-invariant condition, we can unswitch this
167 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
169 TerminatorInst *TI = (*I)->getTerminator();
170 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
171 // If this isn't branching on an invariant condition, we can't unswitch
173 if (BI->isConditional()) {
174 // See if this, or some part of it, is loop invariant. If so, we can
175 // unswitch on it if we desire.
176 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
177 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
183 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
184 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
185 if (LoopCond && SI->getNumCases() > 1) {
186 // Find a value to unswitch on:
187 // FIXME: this should chose the most expensive case!
188 Constant *UnswitchVal = SI->getCaseValue(1);
189 // Do not process same value again and again.
190 if (!UnswitchedVals.insert(UnswitchVal))
193 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
200 // Scan the instructions to check for unswitchable values.
201 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
203 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
204 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
205 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
213 assert(L->isLCSSAForm());
218 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
219 /// 1. Exit the loop with no side effects.
220 /// 2. Branch to the latch block with no side-effects.
222 /// If these conditions are true, we return true and set ExitBB to the block we
225 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
227 std::set<BasicBlock*> &Visited) {
228 if (!Visited.insert(BB).second) {
229 // Already visited and Ok, end of recursion.
231 } else if (!L->contains(BB)) {
232 // Otherwise, this is a loop exit, this is fine so long as this is the
234 if (ExitBB != 0) return false;
239 // Otherwise, this is an unvisited intra-loop node. Check all successors.
240 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
241 // Check to see if the successor is a trivial loop exit.
242 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
246 // Okay, everything after this looks good, check to make sure that this block
247 // doesn't include any side effects.
248 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
249 if (I->mayWriteToMemory())
255 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
256 /// leads to an exit from the specified loop, and has no side-effects in the
257 /// process. If so, return the block that is exited to, otherwise return null.
258 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
259 std::set<BasicBlock*> Visited;
260 Visited.insert(L->getHeader()); // Branches to header are ok.
261 BasicBlock *ExitBB = 0;
262 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
267 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
268 /// trivial: that is, that the condition controls whether or not the loop does
269 /// anything at all. If this is a trivial condition, unswitching produces no
270 /// code duplications (equivalently, it produces a simpler loop and a new empty
271 /// loop, which gets deleted).
273 /// If this is a trivial condition, return true, otherwise return false. When
274 /// returning true, this sets Cond and Val to the condition that controls the
275 /// trivial condition: when Cond dynamically equals Val, the loop is known to
276 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
279 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
280 BasicBlock **LoopExit = 0) {
281 BasicBlock *Header = L->getHeader();
282 TerminatorInst *HeaderTerm = Header->getTerminator();
284 BasicBlock *LoopExitBB = 0;
285 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
286 // If the header block doesn't end with a conditional branch on Cond, we
288 if (!BI->isConditional() || BI->getCondition() != Cond)
291 // Check to see if a successor of the branch is guaranteed to go to the
292 // latch block or exit through a one exit block without having any
293 // side-effects. If so, determine the value of Cond that causes it to do
295 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
296 if (Val) *Val = ConstantInt::getTrue();
297 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
298 if (Val) *Val = ConstantInt::getFalse();
300 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
301 // If this isn't a switch on Cond, we can't handle it.
302 if (SI->getCondition() != Cond) return false;
304 // Check to see if a successor of the switch is guaranteed to go to the
305 // latch block or exit through a one exit block without having any
306 // side-effects. If so, determine the value of Cond that causes it to do
307 // this. Note that we can't trivially unswitch on the default case.
308 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
309 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
310 // Okay, we found a trivial case, remember the value that is trivial.
311 if (Val) *Val = SI->getCaseValue(i);
316 // If we didn't find a single unique LoopExit block, or if the loop exit block
317 // contains phi nodes, this isn't trivial.
318 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
319 return false; // Can't handle this.
321 if (LoopExit) *LoopExit = LoopExitBB;
323 // We already know that nothing uses any scalar values defined inside of this
324 // loop. As such, we just have to check to see if this loop will execute any
325 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
326 // part of the loop that the code *would* execute. We already checked the
327 // tail, check the header now.
328 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
329 if (I->mayWriteToMemory())
334 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
335 /// we choose to unswitch the specified loop on the specified value.
337 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
338 // If the condition is trivial, always unswitch. There is no code growth for
340 if (IsTrivialUnswitchCondition(L, LIC))
343 // FIXME: This is really overly conservative. However, more liberal
344 // estimations have thus far resulted in excessive unswitching, which is bad
345 // both in compile time and in code size. This should be replaced once
346 // someone figures out how a good estimation.
347 return L->getBlocks().size();
350 // FIXME: this is brain dead. It should take into consideration code
352 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
355 // Do not include empty blocks in the cost calculation. This happen due to
356 // loop canonicalization and will be removed.
357 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
360 // Count basic blocks.
367 /// UnswitchIfProfitable - We have found that we can unswitch L when
368 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
369 /// unswitch the loop, reprocess the pieces, then return true.
370 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
371 // Check to see if it would be profitable to unswitch this loop.
372 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
374 // Do not do non-trivial unswitch while optimizing for size.
375 if (Cost && OptimizeForSize)
378 if (Cost > Threshold) {
379 // FIXME: this should estimate growth by the amount of code shared by the
380 // resultant unswitched loops.
382 DOUT << "NOT unswitching loop %"
383 << L->getHeader()->getName() << ", cost too high: "
384 << L->getBlocks().size() << "\n";
388 // If this is a trivial condition to unswitch (which results in no code
389 // duplication), do it now.
391 BasicBlock *ExitBlock;
392 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
393 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
395 UnswitchNontrivialCondition(LoopCond, Val, L);
401 /// SplitBlock - Split the specified block at the specified instruction - every
402 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
403 /// to a new block. The two blocks are joined by an unconditional branch and
404 /// the loop info is updated.
406 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
407 BasicBlock::iterator SplitIt = SplitPt;
408 while (isa<PHINode>(SplitIt))
410 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
412 // The new block lives in whichever loop the old one did.
413 if (Loop *L = LI->getLoopFor(Old))
414 L->addBasicBlockToLoop(New, *LI);
420 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
421 TerminatorInst *LatchTerm = BB->getTerminator();
422 unsigned SuccNum = 0;
423 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
424 assert(i != e && "Didn't find edge?");
425 if (LatchTerm->getSuccessor(i) == Succ) {
431 // If this is a critical edge, let SplitCriticalEdge do it.
432 Loop *OrigDestBBL = LI->getLoopFor(BB->getTerminator()->getSuccessor(SuccNum));
433 if (SplitCriticalEdge(BB->getTerminator(), SuccNum)) {
434 BasicBlock *NewBB = LatchTerm->getSuccessor(SuccNum);
436 Loop *BBL = LI->getLoopFor(BB);
437 if (!BBL || !OrigDestBBL)
440 // If edge is inside a loop then NewBB is part of same loop.
441 if (BBL == OrigDestBBL)
442 BBL->addBasicBlockToLoop(NewBB, *LI);
443 // If edge is entering loop then NewBB is part of outer loop.
444 else if (BBL->contains(OrigDestBBL->getHeader()))
445 BBL->addBasicBlockToLoop(NewBB, *LI);
446 // If edge is from an inner loop to outer loop then NewBB is part
448 else if (OrigDestBBL->contains(BBL->getHeader()))
449 OrigDestBBL->addBasicBlockToLoop(NewBB, *LI);
450 // Else edge is connecting two loops and NewBB is part of their parent loop
451 else if (Loop *PL = OrigDestBBL->getParentLoop())
452 PL->addBasicBlockToLoop(NewBB, *LI);
457 // If the edge isn't critical, then BB has a single successor or Succ has a
458 // single pred. Split the block.
459 BasicBlock::iterator SplitPoint;
460 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
461 // If the successor only has a single pred, split the top of the successor
463 assert(SP == BB && "CFG broken");
464 return SplitBlock(Succ, Succ->begin());
466 // Otherwise, if BB has a single successor, split it at the bottom of the
468 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
469 "Should have a single succ!");
470 return SplitBlock(BB, BB->getTerminator());
476 // RemapInstruction - Convert the instruction operands from referencing the
477 // current values into those specified by ValueMap.
479 static inline void RemapInstruction(Instruction *I,
480 DenseMap<const Value *, Value*> &ValueMap) {
481 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
482 Value *Op = I->getOperand(op);
483 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
484 if (It != ValueMap.end()) Op = It->second;
485 I->setOperand(op, Op);
489 /// CloneLoop - Recursively clone the specified loop and all of its children,
490 /// mapping the blocks with the specified map.
491 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
492 LoopInfo *LI, LPPassManager *LPM) {
493 Loop *New = new Loop();
495 LPM->insertLoop(New, PL);
497 // Add all of the blocks in L to the new loop.
498 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
500 if (LI->getLoopFor(*I) == L)
501 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
503 // Add all of the subloops to the new loop.
504 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
505 CloneLoop(*I, New, VM, LI, LPM);
510 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
511 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
512 /// code immediately before InsertPt.
513 static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
514 BasicBlock *TrueDest,
515 BasicBlock *FalseDest,
516 Instruction *InsertPt) {
517 // Insert a conditional branch on LIC to the two preheaders. The original
518 // code is the true version and the new code is the false version.
519 Value *BranchVal = LIC;
520 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
521 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
522 else if (Val != ConstantInt::getTrue())
523 // We want to enter the new loop when the condition is true.
524 std::swap(TrueDest, FalseDest);
526 // Insert the new branch.
527 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
531 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
532 /// condition in it (a cond branch from its header block to its latch block,
533 /// where the path through the loop that doesn't execute its body has no
534 /// side-effects), unswitch it. This doesn't involve any code duplication, just
535 /// moving the conditional branch outside of the loop and updating loop info.
536 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
538 BasicBlock *ExitBlock) {
539 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
540 << L->getHeader()->getName() << " [" << L->getBlocks().size()
541 << " blocks] in Function " << L->getHeader()->getParent()->getName()
542 << " on cond: " << *Val << " == " << *Cond << "\n";
544 // First step, split the preheader, so that we know that there is a safe place
545 // to insert the conditional branch. We will change 'OrigPH' to have a
546 // conditional branch on Cond.
547 BasicBlock *OrigPH = L->getLoopPreheader();
548 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
550 // Now that we have a place to insert the conditional branch, create a place
551 // to branch to: this is the exit block out of the loop that we should
554 // Split this block now, so that the loop maintains its exit block, and so
555 // that the jump from the preheader can execute the contents of the exit block
556 // without actually branching to it (the exit block should be dominated by the
557 // loop header, not the preheader).
558 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
559 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
561 // Okay, now we have a position to branch from and a position to branch to,
562 // insert the new conditional branch.
563 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
564 OrigPH->getTerminator());
565 OrigPH->getTerminator()->eraseFromParent();
567 // We need to reprocess this loop, it could be unswitched again.
570 // Now that we know that the loop is never entered when this condition is a
571 // particular value, rewrite the loop with this info. We know that this will
572 // at least eliminate the old branch.
573 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
578 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
579 /// equal Val. Split it into loop versions and test the condition outside of
580 /// either loop. Return the loops created as Out1/Out2.
581 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
583 Function *F = L->getHeader()->getParent();
584 DOUT << "loop-unswitch: Unswitching loop %"
585 << L->getHeader()->getName() << " [" << L->getBlocks().size()
586 << " blocks] in Function " << F->getName()
587 << " when '" << *Val << "' == " << *LIC << "\n";
589 // LoopBlocks contains all of the basic blocks of the loop, including the
590 // preheader of the loop, the body of the loop, and the exit blocks of the
591 // loop, in that order.
592 std::vector<BasicBlock*> LoopBlocks;
594 // First step, split the preheader and exit blocks, and add these blocks to
595 // the LoopBlocks list.
596 BasicBlock *OrigPreheader = L->getLoopPreheader();
597 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
599 // We want the loop to come after the preheader, but before the exit blocks.
600 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
602 std::vector<BasicBlock*> ExitBlocks;
603 L->getUniqueExitBlocks(ExitBlocks);
605 // Split all of the edges from inside the loop to their exit blocks. Update
606 // the appropriate Phi nodes as we do so.
607 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
608 BasicBlock *ExitBlock = ExitBlocks[i];
609 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
611 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
612 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
613 BasicBlock* StartBlock = Preds[j];
614 BasicBlock* EndBlock;
615 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
616 EndBlock = MiddleBlock;
617 MiddleBlock = EndBlock->getSinglePredecessor();;
619 EndBlock = ExitBlock;
622 std::set<PHINode*> InsertedPHIs;
623 PHINode* OldLCSSA = 0;
624 for (BasicBlock::iterator I = EndBlock->begin();
625 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
626 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
627 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
628 OldLCSSA->getName() + ".us-lcssa",
629 MiddleBlock->getTerminator());
630 NewLCSSA->addIncoming(OldValue, StartBlock);
631 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
633 InsertedPHIs.insert(NewLCSSA);
636 BasicBlock::iterator InsertPt = EndBlock->begin();
637 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
638 for (BasicBlock::iterator I = MiddleBlock->begin();
639 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
641 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
642 OldLCSSA->getName() + ".us-lcssa",
644 OldLCSSA->replaceAllUsesWith(NewLCSSA);
645 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
650 // The exit blocks may have been changed due to edge splitting, recompute.
652 L->getUniqueExitBlocks(ExitBlocks);
654 // Add exit blocks to the loop blocks.
655 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
657 // Next step, clone all of the basic blocks that make up the loop (including
658 // the loop preheader and exit blocks), keeping track of the mapping between
659 // the instructions and blocks.
660 std::vector<BasicBlock*> NewBlocks;
661 NewBlocks.reserve(LoopBlocks.size());
662 DenseMap<const Value*, Value*> ValueMap;
663 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
664 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
665 NewBlocks.push_back(New);
666 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
669 // Splice the newly inserted blocks into the function right before the
670 // original preheader.
671 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
672 NewBlocks[0], F->end());
674 // Now we create the new Loop object for the versioned loop.
675 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
676 Loop *ParentLoop = L->getParentLoop();
678 // Make sure to add the cloned preheader and exit blocks to the parent loop
680 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
683 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
684 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
685 // The new exit block should be in the same loop as the old one.
686 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
687 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
689 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
690 "Exit block should have been split to have one successor!");
691 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
693 // If the successor of the exit block had PHI nodes, add an entry for
696 for (BasicBlock::iterator I = ExitSucc->begin();
697 (PN = dyn_cast<PHINode>(I)); ++I) {
698 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
699 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
700 if (It != ValueMap.end()) V = It->second;
701 PN->addIncoming(V, NewExit);
705 // Rewrite the code to refer to itself.
706 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
707 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
708 E = NewBlocks[i]->end(); I != E; ++I)
709 RemapInstruction(I, ValueMap);
711 // Rewrite the original preheader to select between versions of the loop.
712 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
713 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
714 "Preheader splitting did not work correctly!");
716 // Emit the new branch that selects between the two versions of this loop.
717 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
718 OldBR->eraseFromParent();
720 LoopProcessWorklist.push_back(NewLoop);
723 // Now we rewrite the original code to know that the condition is true and the
724 // new code to know that the condition is false.
725 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
727 // It's possible that simplifying one loop could cause the other to be
728 // deleted. If so, don't simplify it.
729 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
730 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
733 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
735 static void RemoveFromWorklist(Instruction *I,
736 std::vector<Instruction*> &Worklist) {
737 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
739 while (WI != Worklist.end()) {
740 unsigned Offset = WI-Worklist.begin();
742 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
746 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
747 /// program, replacing all uses with V and update the worklist.
748 static void ReplaceUsesOfWith(Instruction *I, Value *V,
749 std::vector<Instruction*> &Worklist) {
750 DOUT << "Replace with '" << *V << "': " << *I;
752 // Add uses to the worklist, which may be dead now.
753 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
754 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
755 Worklist.push_back(Use);
757 // Add users to the worklist which may be simplified now.
758 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
760 Worklist.push_back(cast<Instruction>(*UI));
761 I->replaceAllUsesWith(V);
762 I->eraseFromParent();
763 RemoveFromWorklist(I, Worklist);
767 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
768 /// information, and remove any dead successors it has.
770 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
771 std::vector<Instruction*> &Worklist) {
772 if (pred_begin(BB) != pred_end(BB)) {
773 // This block isn't dead, since an edge to BB was just removed, see if there
774 // are any easy simplifications we can do now.
775 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
776 // If it has one pred, fold phi nodes in BB.
777 while (isa<PHINode>(BB->begin()))
778 ReplaceUsesOfWith(BB->begin(),
779 cast<PHINode>(BB->begin())->getIncomingValue(0),
782 // If this is the header of a loop and the only pred is the latch, we now
783 // have an unreachable loop.
784 if (Loop *L = LI->getLoopFor(BB))
785 if (L->getHeader() == BB && L->contains(Pred)) {
786 // Remove the branch from the latch to the header block, this makes
787 // the header dead, which will make the latch dead (because the header
788 // dominates the latch).
789 Pred->getTerminator()->eraseFromParent();
790 new UnreachableInst(Pred);
792 // The loop is now broken, remove it from LI.
793 RemoveLoopFromHierarchy(L);
795 // Reprocess the header, which now IS dead.
796 RemoveBlockIfDead(BB, Worklist);
800 // If pred ends in a uncond branch, add uncond branch to worklist so that
801 // the two blocks will get merged.
802 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
803 if (BI->isUnconditional())
804 Worklist.push_back(BI);
809 DOUT << "Nuking dead block: " << *BB;
811 // Remove the instructions in the basic block from the worklist.
812 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
813 RemoveFromWorklist(I, Worklist);
815 // Anything that uses the instructions in this basic block should have their
816 // uses replaced with undefs.
818 I->replaceAllUsesWith(UndefValue::get(I->getType()));
821 // If this is the edge to the header block for a loop, remove the loop and
822 // promote all subloops.
823 if (Loop *BBLoop = LI->getLoopFor(BB)) {
824 if (BBLoop->getLoopLatch() == BB)
825 RemoveLoopFromHierarchy(BBLoop);
828 // Remove the block from the loop info, which removes it from any loops it
833 // Remove phi node entries in successors for this block.
834 TerminatorInst *TI = BB->getTerminator();
835 std::vector<BasicBlock*> Succs;
836 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
837 Succs.push_back(TI->getSuccessor(i));
838 TI->getSuccessor(i)->removePredecessor(BB);
841 // Unique the successors, remove anything with multiple uses.
842 std::sort(Succs.begin(), Succs.end());
843 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
845 // Remove the basic block, including all of the instructions contained in it.
846 BB->eraseFromParent();
848 // Remove successor blocks here that are not dead, so that we know we only
849 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
850 // then getting removed before we revisit them, which is badness.
852 for (unsigned i = 0; i != Succs.size(); ++i)
853 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
854 // One exception is loop headers. If this block was the preheader for a
855 // loop, then we DO want to visit the loop so the loop gets deleted.
856 // We know that if the successor is a loop header, that this loop had to
857 // be the preheader: the case where this was the latch block was handled
858 // above and headers can only have two predecessors.
859 if (!LI->isLoopHeader(Succs[i])) {
860 Succs.erase(Succs.begin()+i);
865 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
866 RemoveBlockIfDead(Succs[i], Worklist);
869 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
870 /// become unwrapped, either because the backedge was deleted, or because the
871 /// edge into the header was removed. If the edge into the header from the
872 /// latch block was removed, the loop is unwrapped but subloops are still alive,
873 /// so they just reparent loops. If the loops are actually dead, they will be
875 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
876 LPM->deleteLoopFromQueue(L);
877 RemoveLoopFromWorklist(L);
882 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
883 // the value specified by Val in the specified loop, or we know it does NOT have
884 // that value. Rewrite any uses of LIC or of properties correlated to it.
885 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
888 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
890 // FIXME: Support correlated properties, like:
897 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
898 // selects, switches.
899 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
900 std::vector<Instruction*> Worklist;
902 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
903 // in the loop with the appropriate one directly.
904 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
909 Replacement = ConstantInt::get(Type::Int1Ty,
910 !cast<ConstantInt>(Val)->getZExtValue());
912 for (unsigned i = 0, e = Users.size(); i != e; ++i)
913 if (Instruction *U = cast<Instruction>(Users[i])) {
914 if (!L->contains(U->getParent()))
916 U->replaceUsesOfWith(LIC, Replacement);
917 Worklist.push_back(U);
920 // Otherwise, we don't know the precise value of LIC, but we do know that it
921 // is certainly NOT "Val". As such, simplify any uses in the loop that we
922 // can. This case occurs when we unswitch switch statements.
923 for (unsigned i = 0, e = Users.size(); i != e; ++i)
924 if (Instruction *U = cast<Instruction>(Users[i])) {
925 if (!L->contains(U->getParent()))
928 Worklist.push_back(U);
930 // If we know that LIC is not Val, use this info to simplify code.
931 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
932 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
933 if (SI->getCaseValue(i) == Val) {
934 // Found a dead case value. Don't remove PHI nodes in the
935 // successor if they become single-entry, those PHI nodes may
936 // be in the Users list.
938 // FIXME: This is a hack. We need to keep the successor around
939 // and hooked up so as to preserve the loop structure, because
940 // trying to update it is complicated. So instead we preserve the
941 // loop structure and put the block on an dead code path.
943 BasicBlock* Old = SI->getParent();
944 BasicBlock* Split = SplitBlock(Old, SI);
946 Instruction* OldTerm = Old->getTerminator();
947 new BranchInst(Split, SI->getSuccessor(i),
948 ConstantInt::getTrue(), OldTerm);
950 Old->getTerminator()->eraseFromParent();
954 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
955 (PN = dyn_cast<PHINode>(II)); ++II) {
956 Value *InVal = PN->removeIncomingValue(Split, false);
957 PN->addIncoming(InVal, Old);
966 // TODO: We could do other simplifications, for example, turning
967 // LIC == Val -> false.
971 SimplifyCode(Worklist);
974 /// SimplifyCode - Okay, now that we have simplified some instructions in the
975 /// loop, walk over it and constant prop, dce, and fold control flow where
976 /// possible. Note that this is effectively a very simple loop-structure-aware
977 /// optimizer. During processing of this loop, L could very well be deleted, so
978 /// it must not be used.
980 /// FIXME: When the loop optimizer is more mature, separate this out to a new
983 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
984 while (!Worklist.empty()) {
985 Instruction *I = Worklist.back();
988 // Simple constant folding.
989 if (Constant *C = ConstantFoldInstruction(I)) {
990 ReplaceUsesOfWith(I, C, Worklist);
995 if (isInstructionTriviallyDead(I)) {
996 DOUT << "Remove dead instruction '" << *I;
998 // Add uses to the worklist, which may be dead now.
999 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1000 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1001 Worklist.push_back(Use);
1002 I->eraseFromParent();
1003 RemoveFromWorklist(I, Worklist);
1008 // Special case hacks that appear commonly in unswitched code.
1009 switch (I->getOpcode()) {
1010 case Instruction::Select:
1011 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1012 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
1016 case Instruction::And:
1017 if (isa<ConstantInt>(I->getOperand(0)) &&
1018 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1019 cast<BinaryOperator>(I)->swapOperands();
1020 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1021 if (CB->getType() == Type::Int1Ty) {
1022 if (CB->isOne()) // X & 1 -> X
1023 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1025 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1029 case Instruction::Or:
1030 if (isa<ConstantInt>(I->getOperand(0)) &&
1031 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1032 cast<BinaryOperator>(I)->swapOperands();
1033 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1034 if (CB->getType() == Type::Int1Ty) {
1035 if (CB->isOne()) // X | 1 -> 1
1036 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1038 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1042 case Instruction::Br: {
1043 BranchInst *BI = cast<BranchInst>(I);
1044 if (BI->isUnconditional()) {
1045 // If BI's parent is the only pred of the successor, fold the two blocks
1047 BasicBlock *Pred = BI->getParent();
1048 BasicBlock *Succ = BI->getSuccessor(0);
1049 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1050 if (!SinglePred) continue; // Nothing to do.
1051 assert(SinglePred == Pred && "CFG broken");
1053 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1054 << Succ->getName() << "\n";
1056 // Resolve any single entry PHI nodes in Succ.
1057 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1058 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1060 // Move all of the successor contents from Succ to Pred.
1061 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1063 BI->eraseFromParent();
1064 RemoveFromWorklist(BI, Worklist);
1066 // If Succ has any successors with PHI nodes, update them to have
1067 // entries coming from Pred instead of Succ.
1068 Succ->replaceAllUsesWith(Pred);
1070 // Remove Succ from the loop tree.
1071 LI->removeBlock(Succ);
1072 Succ->eraseFromParent();
1074 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1075 // Conditional branch. Turn it into an unconditional branch, then
1076 // remove dead blocks.
1077 break; // FIXME: Enable.
1079 DOUT << "Folded branch: " << *BI;
1080 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1081 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1082 DeadSucc->removePredecessor(BI->getParent(), true);
1083 Worklist.push_back(new BranchInst(LiveSucc, BI));
1084 BI->eraseFromParent();
1085 RemoveFromWorklist(BI, Worklist);
1088 RemoveBlockIfDead(DeadSucc, Worklist);