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/Function.h"
33 #include "llvm/Instructions.h"
34 #include "llvm/Analysis/LoopInfo.h"
35 #include "llvm/Transforms/Utils/Cloning.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/PostOrderIterator.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/CommandLine.h"
48 Statistic<> NumBranches("loop-unswitch", "Number of branches unswitched");
49 Statistic<> NumSwitches("loop-unswitch", "Number of switches unswitched");
50 Statistic<> NumSelects ("loop-unswitch", "Number of selects unswitched");
51 Statistic<> NumTrivial ("loop-unswitch",
52 "Number of unswitches that are trivial");
53 Statistic<> NumSimplify("loop-unswitch",
54 "Number of simplifications of unswitched code");
56 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
57 cl::init(10), cl::Hidden);
59 class LoopUnswitch : public FunctionPass {
60 LoopInfo *LI; // Loop information
62 // LoopProcessWorklist - List of loops we need to process.
63 std::vector<Loop*> LoopProcessWorklist;
65 virtual bool runOnFunction(Function &F);
66 bool visitLoop(Loop *L);
68 /// This transformation requires natural loop information & requires that
69 /// loop preheaders be inserted into the CFG...
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequiredID(LoopSimplifyID);
73 AU.addPreservedID(LoopSimplifyID);
74 AU.addRequired<LoopInfo>();
75 AU.addPreserved<LoopInfo>();
76 AU.addRequiredID(LCSSAID);
77 AU.addPreservedID(LCSSAID);
81 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
83 void RemoveLoopFromWorklist(Loop *L) {
84 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
85 LoopProcessWorklist.end(), L);
86 if (I != LoopProcessWorklist.end())
87 LoopProcessWorklist.erase(I);
90 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
91 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
92 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
93 BasicBlock *ExitBlock);
94 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
95 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
96 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
98 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
99 Constant *Val, bool isEqual);
101 void SimplifyCode(std::vector<Instruction*> &Worklist);
102 void RemoveBlockIfDead(BasicBlock *BB,
103 std::vector<Instruction*> &Worklist);
104 void RemoveLoopFromHierarchy(Loop *L);
106 RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
109 FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
111 bool LoopUnswitch::runOnFunction(Function &F) {
112 bool Changed = false;
113 LI = &getAnalysis<LoopInfo>();
115 // Populate the worklist of loops to process in post-order.
116 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
117 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
118 LoopProcessWorklist.push_back(*LI);
120 // Process the loops in worklist order, this is a post-order visitation of
121 // the loops. We use a worklist of loops so that loops can be removed at any
122 // time if they are deleted (e.g. the backedge of a loop is removed).
123 while (!LoopProcessWorklist.empty()) {
124 Loop *L = LoopProcessWorklist.back();
125 LoopProcessWorklist.pop_back();
126 Changed |= visitLoop(L);
132 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
133 /// invariant in the loop, or has an invariant piece, return the invariant.
134 /// Otherwise, return null.
135 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
136 // Constants should be folded, not unswitched on!
137 if (isa<Constant>(Cond)) return false;
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::visitLoop(Loop *L) {
159 assert(L->isLCSSAForm());
161 bool Changed = false;
163 // Loop over all of the basic blocks in the loop. If we find an interior
164 // block that is branching on a loop-invariant condition, we can unswitch this
166 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
168 TerminatorInst *TI = (*I)->getTerminator();
169 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
170 // If this isn't branching on an invariant condition, we can't unswitch
172 if (BI->isConditional()) {
173 // See if this, or some part of it, is loop invariant. If so, we can
174 // unswitch on it if we desire.
175 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
176 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
181 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
182 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
183 if (LoopCond && SI->getNumCases() > 1) {
184 // Find a value to unswitch on:
185 // FIXME: this should chose the most expensive case!
186 Constant *UnswitchVal = SI->getCaseValue(1);
187 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
194 // Scan the instructions to check for unswitchable values.
195 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
197 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
198 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
199 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
206 assert(L->isLCSSAForm());
212 /// LoopValuesUsedOutsideLoop - Return true if there are any values defined in
213 /// the loop that are used by instructions outside of it.
214 static bool LoopValuesUsedOutsideLoop(Loop *L) {
215 // We will be doing lots of "loop contains block" queries. Loop::contains is
216 // linear time, use a set to speed this up.
217 std::set<BasicBlock*> LoopBlocks;
219 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
221 LoopBlocks.insert(*BB);
223 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
225 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
226 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
228 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
229 if (!LoopBlocks.count(UserBB))
236 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
237 /// 1. Exit the loop with no side effects.
238 /// 2. Branch to the latch block with no side-effects.
240 /// If these conditions are true, we return true and set ExitBB to the block we
243 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
245 std::set<BasicBlock*> &Visited) {
246 if (!Visited.insert(BB).second) {
247 // Already visited and Ok, end of recursion.
249 } else if (!L->contains(BB)) {
250 // Otherwise, this is a loop exit, this is fine so long as this is the
252 if (ExitBB != 0) return false;
257 // Otherwise, this is an unvisited intra-loop node. Check all successors.
258 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
259 // Check to see if the successor is a trivial loop exit.
260 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
264 // Okay, everything after this looks good, check to make sure that this block
265 // doesn't include any side effects.
266 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
267 if (I->mayWriteToMemory())
273 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
274 /// leads to an exit from the specified loop, and has no side-effects in the
275 /// process. If so, return the block that is exited to, otherwise return null.
276 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
277 std::set<BasicBlock*> Visited;
278 Visited.insert(L->getHeader()); // Branches to header are ok.
279 BasicBlock *ExitBB = 0;
280 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
285 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
286 /// trivial: that is, that the condition controls whether or not the loop does
287 /// anything at all. If this is a trivial condition, unswitching produces no
288 /// code duplications (equivalently, it produces a simpler loop and a new empty
289 /// loop, which gets deleted).
291 /// If this is a trivial condition, return true, otherwise return false. When
292 /// returning true, this sets Cond and Val to the condition that controls the
293 /// trivial condition: when Cond dynamically equals Val, the loop is known to
294 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
297 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
298 BasicBlock **LoopExit = 0) {
299 BasicBlock *Header = L->getHeader();
300 TerminatorInst *HeaderTerm = Header->getTerminator();
302 BasicBlock *LoopExitBB = 0;
303 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
304 // If the header block doesn't end with a conditional branch on Cond, we
306 if (!BI->isConditional() || BI->getCondition() != Cond)
309 // Check to see if a successor of the branch is guaranteed to go to the
310 // latch block or exit through a one exit block without having any
311 // side-effects. If so, determine the value of Cond that causes it to do
313 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
314 if (Val) *Val = ConstantBool::True;
315 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
316 if (Val) *Val = ConstantBool::False;
318 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
319 // If this isn't a switch on Cond, we can't handle it.
320 if (SI->getCondition() != Cond) return false;
322 // Check to see if a successor of the switch is guaranteed to go to the
323 // latch block or exit through a one exit block without having any
324 // side-effects. If so, determine the value of Cond that causes it to do
325 // this. Note that we can't trivially unswitch on the default case.
326 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
327 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
328 // Okay, we found a trivial case, remember the value that is trivial.
329 if (Val) *Val = SI->getCaseValue(i);
334 // If we didn't find a single unique LoopExit block, or if the loop exit block
335 // contains phi nodes, this isn't trivial.
336 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
337 return false; // Can't handle this.
339 if (LoopExit) *LoopExit = LoopExitBB;
341 // We already know that nothing uses any scalar values defined inside of this
342 // loop. As such, we just have to check to see if this loop will execute any
343 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
344 // part of the loop that the code *would* execute. We already checked the
345 // tail, check the header now.
346 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
347 if (I->mayWriteToMemory())
352 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
353 /// we choose to unswitch the specified loop on the specified value.
355 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
356 // If the condition is trivial, always unswitch. There is no code growth for
358 if (IsTrivialUnswitchCondition(L, LIC))
362 // FIXME: this is brain dead. It should take into consideration code
364 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
367 // Do not include empty blocks in the cost calculation. This happen due to
368 // loop canonicalization and will be removed.
369 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
372 // Count basic blocks.
379 /// UnswitchIfProfitable - We have found that we can unswitch L when
380 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
381 /// unswitch the loop, reprocess the pieces, then return true.
382 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
383 // Check to see if it would be profitable to unswitch this loop.
384 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
385 if (Cost > Threshold) {
386 // FIXME: this should estimate growth by the amount of code shared by the
387 // resultant unswitched loops.
389 DEBUG(std::cerr << "NOT unswitching loop %"
390 << L->getHeader()->getName() << ", cost too high: "
391 << L->getBlocks().size() << "\n");
395 // If this loop has live-out values, we can't unswitch it. We need something
396 // like loop-closed SSA form in order to know how to insert PHI nodes for
398 if (LoopValuesUsedOutsideLoop(L)) {
399 DEBUG(std::cerr << "NOT unswitching loop %" << L->getHeader()->getName()
400 << ", a loop value is used outside loop! Cost: "
405 // If this is a trivial condition to unswitch (which results in no code
406 // duplication), do it now.
408 BasicBlock *ExitBlock;
409 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
410 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
412 UnswitchNontrivialCondition(LoopCond, Val, L);
418 /// SplitBlock - Split the specified block at the specified instruction - every
419 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
420 /// to a new block. The two blocks are joined by an unconditional branch and
421 /// the loop info is updated.
423 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
424 BasicBlock::iterator SplitIt = SplitPt;
425 while (isa<PHINode>(SplitIt))
427 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
429 // The new block lives in whichever loop the old one did.
430 if (Loop *L = LI->getLoopFor(Old))
431 L->addBasicBlockToLoop(New, *LI);
437 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
438 TerminatorInst *LatchTerm = BB->getTerminator();
439 unsigned SuccNum = 0;
440 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
441 assert(i != e && "Didn't find edge?");
442 if (LatchTerm->getSuccessor(i) == Succ) {
448 // If this is a critical edge, let SplitCriticalEdge do it.
449 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
450 return LatchTerm->getSuccessor(SuccNum);
452 // If the edge isn't critical, then BB has a single successor or Succ has a
453 // single pred. Split the block.
454 BasicBlock::iterator SplitPoint;
455 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
456 // If the successor only has a single pred, split the top of the successor
458 assert(SP == BB && "CFG broken");
459 return SplitBlock(Succ, Succ->begin());
461 // Otherwise, if BB has a single successor, split it at the bottom of the
463 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
464 "Should have a single succ!");
465 return SplitBlock(BB, BB->getTerminator());
471 // RemapInstruction - Convert the instruction operands from referencing the
472 // current values into those specified by ValueMap.
474 static inline void RemapInstruction(Instruction *I,
475 std::map<const Value *, Value*> &ValueMap) {
476 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
477 Value *Op = I->getOperand(op);
478 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
479 if (It != ValueMap.end()) Op = It->second;
480 I->setOperand(op, Op);
484 /// CloneLoop - Recursively clone the specified loop and all of its children,
485 /// mapping the blocks with the specified map.
486 static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
488 Loop *New = new Loop();
491 PL->addChildLoop(New);
493 LI->addTopLevelLoop(New);
495 // Add all of the blocks in L to the new loop.
496 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
498 if (LI->getLoopFor(*I) == L)
499 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
501 // Add all of the subloops to the new loop.
502 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
503 CloneLoop(*I, New, VM, LI);
508 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
509 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
510 /// code immediately before InsertPt.
511 static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
512 BasicBlock *TrueDest,
513 BasicBlock *FalseDest,
514 Instruction *InsertPt) {
515 // Insert a conditional branch on LIC to the two preheaders. The original
516 // code is the true version and the new code is the false version.
517 Value *BranchVal = LIC;
518 if (!isa<ConstantBool>(Val)) {
519 BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt);
520 } else if (Val != ConstantBool::True) {
521 // We want to enter the new loop when the condition is true.
522 std::swap(TrueDest, FalseDest);
525 // Insert the new branch.
526 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
530 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
531 /// condition in it (a cond branch from its header block to its latch block,
532 /// where the path through the loop that doesn't execute its body has no
533 /// side-effects), unswitch it. This doesn't involve any code duplication, just
534 /// moving the conditional branch outside of the loop and updating loop info.
535 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
537 BasicBlock *ExitBlock) {
538 DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
539 << L->getHeader()->getName() << " [" << L->getBlocks().size()
540 << " blocks] in Function " << L->getHeader()->getParent()->getName()
541 << " on cond: " << *Val << " == " << *Cond << "\n");
543 // First step, split the preheader, so that we know that there is a safe place
544 // to insert the conditional branch. We will change 'OrigPH' to have a
545 // conditional branch on Cond.
546 BasicBlock *OrigPH = L->getLoopPreheader();
547 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
549 // Now that we have a place to insert the conditional branch, create a place
550 // to branch to: this is the exit block out of the loop that we should
553 // Split this block now, so that the loop maintains its exit block, and so
554 // that the jump from the preheader can execute the contents of the exit block
555 // without actually branching to it (the exit block should be dominated by the
556 // loop header, not the preheader).
557 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
558 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
560 // Okay, now we have a position to branch from and a position to branch to,
561 // insert the new conditional branch.
562 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
563 OrigPH->getTerminator());
564 OrigPH->getTerminator()->eraseFromParent();
566 // We need to reprocess this loop, it could be unswitched again.
567 LoopProcessWorklist.push_back(L);
569 // Now that we know that the loop is never entered when this condition is a
570 // particular value, rewrite the loop with this info. We know that this will
571 // at least eliminate the old branch.
572 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
577 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
578 /// equal Val. Split it into loop versions and test the condition outside of
579 /// either loop. Return the loops created as Out1/Out2.
580 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
582 Function *F = L->getHeader()->getParent();
583 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
584 << L->getHeader()->getName() << " [" << L->getBlocks().size()
585 << " blocks] in Function " << F->getName()
586 << " when '" << *Val << "' == " << *LIC << "\n");
588 // LoopBlocks contains all of the basic blocks of the loop, including the
589 // preheader of the loop, the body of the loop, and the exit blocks of the
590 // loop, in that order.
591 std::vector<BasicBlock*> LoopBlocks;
593 // First step, split the preheader and exit blocks, and add these blocks to
594 // the LoopBlocks list.
595 BasicBlock *OrigPreheader = L->getLoopPreheader();
596 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
598 // We want the loop to come after the preheader, but before the exit blocks.
599 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
601 std::vector<BasicBlock*> ExitBlocks;
602 L->getExitBlocks(ExitBlocks);
603 std::sort(ExitBlocks.begin(), ExitBlocks.end());
604 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
607 // Split all of the edges from inside the loop to their exit blocks. This
608 // unswitching trivial: no phi nodes to update.
609 unsigned NumBlocks = L->getBlocks().size();
611 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
612 BasicBlock *ExitBlock = ExitBlocks[i];
613 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
615 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
616 assert(L->contains(Preds[j]) &&
617 "All preds of loop exit blocks must be the same loop!");
618 SplitEdge(Preds[j], ExitBlock);
622 // The exit blocks may have been changed due to edge splitting, recompute.
624 L->getExitBlocks(ExitBlocks);
625 std::sort(ExitBlocks.begin(), ExitBlocks.end());
626 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
629 // Add exit blocks to the loop blocks.
630 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
632 // Next step, clone all of the basic blocks that make up the loop (including
633 // the loop preheader and exit blocks), keeping track of the mapping between
634 // the instructions and blocks.
635 std::vector<BasicBlock*> NewBlocks;
636 NewBlocks.reserve(LoopBlocks.size());
637 std::map<const Value*, Value*> ValueMap;
638 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
639 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
640 NewBlocks.push_back(New);
641 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
644 // Splice the newly inserted blocks into the function right before the
645 // original preheader.
646 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
647 NewBlocks[0], F->end());
649 // Now we create the new Loop object for the versioned loop.
650 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
651 Loop *ParentLoop = L->getParentLoop();
653 // Make sure to add the cloned preheader and exit blocks to the parent loop
655 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
658 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
659 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
660 // The new exit block should be in the same loop as the old one.
661 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
662 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
664 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
665 "Exit block should have been split to have one successor!");
666 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
668 // If the successor of the exit block had PHI nodes, add an entry for
671 for (BasicBlock::iterator I = ExitSucc->begin();
672 (PN = dyn_cast<PHINode>(I)); ++I) {
673 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
674 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
675 if (It != ValueMap.end()) V = It->second;
676 PN->addIncoming(V, NewExit);
680 // Rewrite the code to refer to itself.
681 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
682 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
683 E = NewBlocks[i]->end(); I != E; ++I)
684 RemapInstruction(I, ValueMap);
686 // Rewrite the original preheader to select between versions of the loop.
687 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
688 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
689 "Preheader splitting did not work correctly!");
691 // Emit the new branch that selects between the two versions of this loop.
692 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
693 OldBR->eraseFromParent();
695 LoopProcessWorklist.push_back(L);
696 LoopProcessWorklist.push_back(NewLoop);
698 // Now we rewrite the original code to know that the condition is true and the
699 // new code to know that the condition is false.
700 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
702 // It's possible that simplifying one loop could cause the other to be
703 // deleted. If so, don't simplify it.
704 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
705 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
708 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
710 static void RemoveFromWorklist(Instruction *I,
711 std::vector<Instruction*> &Worklist) {
712 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
714 while (WI != Worklist.end()) {
715 unsigned Offset = WI-Worklist.begin();
717 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
721 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
722 /// program, replacing all uses with V and update the worklist.
723 static void ReplaceUsesOfWith(Instruction *I, Value *V,
724 std::vector<Instruction*> &Worklist) {
725 DEBUG(std::cerr << "Replace with '" << *V << "': " << *I);
727 // Add uses to the worklist, which may be dead now.
728 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
729 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
730 Worklist.push_back(Use);
732 // Add users to the worklist which may be simplified now.
733 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
735 Worklist.push_back(cast<Instruction>(*UI));
736 I->replaceAllUsesWith(V);
737 I->eraseFromParent();
738 RemoveFromWorklist(I, Worklist);
742 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
743 /// information, and remove any dead successors it has.
745 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
746 std::vector<Instruction*> &Worklist) {
747 if (pred_begin(BB) != pred_end(BB)) {
748 // This block isn't dead, since an edge to BB was just removed, see if there
749 // are any easy simplifications we can do now.
750 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
751 // If it has one pred, fold phi nodes in BB.
752 while (isa<PHINode>(BB->begin()))
753 ReplaceUsesOfWith(BB->begin(),
754 cast<PHINode>(BB->begin())->getIncomingValue(0),
757 // If this is the header of a loop and the only pred is the latch, we now
758 // have an unreachable loop.
759 if (Loop *L = LI->getLoopFor(BB))
760 if (L->getHeader() == BB && L->contains(Pred)) {
761 // Remove the branch from the latch to the header block, this makes
762 // the header dead, which will make the latch dead (because the header
763 // dominates the latch).
764 Pred->getTerminator()->eraseFromParent();
765 new UnreachableInst(Pred);
767 // The loop is now broken, remove it from LI.
768 RemoveLoopFromHierarchy(L);
770 // Reprocess the header, which now IS dead.
771 RemoveBlockIfDead(BB, Worklist);
775 // If pred ends in a uncond branch, add uncond branch to worklist so that
776 // the two blocks will get merged.
777 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
778 if (BI->isUnconditional())
779 Worklist.push_back(BI);
784 DEBUG(std::cerr << "Nuking dead block: " << *BB);
786 // Remove the instructions in the basic block from the worklist.
787 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
788 RemoveFromWorklist(I, Worklist);
790 // Anything that uses the instructions in this basic block should have their
791 // uses replaced with undefs.
793 I->replaceAllUsesWith(UndefValue::get(I->getType()));
796 // If this is the edge to the header block for a loop, remove the loop and
797 // promote all subloops.
798 if (Loop *BBLoop = LI->getLoopFor(BB)) {
799 if (BBLoop->getLoopLatch() == BB)
800 RemoveLoopFromHierarchy(BBLoop);
803 // Remove the block from the loop info, which removes it from any loops it
808 // Remove phi node entries in successors for this block.
809 TerminatorInst *TI = BB->getTerminator();
810 std::vector<BasicBlock*> Succs;
811 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
812 Succs.push_back(TI->getSuccessor(i));
813 TI->getSuccessor(i)->removePredecessor(BB);
816 // Unique the successors, remove anything with multiple uses.
817 std::sort(Succs.begin(), Succs.end());
818 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
820 // Remove the basic block, including all of the instructions contained in it.
821 BB->eraseFromParent();
823 // Remove successor blocks here that are not dead, so that we know we only
824 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
825 // then getting removed before we revisit them, which is badness.
827 for (unsigned i = 0; i != Succs.size(); ++i)
828 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
829 // One exception is loop headers. If this block was the preheader for a
830 // loop, then we DO want to visit the loop so the loop gets deleted.
831 // We know that if the successor is a loop header, that this loop had to
832 // be the preheader: the case where this was the latch block was handled
833 // above and headers can only have two predecessors.
834 if (!LI->isLoopHeader(Succs[i])) {
835 Succs.erase(Succs.begin()+i);
840 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
841 RemoveBlockIfDead(Succs[i], Worklist);
844 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
845 /// become unwrapped, either because the backedge was deleted, or because the
846 /// edge into the header was removed. If the edge into the header from the
847 /// latch block was removed, the loop is unwrapped but subloops are still alive,
848 /// so they just reparent loops. If the loops are actually dead, they will be
850 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
851 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
852 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
853 // they are now all in it.
854 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
856 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
857 LI->changeLoopFor(*I, ParentLoop);
859 // Remove the loop from its parent loop.
860 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
862 assert(I != E && "Couldn't find loop");
864 ParentLoop->removeChildLoop(I);
869 // Move all subloops into the parent loop.
870 while (L->begin() != L->end())
871 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
873 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
874 // they no longer in a loop at all.
876 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
877 // Don't change blocks in subloops.
878 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
879 LI->removeBlock(L->getBlocks()[i]);
884 // Remove the loop from the top-level LoopInfo object.
885 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
886 assert(I != E && "Couldn't find loop");
893 // Move all of the subloops to the top-level.
894 while (L->begin() != L->end())
895 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
899 RemoveLoopFromWorklist(L);
904 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
905 // the value specified by Val in the specified loop, or we know it does NOT have
906 // that value. Rewrite any uses of LIC or of properties correlated to it.
907 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
910 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
912 // FIXME: Support correlated properties, like:
919 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
920 // selects, switches.
921 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
922 std::vector<Instruction*> Worklist;
924 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
925 // in the loop with the appropriate one directly.
926 if (IsEqual || isa<ConstantBool>(Val)) {
931 Replacement = ConstantBool::get(!cast<ConstantBool>(Val)->getValue());
933 for (unsigned i = 0, e = Users.size(); i != e; ++i)
934 if (Instruction *U = cast<Instruction>(Users[i])) {
935 if (!L->contains(U->getParent()))
937 U->replaceUsesOfWith(LIC, Replacement);
938 Worklist.push_back(U);
941 // Otherwise, we don't know the precise value of LIC, but we do know that it
942 // is certainly NOT "Val". As such, simplify any uses in the loop that we
943 // can. This case occurs when we unswitch switch statements.
944 for (unsigned i = 0, e = Users.size(); i != e; ++i)
945 if (Instruction *U = cast<Instruction>(Users[i])) {
946 if (!L->contains(U->getParent()))
949 Worklist.push_back(U);
951 // If we know that LIC is not Val, use this info to simplify code.
952 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
953 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
954 if (SI->getCaseValue(i) == Val) {
955 // Found a dead case value. Don't remove PHI nodes in the
956 // successor if they become single-entry, those PHI nodes may
957 // be in the Users list.
958 SI->getSuccessor(i)->removePredecessor(SI->getParent(), true);
965 // TODO: We could do other simplifications, for example, turning
966 // LIC == Val -> false.
970 SimplifyCode(Worklist);
973 /// SimplifyCode - Okay, now that we have simplified some instructions in the
974 /// loop, walk over it and constant prop, dce, and fold control flow where
975 /// possible. Note that this is effectively a very simple loop-structure-aware
976 /// optimizer. During processing of this loop, L could very well be deleted, so
977 /// it must not be used.
979 /// FIXME: When the loop optimizer is more mature, separate this out to a new
982 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
983 while (!Worklist.empty()) {
984 Instruction *I = Worklist.back();
987 // Simple constant folding.
988 if (Constant *C = ConstantFoldInstruction(I)) {
989 ReplaceUsesOfWith(I, C, Worklist);
994 if (isInstructionTriviallyDead(I)) {
995 DEBUG(std::cerr << "Remove dead instruction '" << *I);
997 // Add uses to the worklist, which may be dead now.
998 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
999 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1000 Worklist.push_back(Use);
1001 I->eraseFromParent();
1002 RemoveFromWorklist(I, Worklist);
1007 // Special case hacks that appear commonly in unswitched code.
1008 switch (I->getOpcode()) {
1009 case Instruction::Select:
1010 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
1011 ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
1015 case Instruction::And:
1016 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1017 cast<BinaryOperator>(I)->swapOperands();
1018 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1019 if (CB->getValue()) // X & 1 -> X
1020 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1022 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1026 case Instruction::Or:
1027 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1028 cast<BinaryOperator>(I)->swapOperands();
1029 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1030 if (CB->getValue()) // X | 1 -> 1
1031 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1033 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1037 case Instruction::Br: {
1038 BranchInst *BI = cast<BranchInst>(I);
1039 if (BI->isUnconditional()) {
1040 // If BI's parent is the only pred of the successor, fold the two blocks
1042 BasicBlock *Pred = BI->getParent();
1043 BasicBlock *Succ = BI->getSuccessor(0);
1044 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1045 if (!SinglePred) continue; // Nothing to do.
1046 assert(SinglePred == Pred && "CFG broken");
1048 DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- "
1049 << Succ->getName() << "\n");
1051 // Resolve any single entry PHI nodes in Succ.
1052 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1053 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1055 // Move all of the successor contents from Succ to Pred.
1056 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1058 BI->eraseFromParent();
1059 RemoveFromWorklist(BI, Worklist);
1061 // If Succ has any successors with PHI nodes, update them to have
1062 // entries coming from Pred instead of Succ.
1063 Succ->replaceAllUsesWith(Pred);
1065 // Remove Succ from the loop tree.
1066 LI->removeBlock(Succ);
1067 Succ->eraseFromParent();
1069 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
1070 // Conditional branch. Turn it into an unconditional branch, then
1071 // remove dead blocks.
1072 break; // FIXME: Enable.
1074 DEBUG(std::cerr << "Folded branch: " << *BI);
1075 BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue());
1076 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue());
1077 DeadSucc->removePredecessor(BI->getParent(), true);
1078 Worklist.push_back(new BranchInst(LiveSucc, BI));
1079 BI->eraseFromParent();
1080 RemoveFromWorklist(BI, Worklist);
1083 RemoveBlockIfDead(DeadSucc, Worklist);