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/Support/Debug.h"
40 #include "llvm/Support/CommandLine.h"
47 Statistic<> NumUnswitched("loop-unswitch", "Number of loops unswitched");
49 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
50 cl::init(10), cl::Hidden);
52 class LoopUnswitch : public FunctionPass {
53 LoopInfo *LI; // Loop information
55 virtual bool runOnFunction(Function &F);
56 bool visitLoop(Loop *L);
58 /// This transformation requires natural loop information & requires that
59 /// loop preheaders be inserted into the CFG...
61 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 AU.addRequiredID(LoopSimplifyID);
63 AU.addPreservedID(LoopSimplifyID);
64 AU.addRequired<LoopInfo>();
65 AU.addPreserved<LoopInfo>();
69 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
70 void VersionLoop(Value *LIC, Loop *L, Loop *&Out1, Loop *&Out2);
71 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
72 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, bool Val);
73 void UnswitchTrivialCondition(Loop *L, Value *Cond, bool EntersLoopOnCond,
74 BasicBlock *ExitBlock);
76 RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
79 FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
81 bool LoopUnswitch::runOnFunction(Function &F) {
83 LI = &getAnalysis<LoopInfo>();
85 // Transform all the top-level loops. Copy the loop list so that the child
86 // can update the loop tree if it needs to delete the loop.
87 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
88 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
89 Changed |= visitLoop(SubLoops[i]);
95 /// LoopValuesUsedOutsideLoop - Return true if there are any values defined in
96 /// the loop that are used by instructions outside of it.
97 static bool LoopValuesUsedOutsideLoop(Loop *L) {
98 // We will be doing lots of "loop contains block" queries. Loop::contains is
99 // linear time, use a set to speed this up.
100 std::set<BasicBlock*> LoopBlocks;
102 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
104 LoopBlocks.insert(*BB);
106 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
108 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
109 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
111 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
112 if (!LoopBlocks.count(UserBB))
119 /// FindTrivialLoopExitBlock - We know that we have a branch from the loop
120 /// header to the specified latch block. See if one of the successors of the
121 /// latch block is an exit, and if so what block it is.
122 static BasicBlock *FindTrivialLoopExitBlock(Loop *L, BasicBlock *Latch) {
123 BasicBlock *Header = L->getHeader();
124 BranchInst *LatchBranch = dyn_cast<BranchInst>(Latch->getTerminator());
125 if (!LatchBranch || !LatchBranch->isConditional()) return 0;
127 // Simple case, the latch block is a conditional branch. The target that
128 // doesn't go to the loop header is our block if it is not in the loop.
129 if (LatchBranch->getSuccessor(0) == Header) {
130 if (L->contains(LatchBranch->getSuccessor(1))) return false;
131 return LatchBranch->getSuccessor(1);
133 assert(LatchBranch->getSuccessor(1) == Header);
134 if (L->contains(LatchBranch->getSuccessor(0))) return false;
135 return LatchBranch->getSuccessor(0);
140 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
141 /// trivial: that is, that the condition controls whether or not the loop does
142 /// anything at all. If this is a trivial condition, unswitching produces no
143 /// code duplications (equivalently, it produces a simpler loop and a new empty
144 /// loop, which gets deleted).
146 /// If this is a trivial condition, return ConstantBool::True if the loop body
147 /// runs when the condition is true, False if the loop body executes when the
148 /// condition is false. Otherwise, return null to indicate a complex condition.
149 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond,
150 bool *CondEntersLoop = 0,
151 BasicBlock **LoopExit = 0) {
152 BasicBlock *Header = L->getHeader();
153 BranchInst *HeaderTerm = dyn_cast<BranchInst>(Header->getTerminator());
155 // If the header block doesn't end with a conditional branch on Cond, we can't
157 if (!HeaderTerm || !HeaderTerm->isConditional() ||
158 HeaderTerm->getCondition() != Cond)
161 // Check to see if the conditional branch goes to the latch block. If not,
162 // it's not trivial. This also determines the value of Cond that will execute
164 BasicBlock *Latch = L->getLoopLatch();
165 if (HeaderTerm->getSuccessor(1) == Latch) {
166 if (CondEntersLoop) *CondEntersLoop = true;
167 } else if (HeaderTerm->getSuccessor(0) == Latch)
168 if (CondEntersLoop) *CondEntersLoop = false;
170 return false; // Doesn't branch to latch block.
172 // The latch block must end with a conditional branch where one edge goes to
173 // the header (this much we know) and one edge goes OUT of the loop.
174 BasicBlock *LoopExitBlock = FindTrivialLoopExitBlock(L, Latch);
175 if (!LoopExitBlock) return 0;
176 if (LoopExit) *LoopExit = LoopExitBlock;
178 // We already know that nothing uses any scalar values defined inside of this
179 // loop. As such, we just have to check to see if this loop will execute any
180 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
181 // part of the loop that the code *would* execute.
182 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
183 if (I->mayWriteToMemory())
185 for (BasicBlock::iterator I = Latch->begin(), E = Latch->end(); I != E; ++I)
186 if (I->mayWriteToMemory())
191 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
192 /// we choose to unswitch the specified loop on the specified value.
194 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
195 // If the condition is trivial, always unswitch. There is no code growth for
197 if (IsTrivialUnswitchCondition(L, LIC))
201 // FIXME: this is brain dead. It should take into consideration code
203 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
206 // Do not include empty blocks in the cost calculation. This happen due to
207 // loop canonicalization and will be removed.
208 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
211 // Count basic blocks.
218 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
219 /// invariant in the loop, or has an invariant piece, return the invariant.
220 /// Otherwise, return null.
221 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
222 // Constants should be folded, not unswitched on!
223 if (isa<Constant>(Cond)) return false;
225 // TODO: Handle: br (VARIANT|INVARIANT).
226 // TODO: Hoist simple expressions out of loops.
227 if (L->isLoopInvariant(Cond)) return Cond;
229 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
230 if (BO->getOpcode() == Instruction::And ||
231 BO->getOpcode() == Instruction::Or) {
232 // If either the left or right side is invariant, we can unswitch on this,
233 // which will cause the branch to go away in one loop and the condition to
234 // simplify in the other one.
235 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
237 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
244 bool LoopUnswitch::visitLoop(Loop *L) {
245 bool Changed = false;
247 // Recurse through all subloops before we process this loop. Copy the loop
248 // list so that the child can update the loop tree if it needs to delete the
250 std::vector<Loop*> SubLoops(L->begin(), L->end());
251 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
252 Changed |= visitLoop(SubLoops[i]);
254 // Loop over all of the basic blocks in the loop. If we find an interior
255 // block that is branching on a loop-invariant condition, we can unswitch this
257 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
259 TerminatorInst *TI = (*I)->getTerminator();
260 // FIXME: Handle invariant select instructions.
262 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
263 if (!isa<Constant>(SI) && L->isLoopInvariant(SI->getCondition()))
264 DEBUG(std::cerr << "TODO: Implement unswitching 'switch' loop %"
265 << L->getHeader()->getName() << ", cost = "
266 << L->getBlocks().size() << "\n" << **I);
270 BranchInst *BI = dyn_cast<BranchInst>(TI);
273 // If this isn't branching on an invariant condition, we can't unswitch it.
274 if (!BI->isConditional())
277 // See if this, or some part of it, is loop invariant. If so, we can
278 // unswitch on it if we desire.
279 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
280 if (LoopCond == 0) continue;
282 // Check to see if it would be profitable to unswitch this loop.
283 if (getLoopUnswitchCost(L, LoopCond) > Threshold) {
284 // FIXME: this should estimate growth by the amount of code shared by the
285 // resultant unswitched loops. This should have no code growth:
286 // for () { if (iv) {...} }
287 // as one copy of the loop will be empty.
289 DEBUG(std::cerr << "NOT unswitching loop %"
290 << L->getHeader()->getName() << ", cost too high: "
291 << L->getBlocks().size() << "\n");
295 // If this loop has live-out values, we can't unswitch it. We need something
296 // like loop-closed SSA form in order to know how to insert PHI nodes for
298 if (LoopValuesUsedOutsideLoop(L)) {
299 DEBUG(std::cerr << "NOT unswitching loop %"
300 << L->getHeader()->getName()
301 << ", a loop value is used outside loop!\n");
305 //std::cerr << "BEFORE:\n"; LI->dump();
306 Loop *NewLoop1 = 0, *NewLoop2 = 0;
308 // If this is a trivial condition to unswitch (which results in no code
309 // duplication), do it now.
310 bool EntersLoopOnCond;
311 BasicBlock *ExitBlock;
312 if (IsTrivialUnswitchCondition(L, LoopCond, &EntersLoopOnCond, &ExitBlock)){
313 UnswitchTrivialCondition(L, LoopCond, EntersLoopOnCond, ExitBlock);
316 VersionLoop(LoopCond, L, NewLoop1, NewLoop2);
319 //std::cerr << "AFTER:\n"; LI->dump();
321 // Try to unswitch each of our new loops now!
322 if (NewLoop1) visitLoop(NewLoop1);
323 if (NewLoop2) visitLoop(NewLoop2);
330 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
331 TerminatorInst *LatchTerm = BB->getTerminator();
332 unsigned SuccNum = 0;
333 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
334 assert(i != e && "Didn't find edge?");
335 if (LatchTerm->getSuccessor(i) == Succ) {
341 // If this is a critical edge, let SplitCriticalEdge do it.
342 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
343 return LatchTerm->getSuccessor(SuccNum);
345 // If the edge isn't critical, then BB has a single successor or Succ has a
346 // single pred. Split the block.
347 BasicBlock *BlockToSplit;
348 BasicBlock::iterator SplitPoint;
349 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
350 // If the successor only has a single pred, split the top of the successor
352 assert(SP == BB && "CFG broken");
354 SplitPoint = Succ->begin();
356 // Otherwise, if BB has a single successor, split it at the bottom of the
358 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
359 "Should have a single succ!");
361 SplitPoint = BB->getTerminator();
365 BlockToSplit->splitBasicBlock(SplitPoint,
366 BlockToSplit->getName()+".tail");
367 // New now lives in whichever loop that BB used to.
368 if (Loop *L = LI->getLoopFor(BlockToSplit))
369 L->addBasicBlockToLoop(New, *LI);
375 // RemapInstruction - Convert the instruction operands from referencing the
376 // current values into those specified by ValueMap.
378 static inline void RemapInstruction(Instruction *I,
379 std::map<const Value *, Value*> &ValueMap) {
380 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
381 Value *Op = I->getOperand(op);
382 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
383 if (It != ValueMap.end()) Op = It->second;
384 I->setOperand(op, Op);
388 /// CloneLoop - Recursively clone the specified loop and all of its children,
389 /// mapping the blocks with the specified map.
390 static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
392 Loop *New = new Loop();
395 PL->addChildLoop(New);
397 LI->addTopLevelLoop(New);
399 // Add all of the blocks in L to the new loop.
400 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
402 if (LI->getLoopFor(*I) == L)
403 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
405 // Add all of the subloops to the new loop.
406 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
407 CloneLoop(*I, New, VM, LI);
412 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
413 /// condition in it (a cond branch from its header block to its latch block,
414 /// where the path through the loop that doesn't execute its body has no
415 /// side-effects), unswitch it. This doesn't involve any code duplication, just
416 /// moving the conditional branch outside of the loop and updating loop info.
417 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
419 BasicBlock *ExitBlock) {
420 DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
421 << L->getHeader()->getName() << " [" << L->getBlocks().size()
422 << " blocks] in Function " << L->getHeader()->getParent()->getName()
423 << " on cond:" << *Cond << "\n");
425 // First step, split the preheader, so that we know that there is a safe place
426 // to insert the conditional branch. We will change 'OrigPH' to have a
427 // conditional branch on Cond.
428 BasicBlock *OrigPH = L->getLoopPreheader();
429 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
431 // Now that we have a place to insert the conditional branch, create a place
432 // to branch to: this is the exit block out of the loop that we should
435 // Split this edge now, so that the loop maintains its exit block.
436 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
437 BasicBlock *NewExit = SplitEdge(L->getLoopLatch(), ExitBlock);
438 assert(NewExit != ExitBlock && "Edge not split!");
440 // Okay, now we have a position to branch from and a position to branch to,
441 // insert the new conditional branch.
442 new BranchInst(EnterOnCond ? NewPH : NewExit, EnterOnCond ? NewExit : NewPH,
443 Cond, OrigPH->getTerminator());
444 OrigPH->getTerminator()->eraseFromParent();
446 // Now that we know that the loop is never entered when this condition is a
447 // particular value, rewrite the loop with this info. We know that this will
448 // at least eliminate the old branch.
449 RewriteLoopBodyWithConditionConstant(L, Cond, EnterOnCond);
455 /// VersionLoop - We determined that the loop is profitable to unswitch and
456 /// contains a branch on a loop invariant condition. Split it into loop
457 /// versions and test the condition outside of either loop. Return the loops
458 /// created as Out1/Out2.
459 void LoopUnswitch::VersionLoop(Value *LIC, Loop *L, Loop *&Out1, Loop *&Out2) {
460 Function *F = L->getHeader()->getParent();
462 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
463 << L->getHeader()->getName() << " [" << L->getBlocks().size()
464 << " blocks] in Function " << F->getName()
465 << " on cond:" << *LIC << "\n");
467 // LoopBlocks contains all of the basic blocks of the loop, including the
468 // preheader of the loop, the body of the loop, and the exit blocks of the
469 // loop, in that order.
470 std::vector<BasicBlock*> LoopBlocks;
472 // First step, split the preheader and exit blocks, and add these blocks to
473 // the LoopBlocks list.
474 BasicBlock *OrigPreheader = L->getLoopPreheader();
475 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
477 // We want the loop to come after the preheader, but before the exit blocks.
478 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
480 std::vector<BasicBlock*> ExitBlocks;
481 L->getExitBlocks(ExitBlocks);
482 std::sort(ExitBlocks.begin(), ExitBlocks.end());
483 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
485 // Split all of the edges from inside the loop to their exit blocks. This
486 // unswitching trivial: no phi nodes to update.
487 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
488 BasicBlock *ExitBlock = ExitBlocks[i];
489 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
491 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
492 assert(L->contains(Preds[j]) &&
493 "All preds of loop exit blocks must be the same loop!");
494 SplitEdge(Preds[j], ExitBlock);
498 // The exit blocks may have been changed due to edge splitting, recompute.
500 L->getExitBlocks(ExitBlocks);
501 std::sort(ExitBlocks.begin(), ExitBlocks.end());
502 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
505 // Add exit blocks to the loop blocks.
506 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
508 // Next step, clone all of the basic blocks that make up the loop (including
509 // the loop preheader and exit blocks), keeping track of the mapping between
510 // the instructions and blocks.
511 std::vector<BasicBlock*> NewBlocks;
512 NewBlocks.reserve(LoopBlocks.size());
513 std::map<const Value*, Value*> ValueMap;
514 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
515 NewBlocks.push_back(CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F));
516 ValueMap[LoopBlocks[i]] = NewBlocks.back(); // Keep the BB mapping.
519 // Splice the newly inserted blocks into the function right before the
520 // original preheader.
521 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
522 NewBlocks[0], F->end());
524 // Now we create the new Loop object for the versioned loop.
525 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
526 if (Loop *Parent = L->getParentLoop()) {
527 // Make sure to add the cloned preheader and exit blocks to the parent loop
529 Parent->addBasicBlockToLoop(NewBlocks[0], *LI);
530 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
531 Parent->addBasicBlockToLoop(cast<BasicBlock>(ValueMap[ExitBlocks[i]]),
535 // Rewrite the code to refer to itself.
536 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
537 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
538 E = NewBlocks[i]->end(); I != E; ++I)
539 RemapInstruction(I, ValueMap);
541 // Rewrite the original preheader to select between versions of the loop.
542 assert(isa<BranchInst>(OrigPreheader->getTerminator()) &&
543 cast<BranchInst>(OrigPreheader->getTerminator())->isUnconditional() &&
544 OrigPreheader->getTerminator()->getSuccessor(0) == LoopBlocks[0] &&
545 "Preheader splitting did not work correctly!");
546 // Remove the unconditional branch to LoopBlocks[0].
547 OrigPreheader->getInstList().pop_back();
549 // Insert a conditional branch on LIC to the two preheaders. The original
550 // code is the true version and the new code is the false version.
551 new BranchInst(LoopBlocks[0], NewBlocks[0], LIC, OrigPreheader);
553 // Now we rewrite the original code to know that the condition is true and the
554 // new code to know that the condition is false.
555 RewriteLoopBodyWithConditionConstant(L, LIC, true);
556 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, false);
562 // RewriteLoopBodyWithConditionConstant - We know that the boolean value LIC has
563 // the value specified by Val in the specified loop. Rewrite any uses of LIC or
564 // of properties correlated to it.
565 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
567 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
568 // FIXME: Support correlated properties, like:
574 ConstantBool *BoolVal = ConstantBool::get(Val);
576 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
577 // selects, switches.
578 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
579 for (unsigned i = 0, e = Users.size(); i != e; ++i)
580 if (Instruction *U = cast<Instruction>(Users[i]))
581 if (L->contains(U->getParent()))
582 U->replaceUsesOfWith(LIC, BoolVal);