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/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/PostOrderIterator.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/Debug.h"
50 STATISTIC(NumBranches, "Number of branches unswitched");
51 STATISTIC(NumSwitches, "Number of switches unswitched");
52 STATISTIC(NumSelects , "Number of selects unswitched");
53 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
54 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
58 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
59 cl::init(10), cl::Hidden);
61 class VISIBILITY_HIDDEN LoopUnswitch : public FunctionPass {
62 LoopInfo *LI; // Loop information
64 // LoopProcessWorklist - List of loops we need to process.
65 std::vector<Loop*> LoopProcessWorklist;
66 SmallPtrSet<Value *,8> UnswitchedVals;
69 virtual bool runOnFunction(Function &F);
70 bool visitLoop(Loop *L);
72 /// This transformation requires natural loop information & requires that
73 /// loop preheaders be inserted into the CFG...
75 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequiredID(LoopSimplifyID);
77 AU.addPreservedID(LoopSimplifyID);
78 AU.addRequired<LoopInfo>();
79 AU.addPreserved<LoopInfo>();
80 AU.addRequiredID(LCSSAID);
81 AU.addPreservedID(LCSSAID);
85 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
87 void RemoveLoopFromWorklist(Loop *L) {
88 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
89 LoopProcessWorklist.end(), L);
90 if (I != LoopProcessWorklist.end())
91 LoopProcessWorklist.erase(I);
94 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
95 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
96 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
97 BasicBlock *ExitBlock);
98 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
99 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
100 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
102 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
103 Constant *Val, bool isEqual);
105 void SimplifyCode(std::vector<Instruction*> &Worklist);
106 void RemoveBlockIfDead(BasicBlock *BB,
107 std::vector<Instruction*> &Worklist);
108 void RemoveLoopFromHierarchy(Loop *L);
110 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
113 FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
115 bool LoopUnswitch::runOnFunction(Function &F) {
116 bool Changed = false;
117 LI = &getAnalysis<LoopInfo>();
119 // Populate the worklist of loops to process in post-order.
120 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
121 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
122 LoopProcessWorklist.push_back(*LI);
124 // Process the loops in worklist order, this is a post-order visitation of
125 // the loops. We use a worklist of loops so that loops can be removed at any
126 // time if they are deleted (e.g. the backedge of a loop is removed).
127 while (!LoopProcessWorklist.empty()) {
128 Loop *L = LoopProcessWorklist.back();
129 LoopProcessWorklist.pop_back();
130 Changed |= visitLoop(L);
133 UnswitchedVals.clear();
137 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
138 /// invariant in the loop, or has an invariant piece, return the invariant.
139 /// Otherwise, return null.
140 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
141 // Constants should be folded, not unswitched on!
142 if (isa<Constant>(Cond)) return false;
144 // TODO: Handle: br (VARIANT|INVARIANT).
145 // TODO: Hoist simple expressions out of loops.
146 if (L->isLoopInvariant(Cond)) return Cond;
148 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
149 if (BO->getOpcode() == Instruction::And ||
150 BO->getOpcode() == Instruction::Or) {
151 // If either the left or right side is invariant, we can unswitch on this,
152 // which will cause the branch to go away in one loop and the condition to
153 // simplify in the other one.
154 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
156 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
163 bool LoopUnswitch::visitLoop(Loop *L) {
164 assert(L->isLCSSAForm());
166 bool Changed = false;
168 // Loop over all of the basic blocks in the loop. If we find an interior
169 // block that is branching on a loop-invariant condition, we can unswitch this
171 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
173 TerminatorInst *TI = (*I)->getTerminator();
174 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
175 // If this isn't branching on an invariant condition, we can't unswitch
177 if (BI->isConditional()) {
178 // See if this, or some part of it, is loop invariant. If so, we can
179 // unswitch on it if we desire.
180 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
181 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
187 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
188 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
189 if (LoopCond && SI->getNumCases() > 1) {
190 // Find a value to unswitch on:
191 // FIXME: this should chose the most expensive case!
192 Constant *UnswitchVal = SI->getCaseValue(1);
193 // Do not process same value again and again.
194 if (!UnswitchedVals.insert(UnswitchVal))
197 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
204 // Scan the instructions to check for unswitchable values.
205 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
207 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
208 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
209 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
217 assert(L->isLCSSAForm());
222 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
223 /// 1. Exit the loop with no side effects.
224 /// 2. Branch to the latch block with no side-effects.
226 /// If these conditions are true, we return true and set ExitBB to the block we
229 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
231 std::set<BasicBlock*> &Visited) {
232 if (!Visited.insert(BB).second) {
233 // Already visited and Ok, end of recursion.
235 } else if (!L->contains(BB)) {
236 // Otherwise, this is a loop exit, this is fine so long as this is the
238 if (ExitBB != 0) return false;
243 // Otherwise, this is an unvisited intra-loop node. Check all successors.
244 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
245 // Check to see if the successor is a trivial loop exit.
246 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
250 // Okay, everything after this looks good, check to make sure that this block
251 // doesn't include any side effects.
252 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
253 if (I->mayWriteToMemory())
259 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
260 /// leads to an exit from the specified loop, and has no side-effects in the
261 /// process. If so, return the block that is exited to, otherwise return null.
262 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
263 std::set<BasicBlock*> Visited;
264 Visited.insert(L->getHeader()); // Branches to header are ok.
265 BasicBlock *ExitBB = 0;
266 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
271 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
272 /// trivial: that is, that the condition controls whether or not the loop does
273 /// anything at all. If this is a trivial condition, unswitching produces no
274 /// code duplications (equivalently, it produces a simpler loop and a new empty
275 /// loop, which gets deleted).
277 /// If this is a trivial condition, return true, otherwise return false. When
278 /// returning true, this sets Cond and Val to the condition that controls the
279 /// trivial condition: when Cond dynamically equals Val, the loop is known to
280 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
283 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
284 BasicBlock **LoopExit = 0) {
285 BasicBlock *Header = L->getHeader();
286 TerminatorInst *HeaderTerm = Header->getTerminator();
288 BasicBlock *LoopExitBB = 0;
289 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
290 // If the header block doesn't end with a conditional branch on Cond, we
292 if (!BI->isConditional() || BI->getCondition() != Cond)
295 // Check to see if a successor of the branch is guaranteed to go to the
296 // latch block or exit through a one exit block without having any
297 // side-effects. If so, determine the value of Cond that causes it to do
299 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
300 if (Val) *Val = ConstantInt::getTrue();
301 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
302 if (Val) *Val = ConstantInt::getFalse();
304 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
305 // If this isn't a switch on Cond, we can't handle it.
306 if (SI->getCondition() != Cond) return false;
308 // Check to see if a successor of the switch is guaranteed to go to the
309 // latch block or exit through a one exit block without having any
310 // side-effects. If so, determine the value of Cond that causes it to do
311 // this. Note that we can't trivially unswitch on the default case.
312 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
313 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
314 // Okay, we found a trivial case, remember the value that is trivial.
315 if (Val) *Val = SI->getCaseValue(i);
320 // If we didn't find a single unique LoopExit block, or if the loop exit block
321 // contains phi nodes, this isn't trivial.
322 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
323 return false; // Can't handle this.
325 if (LoopExit) *LoopExit = LoopExitBB;
327 // We already know that nothing uses any scalar values defined inside of this
328 // loop. As such, we just have to check to see if this loop will execute any
329 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
330 // part of the loop that the code *would* execute. We already checked the
331 // tail, check the header now.
332 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
333 if (I->mayWriteToMemory())
338 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
339 /// we choose to unswitch the specified loop on the specified value.
341 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
342 // If the condition is trivial, always unswitch. There is no code growth for
344 if (IsTrivialUnswitchCondition(L, LIC))
347 // FIXME: This is really overly conservative. However, more liberal
348 // estimations have thus far resulted in excessive unswitching, which is bad
349 // both in compile time and in code size. This should be replaced once
350 // someone figures out how a good estimation.
351 return L->getBlocks().size();
354 // FIXME: this is brain dead. It should take into consideration code
356 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
359 // Do not include empty blocks in the cost calculation. This happen due to
360 // loop canonicalization and will be removed.
361 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
364 // Count basic blocks.
371 /// UnswitchIfProfitable - We have found that we can unswitch L when
372 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
373 /// unswitch the loop, reprocess the pieces, then return true.
374 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
375 // Check to see if it would be profitable to unswitch this loop.
376 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
377 if (Cost > Threshold) {
378 // FIXME: this should estimate growth by the amount of code shared by the
379 // resultant unswitched loops.
381 DOUT << "NOT unswitching loop %"
382 << L->getHeader()->getName() << ", cost too high: "
383 << L->getBlocks().size() << "\n";
387 // If this is a trivial condition to unswitch (which results in no code
388 // duplication), do it now.
390 BasicBlock *ExitBlock;
391 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
392 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
394 UnswitchNontrivialCondition(LoopCond, Val, L);
400 /// SplitBlock - Split the specified block at the specified instruction - every
401 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
402 /// to a new block. The two blocks are joined by an unconditional branch and
403 /// the loop info is updated.
405 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
406 BasicBlock::iterator SplitIt = SplitPt;
407 while (isa<PHINode>(SplitIt))
409 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
411 // The new block lives in whichever loop the old one did.
412 if (Loop *L = LI->getLoopFor(Old))
413 L->addBasicBlockToLoop(New, *LI);
419 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
420 TerminatorInst *LatchTerm = BB->getTerminator();
421 unsigned SuccNum = 0;
422 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
423 assert(i != e && "Didn't find edge?");
424 if (LatchTerm->getSuccessor(i) == Succ) {
430 // If this is a critical edge, let SplitCriticalEdge do it.
431 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
432 return LatchTerm->getSuccessor(SuccNum);
434 // If the edge isn't critical, then BB has a single successor or Succ has a
435 // single pred. Split the block.
436 BasicBlock::iterator SplitPoint;
437 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
438 // If the successor only has a single pred, split the top of the successor
440 assert(SP == BB && "CFG broken");
441 return SplitBlock(Succ, Succ->begin());
443 // Otherwise, if BB has a single successor, split it at the bottom of the
445 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
446 "Should have a single succ!");
447 return SplitBlock(BB, BB->getTerminator());
453 // RemapInstruction - Convert the instruction operands from referencing the
454 // current values into those specified by ValueMap.
456 static inline void RemapInstruction(Instruction *I,
457 DenseMap<const Value *, Value*> &ValueMap) {
458 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
459 Value *Op = I->getOperand(op);
460 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
461 if (It != ValueMap.end()) Op = It->second;
462 I->setOperand(op, Op);
466 /// CloneLoop - Recursively clone the specified loop and all of its children,
467 /// mapping the blocks with the specified map.
468 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
470 Loop *New = new Loop();
473 PL->addChildLoop(New);
475 LI->addTopLevelLoop(New);
477 // Add all of the blocks in L to the new loop.
478 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
480 if (LI->getLoopFor(*I) == L)
481 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
483 // Add all of the subloops to the new loop.
484 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
485 CloneLoop(*I, New, VM, LI);
490 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
491 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
492 /// code immediately before InsertPt.
493 static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
494 BasicBlock *TrueDest,
495 BasicBlock *FalseDest,
496 Instruction *InsertPt) {
497 // Insert a conditional branch on LIC to the two preheaders. The original
498 // code is the true version and the new code is the false version.
499 Value *BranchVal = LIC;
500 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
501 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
502 else if (Val != ConstantInt::getTrue())
503 // We want to enter the new loop when the condition is true.
504 std::swap(TrueDest, FalseDest);
506 // Insert the new branch.
507 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
511 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
512 /// condition in it (a cond branch from its header block to its latch block,
513 /// where the path through the loop that doesn't execute its body has no
514 /// side-effects), unswitch it. This doesn't involve any code duplication, just
515 /// moving the conditional branch outside of the loop and updating loop info.
516 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
518 BasicBlock *ExitBlock) {
519 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
520 << L->getHeader()->getName() << " [" << L->getBlocks().size()
521 << " blocks] in Function " << L->getHeader()->getParent()->getName()
522 << " on cond: " << *Val << " == " << *Cond << "\n";
524 // First step, split the preheader, so that we know that there is a safe place
525 // to insert the conditional branch. We will change 'OrigPH' to have a
526 // conditional branch on Cond.
527 BasicBlock *OrigPH = L->getLoopPreheader();
528 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
530 // Now that we have a place to insert the conditional branch, create a place
531 // to branch to: this is the exit block out of the loop that we should
534 // Split this block now, so that the loop maintains its exit block, and so
535 // that the jump from the preheader can execute the contents of the exit block
536 // without actually branching to it (the exit block should be dominated by the
537 // loop header, not the preheader).
538 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
539 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
541 // Okay, now we have a position to branch from and a position to branch to,
542 // insert the new conditional branch.
543 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
544 OrigPH->getTerminator());
545 OrigPH->getTerminator()->eraseFromParent();
547 // We need to reprocess this loop, it could be unswitched again.
548 LoopProcessWorklist.push_back(L);
550 // Now that we know that the loop is never entered when this condition is a
551 // particular value, rewrite the loop with this info. We know that this will
552 // at least eliminate the old branch.
553 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
558 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
559 /// equal Val. Split it into loop versions and test the condition outside of
560 /// either loop. Return the loops created as Out1/Out2.
561 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
563 Function *F = L->getHeader()->getParent();
564 DOUT << "loop-unswitch: Unswitching loop %"
565 << L->getHeader()->getName() << " [" << L->getBlocks().size()
566 << " blocks] in Function " << F->getName()
567 << " when '" << *Val << "' == " << *LIC << "\n";
569 // LoopBlocks contains all of the basic blocks of the loop, including the
570 // preheader of the loop, the body of the loop, and the exit blocks of the
571 // loop, in that order.
572 std::vector<BasicBlock*> LoopBlocks;
574 // First step, split the preheader and exit blocks, and add these blocks to
575 // the LoopBlocks list.
576 BasicBlock *OrigPreheader = L->getLoopPreheader();
577 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
579 // We want the loop to come after the preheader, but before the exit blocks.
580 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
582 std::vector<BasicBlock*> ExitBlocks;
583 L->getUniqueExitBlocks(ExitBlocks);
585 // Split all of the edges from inside the loop to their exit blocks. Update
586 // the appropriate Phi nodes as we do so.
587 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
588 BasicBlock *ExitBlock = ExitBlocks[i];
589 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
591 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
592 assert(L->contains(Preds[j]) &&
593 "All preds of loop exit blocks must be the same loop!");
594 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
595 BasicBlock* StartBlock = Preds[j];
596 BasicBlock* EndBlock;
597 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
598 EndBlock = MiddleBlock;
599 MiddleBlock = EndBlock->getSinglePredecessor();;
601 EndBlock = ExitBlock;
604 std::set<PHINode*> InsertedPHIs;
605 PHINode* OldLCSSA = 0;
606 for (BasicBlock::iterator I = EndBlock->begin();
607 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
608 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
609 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
610 OldLCSSA->getName() + ".us-lcssa",
611 MiddleBlock->getTerminator());
612 NewLCSSA->addIncoming(OldValue, StartBlock);
613 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
615 InsertedPHIs.insert(NewLCSSA);
618 BasicBlock::iterator InsertPt = EndBlock->begin();
619 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
620 for (BasicBlock::iterator I = MiddleBlock->begin();
621 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
623 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
624 OldLCSSA->getName() + ".us-lcssa",
626 OldLCSSA->replaceAllUsesWith(NewLCSSA);
627 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
632 // The exit blocks may have been changed due to edge splitting, recompute.
634 L->getUniqueExitBlocks(ExitBlocks);
636 // Add exit blocks to the loop blocks.
637 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
639 // Next step, clone all of the basic blocks that make up the loop (including
640 // the loop preheader and exit blocks), keeping track of the mapping between
641 // the instructions and blocks.
642 std::vector<BasicBlock*> NewBlocks;
643 NewBlocks.reserve(LoopBlocks.size());
644 DenseMap<const Value*, Value*> ValueMap;
645 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
646 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
647 NewBlocks.push_back(New);
648 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
651 // Splice the newly inserted blocks into the function right before the
652 // original preheader.
653 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
654 NewBlocks[0], F->end());
656 // Now we create the new Loop object for the versioned loop.
657 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
658 Loop *ParentLoop = L->getParentLoop();
660 // Make sure to add the cloned preheader and exit blocks to the parent loop
662 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
665 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
666 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
667 // The new exit block should be in the same loop as the old one.
668 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
669 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
671 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
672 "Exit block should have been split to have one successor!");
673 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
675 // If the successor of the exit block had PHI nodes, add an entry for
678 for (BasicBlock::iterator I = ExitSucc->begin();
679 (PN = dyn_cast<PHINode>(I)); ++I) {
680 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
681 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
682 if (It != ValueMap.end()) V = It->second;
683 PN->addIncoming(V, NewExit);
687 // Rewrite the code to refer to itself.
688 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
689 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
690 E = NewBlocks[i]->end(); I != E; ++I)
691 RemapInstruction(I, ValueMap);
693 // Rewrite the original preheader to select between versions of the loop.
694 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
695 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
696 "Preheader splitting did not work correctly!");
698 // Emit the new branch that selects between the two versions of this loop.
699 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
700 OldBR->eraseFromParent();
702 LoopProcessWorklist.push_back(L);
703 LoopProcessWorklist.push_back(NewLoop);
705 // Now we rewrite the original code to know that the condition is true and the
706 // new code to know that the condition is false.
707 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
709 // It's possible that simplifying one loop could cause the other to be
710 // deleted. If so, don't simplify it.
711 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
712 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
715 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
717 static void RemoveFromWorklist(Instruction *I,
718 std::vector<Instruction*> &Worklist) {
719 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
721 while (WI != Worklist.end()) {
722 unsigned Offset = WI-Worklist.begin();
724 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
728 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
729 /// program, replacing all uses with V and update the worklist.
730 static void ReplaceUsesOfWith(Instruction *I, Value *V,
731 std::vector<Instruction*> &Worklist) {
732 DOUT << "Replace with '" << *V << "': " << *I;
734 // Add uses to the worklist, which may be dead now.
735 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
736 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
737 Worklist.push_back(Use);
739 // Add users to the worklist which may be simplified now.
740 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
742 Worklist.push_back(cast<Instruction>(*UI));
743 I->replaceAllUsesWith(V);
744 I->eraseFromParent();
745 RemoveFromWorklist(I, Worklist);
749 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
750 /// information, and remove any dead successors it has.
752 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
753 std::vector<Instruction*> &Worklist) {
754 if (pred_begin(BB) != pred_end(BB)) {
755 // This block isn't dead, since an edge to BB was just removed, see if there
756 // are any easy simplifications we can do now.
757 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
758 // If it has one pred, fold phi nodes in BB.
759 while (isa<PHINode>(BB->begin()))
760 ReplaceUsesOfWith(BB->begin(),
761 cast<PHINode>(BB->begin())->getIncomingValue(0),
764 // If this is the header of a loop and the only pred is the latch, we now
765 // have an unreachable loop.
766 if (Loop *L = LI->getLoopFor(BB))
767 if (L->getHeader() == BB && L->contains(Pred)) {
768 // Remove the branch from the latch to the header block, this makes
769 // the header dead, which will make the latch dead (because the header
770 // dominates the latch).
771 Pred->getTerminator()->eraseFromParent();
772 new UnreachableInst(Pred);
774 // The loop is now broken, remove it from LI.
775 RemoveLoopFromHierarchy(L);
777 // Reprocess the header, which now IS dead.
778 RemoveBlockIfDead(BB, Worklist);
782 // If pred ends in a uncond branch, add uncond branch to worklist so that
783 // the two blocks will get merged.
784 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
785 if (BI->isUnconditional())
786 Worklist.push_back(BI);
791 DOUT << "Nuking dead block: " << *BB;
793 // Remove the instructions in the basic block from the worklist.
794 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
795 RemoveFromWorklist(I, Worklist);
797 // Anything that uses the instructions in this basic block should have their
798 // uses replaced with undefs.
800 I->replaceAllUsesWith(UndefValue::get(I->getType()));
803 // If this is the edge to the header block for a loop, remove the loop and
804 // promote all subloops.
805 if (Loop *BBLoop = LI->getLoopFor(BB)) {
806 if (BBLoop->getLoopLatch() == BB)
807 RemoveLoopFromHierarchy(BBLoop);
810 // Remove the block from the loop info, which removes it from any loops it
815 // Remove phi node entries in successors for this block.
816 TerminatorInst *TI = BB->getTerminator();
817 std::vector<BasicBlock*> Succs;
818 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
819 Succs.push_back(TI->getSuccessor(i));
820 TI->getSuccessor(i)->removePredecessor(BB);
823 // Unique the successors, remove anything with multiple uses.
824 std::sort(Succs.begin(), Succs.end());
825 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
827 // Remove the basic block, including all of the instructions contained in it.
828 BB->eraseFromParent();
830 // Remove successor blocks here that are not dead, so that we know we only
831 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
832 // then getting removed before we revisit them, which is badness.
834 for (unsigned i = 0; i != Succs.size(); ++i)
835 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
836 // One exception is loop headers. If this block was the preheader for a
837 // loop, then we DO want to visit the loop so the loop gets deleted.
838 // We know that if the successor is a loop header, that this loop had to
839 // be the preheader: the case where this was the latch block was handled
840 // above and headers can only have two predecessors.
841 if (!LI->isLoopHeader(Succs[i])) {
842 Succs.erase(Succs.begin()+i);
847 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
848 RemoveBlockIfDead(Succs[i], Worklist);
851 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
852 /// become unwrapped, either because the backedge was deleted, or because the
853 /// edge into the header was removed. If the edge into the header from the
854 /// latch block was removed, the loop is unwrapped but subloops are still alive,
855 /// so they just reparent loops. If the loops are actually dead, they will be
857 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
858 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
859 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
860 // they are now all in it.
861 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
863 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
864 LI->changeLoopFor(*I, ParentLoop);
866 // Remove the loop from its parent loop.
867 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
869 assert(I != E && "Couldn't find loop");
871 ParentLoop->removeChildLoop(I);
876 // Move all subloops into the parent loop.
877 while (L->begin() != L->end())
878 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
880 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
881 // they no longer in a loop at all.
883 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
884 // Don't change blocks in subloops.
885 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
886 LI->removeBlock(L->getBlocks()[i]);
891 // Remove the loop from the top-level LoopInfo object.
892 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
893 assert(I != E && "Couldn't find loop");
900 // Move all of the subloops to the top-level.
901 while (L->begin() != L->end())
902 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
906 RemoveLoopFromWorklist(L);
911 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
912 // the value specified by Val in the specified loop, or we know it does NOT have
913 // that value. Rewrite any uses of LIC or of properties correlated to it.
914 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
917 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
919 // FIXME: Support correlated properties, like:
926 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
927 // selects, switches.
928 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
929 std::vector<Instruction*> Worklist;
931 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
932 // in the loop with the appropriate one directly.
933 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
938 Replacement = ConstantInt::get(Type::Int1Ty,
939 !cast<ConstantInt>(Val)->getZExtValue());
941 for (unsigned i = 0, e = Users.size(); i != e; ++i)
942 if (Instruction *U = cast<Instruction>(Users[i])) {
943 if (!L->contains(U->getParent()))
945 U->replaceUsesOfWith(LIC, Replacement);
946 Worklist.push_back(U);
949 // Otherwise, we don't know the precise value of LIC, but we do know that it
950 // is certainly NOT "Val". As such, simplify any uses in the loop that we
951 // can. This case occurs when we unswitch switch statements.
952 for (unsigned i = 0, e = Users.size(); i != e; ++i)
953 if (Instruction *U = cast<Instruction>(Users[i])) {
954 if (!L->contains(U->getParent()))
957 Worklist.push_back(U);
959 // If we know that LIC is not Val, use this info to simplify code.
960 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
961 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
962 if (SI->getCaseValue(i) == Val) {
963 // Found a dead case value. Don't remove PHI nodes in the
964 // successor if they become single-entry, those PHI nodes may
965 // be in the Users list.
967 // FIXME: This is a hack. We need to keep the successor around
968 // and hooked up so as to preserve the loop structure, because
969 // trying to update it is complicated. So instead we preserve the
970 // loop structure and put the block on an dead code path.
972 BasicBlock* Old = SI->getParent();
973 BasicBlock* Split = SplitBlock(Old, SI);
975 Instruction* OldTerm = Old->getTerminator();
976 new BranchInst(Split, SI->getSuccessor(i),
977 ConstantInt::getTrue(), OldTerm);
979 Old->getTerminator()->eraseFromParent();
983 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
984 (PN = dyn_cast<PHINode>(II)); ++II) {
985 Value *InVal = PN->removeIncomingValue(Split, false);
986 PN->addIncoming(InVal, Old);
995 // TODO: We could do other simplifications, for example, turning
996 // LIC == Val -> false.
1000 SimplifyCode(Worklist);
1003 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1004 /// loop, walk over it and constant prop, dce, and fold control flow where
1005 /// possible. Note that this is effectively a very simple loop-structure-aware
1006 /// optimizer. During processing of this loop, L could very well be deleted, so
1007 /// it must not be used.
1009 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1012 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
1013 while (!Worklist.empty()) {
1014 Instruction *I = Worklist.back();
1015 Worklist.pop_back();
1017 // Simple constant folding.
1018 if (Constant *C = ConstantFoldInstruction(I)) {
1019 ReplaceUsesOfWith(I, C, Worklist);
1024 if (isInstructionTriviallyDead(I)) {
1025 DOUT << "Remove dead instruction '" << *I;
1027 // Add uses to the worklist, which may be dead now.
1028 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1029 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1030 Worklist.push_back(Use);
1031 I->eraseFromParent();
1032 RemoveFromWorklist(I, Worklist);
1037 // Special case hacks that appear commonly in unswitched code.
1038 switch (I->getOpcode()) {
1039 case Instruction::Select:
1040 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1041 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
1045 case Instruction::And:
1046 if (isa<ConstantInt>(I->getOperand(0)) &&
1047 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1048 cast<BinaryOperator>(I)->swapOperands();
1049 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1050 if (CB->getType() == Type::Int1Ty) {
1051 if (CB->isOne()) // X & 1 -> X
1052 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1054 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1058 case Instruction::Or:
1059 if (isa<ConstantInt>(I->getOperand(0)) &&
1060 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1061 cast<BinaryOperator>(I)->swapOperands();
1062 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1063 if (CB->getType() == Type::Int1Ty) {
1064 if (CB->isOne()) // X | 1 -> 1
1065 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1067 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1071 case Instruction::Br: {
1072 BranchInst *BI = cast<BranchInst>(I);
1073 if (BI->isUnconditional()) {
1074 // If BI's parent is the only pred of the successor, fold the two blocks
1076 BasicBlock *Pred = BI->getParent();
1077 BasicBlock *Succ = BI->getSuccessor(0);
1078 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1079 if (!SinglePred) continue; // Nothing to do.
1080 assert(SinglePred == Pred && "CFG broken");
1082 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1083 << Succ->getName() << "\n";
1085 // Resolve any single entry PHI nodes in Succ.
1086 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1087 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1089 // Move all of the successor contents from Succ to Pred.
1090 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1092 BI->eraseFromParent();
1093 RemoveFromWorklist(BI, Worklist);
1095 // If Succ has any successors with PHI nodes, update them to have
1096 // entries coming from Pred instead of Succ.
1097 Succ->replaceAllUsesWith(Pred);
1099 // Remove Succ from the loop tree.
1100 LI->removeBlock(Succ);
1101 Succ->eraseFromParent();
1103 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1104 // Conditional branch. Turn it into an unconditional branch, then
1105 // remove dead blocks.
1106 break; // FIXME: Enable.
1108 DOUT << "Folded branch: " << *BI;
1109 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1110 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1111 DeadSucc->removePredecessor(BI->getParent(), true);
1112 Worklist.push_back(new BranchInst(LiveSucc, BI));
1113 BI->eraseFromParent();
1114 RemoveFromWorklist(BI, Worklist);
1117 RemoveBlockIfDead(DeadSucc, Worklist);