1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms loops that contain branches on loop-invariant conditions
11 // to have multiple loops. For example, it turns the left into the right code:
20 // This can increase the size of the code exponentially (doubling it every time
21 // a loop is unswitched) so we only unswitch if the resultant code will be
22 // smaller than a threshold.
24 // This pass expects LICM to be run before it to hoist invariant conditions out
25 // of the loop, to make the unswitching opportunity obvious.
27 //===----------------------------------------------------------------------===//
29 #define DEBUG_TYPE "loop-unswitch"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Constants.h"
32 #include "llvm/DerivedTypes.h"
33 #include "llvm/Function.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Analysis/ConstantFolding.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Analysis/Dominators.h"
39 #include "llvm/Transforms/Utils/Cloning.h"
40 #include "llvm/Transforms/Utils/Local.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/PostOrderIterator.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/Debug.h"
52 STATISTIC(NumBranches, "Number of branches unswitched");
53 STATISTIC(NumSwitches, "Number of switches unswitched");
54 STATISTIC(NumSelects , "Number of selects unswitched");
55 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
56 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
60 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
61 cl::init(10), cl::Hidden);
63 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
64 LoopInfo *LI; // Loop information
67 // LoopProcessWorklist - Used to check if second loop needs processing
68 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
69 std::vector<Loop*> LoopProcessWorklist;
70 SmallPtrSet<Value *,8> UnswitchedVals;
74 static char ID; // Pass ID, replacement for typeid
75 LoopUnswitch(bool Os = false) :
76 LoopPass((intptr_t)&ID), OptimizeForSize(Os) {}
78 bool runOnLoop(Loop *L, LPPassManager &LPM);
80 /// This transformation requires natural loop information & requires that
81 /// loop preheaders be inserted into the CFG...
83 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.addRequiredID(LoopSimplifyID);
85 AU.addPreservedID(LoopSimplifyID);
86 AU.addPreserved<DominatorTree>();
87 AU.addPreserved<DominanceFrontier>();
88 AU.addRequired<LoopInfo>();
89 AU.addPreserved<LoopInfo>();
90 AU.addRequiredID(LCSSAID);
91 AU.addPreservedID(LCSSAID);
95 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
97 void RemoveLoopFromWorklist(Loop *L) {
98 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
99 LoopProcessWorklist.end(), L);
100 if (I != LoopProcessWorklist.end())
101 LoopProcessWorklist.erase(I);
104 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
105 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
106 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
107 BasicBlock *ExitBlock);
108 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
110 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
111 Constant *Val, bool isEqual);
113 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
114 BasicBlock *TrueDest,
115 BasicBlock *FalseDest,
116 Instruction *InsertPt);
118 void SimplifyCode(std::vector<Instruction*> &Worklist);
119 void RemoveBlockIfDead(BasicBlock *BB,
120 std::vector<Instruction*> &Worklist);
121 void RemoveLoopFromHierarchy(Loop *L);
123 char LoopUnswitch::ID = 0;
124 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
127 LoopPass *llvm::createLoopUnswitchPass(bool Os) {
128 return new LoopUnswitch(Os);
131 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
132 /// invariant in the loop, or has an invariant piece, return the invariant.
133 /// Otherwise, return null.
134 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
135 // Constants should be folded, not unswitched on!
136 if (isa<Constant>(Cond)) return false;
138 // TODO: Handle: br (VARIANT|INVARIANT).
139 // TODO: Hoist simple expressions out of loops.
140 if (L->isLoopInvariant(Cond)) return Cond;
142 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
143 if (BO->getOpcode() == Instruction::And ||
144 BO->getOpcode() == Instruction::Or) {
145 // If either the left or right side is invariant, we can unswitch on this,
146 // which will cause the branch to go away in one loop and the condition to
147 // simplify in the other one.
148 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
150 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
157 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
158 assert(L->isLCSSAForm());
159 LI = &getAnalysis<LoopInfo>();
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, ConstantInt::getTrue(),
182 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
183 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
184 if (LoopCond && SI->getNumCases() > 1) {
185 // Find a value to unswitch on:
186 // FIXME: this should chose the most expensive case!
187 Constant *UnswitchVal = SI->getCaseValue(1);
188 // Do not process same value again and again.
189 if (!UnswitchedVals.insert(UnswitchVal))
192 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
199 // Scan the instructions to check for unswitchable values.
200 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
202 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
203 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
204 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
212 assert(L->isLCSSAForm());
217 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
218 /// 1. Exit the loop with no side effects.
219 /// 2. Branch to the latch block with no side-effects.
221 /// If these conditions are true, we return true and set ExitBB to the block we
224 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
226 std::set<BasicBlock*> &Visited) {
227 if (!Visited.insert(BB).second) {
228 // Already visited and Ok, end of recursion.
230 } else if (!L->contains(BB)) {
231 // Otherwise, this is a loop exit, this is fine so long as this is the
233 if (ExitBB != 0) return false;
238 // Otherwise, this is an unvisited intra-loop node. Check all successors.
239 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
240 // Check to see if the successor is a trivial loop exit.
241 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
245 // Okay, everything after this looks good, check to make sure that this block
246 // doesn't include any side effects.
247 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
248 if (I->mayWriteToMemory())
254 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
255 /// leads to an exit from the specified loop, and has no side-effects in the
256 /// process. If so, return the block that is exited to, otherwise return null.
257 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
258 std::set<BasicBlock*> Visited;
259 Visited.insert(L->getHeader()); // Branches to header are ok.
260 BasicBlock *ExitBB = 0;
261 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
266 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
267 /// trivial: that is, that the condition controls whether or not the loop does
268 /// anything at all. If this is a trivial condition, unswitching produces no
269 /// code duplications (equivalently, it produces a simpler loop and a new empty
270 /// loop, which gets deleted).
272 /// If this is a trivial condition, return true, otherwise return false. When
273 /// returning true, this sets Cond and Val to the condition that controls the
274 /// trivial condition: when Cond dynamically equals Val, the loop is known to
275 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
278 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
279 BasicBlock **LoopExit = 0) {
280 BasicBlock *Header = L->getHeader();
281 TerminatorInst *HeaderTerm = Header->getTerminator();
283 BasicBlock *LoopExitBB = 0;
284 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
285 // If the header block doesn't end with a conditional branch on Cond, we
287 if (!BI->isConditional() || BI->getCondition() != Cond)
290 // Check to see if a successor of the branch is guaranteed to go to the
291 // latch block or exit through a one exit block without having any
292 // side-effects. If so, determine the value of Cond that causes it to do
294 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
295 if (Val) *Val = ConstantInt::getTrue();
296 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
297 if (Val) *Val = ConstantInt::getFalse();
299 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
300 // If this isn't a switch on Cond, we can't handle it.
301 if (SI->getCondition() != Cond) return false;
303 // Check to see if a successor of the switch is guaranteed to go to the
304 // latch block or exit through a one exit block without having any
305 // side-effects. If so, determine the value of Cond that causes it to do
306 // this. Note that we can't trivially unswitch on the default case.
307 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
308 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
309 // Okay, we found a trivial case, remember the value that is trivial.
310 if (Val) *Val = SI->getCaseValue(i);
315 // If we didn't find a single unique LoopExit block, or if the loop exit block
316 // contains phi nodes, this isn't trivial.
317 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
318 return false; // Can't handle this.
320 if (LoopExit) *LoopExit = LoopExitBB;
322 // We already know that nothing uses any scalar values defined inside of this
323 // loop. As such, we just have to check to see if this loop will execute any
324 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
325 // part of the loop that the code *would* execute. We already checked the
326 // tail, check the header now.
327 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
328 if (I->mayWriteToMemory())
333 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
334 /// we choose to unswitch the specified loop on the specified value.
336 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
337 // If the condition is trivial, always unswitch. There is no code growth for
339 if (IsTrivialUnswitchCondition(L, LIC))
342 // FIXME: This is really overly conservative. However, more liberal
343 // estimations have thus far resulted in excessive unswitching, which is bad
344 // both in compile time and in code size. This should be replaced once
345 // someone figures out how a good estimation.
346 return L->getBlocks().size();
349 // FIXME: this is brain dead. It should take into consideration code
351 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
354 // Do not include empty blocks in the cost calculation. This happen due to
355 // loop canonicalization and will be removed.
356 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
359 // Count basic blocks.
366 /// UnswitchIfProfitable - We have found that we can unswitch L when
367 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
368 /// unswitch the loop, reprocess the pieces, then return true.
369 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
370 // Check to see if it would be profitable to unswitch this loop.
371 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
373 // Do not do non-trivial unswitch while optimizing for size.
374 if (Cost && OptimizeForSize)
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 // RemapInstruction - Convert the instruction operands from referencing the
401 // current values into those specified by ValueMap.
403 static inline void RemapInstruction(Instruction *I,
404 DenseMap<const Value *, Value*> &ValueMap) {
405 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
406 Value *Op = I->getOperand(op);
407 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
408 if (It != ValueMap.end()) Op = It->second;
409 I->setOperand(op, Op);
413 // CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator Info.
414 // If Orig is in Loop then find and use Orig dominator's cloned block as NewBB
416 void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig, Loop *L,
417 DominatorTree *DT, DominanceFrontier *DF,
418 DenseMap<const Value*, Value*> &VM) {
420 DomTreeNode *OrigNode = DT->getNode(Orig);
423 BasicBlock *OrigIDom = OrigNode->getBlock();
424 BasicBlock *NewIDom = OrigIDom;
425 if (L->contains(OrigIDom)) {
426 if (!DT->getNode(OrigIDom))
427 CloneDomInfo(NewIDom, OrigIDom, L, DT, DF, VM);
428 NewIDom = cast<BasicBlock>(VM[OrigIDom]);
430 if (NewBB == NewIDom) {
431 DT->addNewBlock(NewBB, OrigIDom);
432 DT->changeImmediateDominator(NewBB, NewIDom);
434 DT->addNewBlock(NewBB, NewIDom);
436 DominanceFrontier::DomSetType NewDFSet;
438 DominanceFrontier::iterator DFI = DF->find(Orig);
439 if ( DFI != DF->end()) {
440 DominanceFrontier::DomSetType S = DFI->second;
441 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
445 NewDFSet.insert(cast<BasicBlock>(VM[Orig]));
450 DF->addBasicBlock(NewBB, NewDFSet);
454 /// CloneLoop - Recursively clone the specified loop and all of its children,
455 /// mapping the blocks with the specified map.
456 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
457 LoopInfo *LI, LPPassManager *LPM) {
458 Loop *New = new Loop();
460 LPM->insertLoop(New, PL);
462 // Add all of the blocks in L to the new loop.
463 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
465 if (LI->getLoopFor(*I) == L)
466 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
468 // Add all of the subloops to the new loop.
469 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
470 CloneLoop(*I, New, VM, LI, LPM);
475 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
476 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
477 /// code immediately before InsertPt.
478 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
479 BasicBlock *TrueDest,
480 BasicBlock *FalseDest,
481 Instruction *InsertPt) {
482 // Insert a conditional branch on LIC to the two preheaders. The original
483 // code is the true version and the new code is the false version.
484 Value *BranchVal = LIC;
485 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
486 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
487 else if (Val != ConstantInt::getTrue())
488 // We want to enter the new loop when the condition is true.
489 std::swap(TrueDest, FalseDest);
491 // Insert the new branch.
492 BranchInst *BRI = new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
494 // Update dominator info.
495 // BranchVal is a new preheader so it dominates true and false destination
497 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
498 DT->changeImmediateDominator(TrueDest, BRI->getParent());
499 DT->changeImmediateDominator(FalseDest, BRI->getParent());
501 // No need to update DominanceFrontier. BRI->getParent() dominated TrueDest
502 // and FalseDest anyway. Now it immediately dominates them.
506 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
507 /// condition in it (a cond branch from its header block to its latch block,
508 /// where the path through the loop that doesn't execute its body has no
509 /// side-effects), unswitch it. This doesn't involve any code duplication, just
510 /// moving the conditional branch outside of the loop and updating loop info.
511 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
513 BasicBlock *ExitBlock) {
514 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
515 << L->getHeader()->getName() << " [" << L->getBlocks().size()
516 << " blocks] in Function " << L->getHeader()->getParent()->getName()
517 << " on cond: " << *Val << " == " << *Cond << "\n";
519 // First step, split the preheader, so that we know that there is a safe place
520 // to insert the conditional branch. We will change 'OrigPH' to have a
521 // conditional branch on Cond.
522 BasicBlock *OrigPH = L->getLoopPreheader();
523 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader(), this);
525 // Now that we have a place to insert the conditional branch, create a place
526 // to branch to: this is the exit block out of the loop that we should
529 // Split this block now, so that the loop maintains its exit block, and so
530 // that the jump from the preheader can execute the contents of the exit block
531 // without actually branching to it (the exit block should be dominated by the
532 // loop header, not the preheader).
533 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
534 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
536 // Okay, now we have a position to branch from and a position to branch to,
537 // insert the new conditional branch.
538 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
539 OrigPH->getTerminator());
540 OrigPH->getTerminator()->eraseFromParent();
542 // We need to reprocess this loop, it could be unswitched again.
545 // Now that we know that the loop is never entered when this condition is a
546 // particular value, rewrite the loop with this info. We know that this will
547 // at least eliminate the old branch.
548 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
552 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
553 /// equal Val. Split it into loop versions and test the condition outside of
554 /// either loop. Return the loops created as Out1/Out2.
555 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
557 Function *F = L->getHeader()->getParent();
558 DOUT << "loop-unswitch: Unswitching loop %"
559 << L->getHeader()->getName() << " [" << L->getBlocks().size()
560 << " blocks] in Function " << F->getName()
561 << " when '" << *Val << "' == " << *LIC << "\n";
563 // LoopBlocks contains all of the basic blocks of the loop, including the
564 // preheader of the loop, the body of the loop, and the exit blocks of the
565 // loop, in that order.
566 std::vector<BasicBlock*> LoopBlocks;
568 // First step, split the preheader and exit blocks, and add these blocks to
569 // the LoopBlocks list.
570 BasicBlock *OrigPreheader = L->getLoopPreheader();
571 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader(), this));
573 // We want the loop to come after the preheader, but before the exit blocks.
574 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
576 std::vector<BasicBlock*> ExitBlocks;
577 L->getUniqueExitBlocks(ExitBlocks);
579 // Split all of the edges from inside the loop to their exit blocks. Update
580 // the appropriate Phi nodes as we do so.
581 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
582 BasicBlock *ExitBlock = ExitBlocks[i];
583 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
585 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
586 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
587 BasicBlock* StartBlock = Preds[j];
588 BasicBlock* EndBlock;
589 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
590 EndBlock = MiddleBlock;
591 MiddleBlock = EndBlock->getSinglePredecessor();;
593 EndBlock = ExitBlock;
596 std::set<PHINode*> InsertedPHIs;
597 PHINode* OldLCSSA = 0;
598 for (BasicBlock::iterator I = EndBlock->begin();
599 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
600 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
601 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
602 OldLCSSA->getName() + ".us-lcssa",
603 MiddleBlock->getTerminator());
604 NewLCSSA->addIncoming(OldValue, StartBlock);
605 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
607 InsertedPHIs.insert(NewLCSSA);
610 BasicBlock::iterator InsertPt = EndBlock->begin();
611 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
612 for (BasicBlock::iterator I = MiddleBlock->begin();
613 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
615 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
616 OldLCSSA->getName() + ".us-lcssa",
618 OldLCSSA->replaceAllUsesWith(NewLCSSA);
619 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
624 // The exit blocks may have been changed due to edge splitting, recompute.
626 L->getUniqueExitBlocks(ExitBlocks);
628 // Add exit blocks to the loop blocks.
629 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
631 // Next step, clone all of the basic blocks that make up the loop (including
632 // the loop preheader and exit blocks), keeping track of the mapping between
633 // the instructions and blocks.
634 std::vector<BasicBlock*> NewBlocks;
635 NewBlocks.reserve(LoopBlocks.size());
636 DenseMap<const Value*, Value*> ValueMap;
637 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
638 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
639 NewBlocks.push_back(New);
640 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
643 // Update dominator info
644 DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>();
645 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>())
646 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
647 BasicBlock *LBB = LoopBlocks[i];
648 BasicBlock *NBB = NewBlocks[i];
649 CloneDomInfo(NBB, LBB, L, DT, DF, ValueMap);
652 // Splice the newly inserted blocks into the function right before the
653 // original preheader.
654 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
655 NewBlocks[0], F->end());
657 // Now we create the new Loop object for the versioned loop.
658 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
659 Loop *ParentLoop = L->getParentLoop();
661 // Make sure to add the cloned preheader and exit blocks to the parent loop
663 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
666 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
667 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
668 // The new exit block should be in the same loop as the old one.
669 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
670 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
672 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
673 "Exit block should have been split to have one successor!");
674 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
676 // If the successor of the exit block had PHI nodes, add an entry for
679 for (BasicBlock::iterator I = ExitSucc->begin();
680 (PN = dyn_cast<PHINode>(I)); ++I) {
681 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
682 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
683 if (It != ValueMap.end()) V = It->second;
684 PN->addIncoming(V, NewExit);
688 // Rewrite the code to refer to itself.
689 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
690 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
691 E = NewBlocks[i]->end(); I != E; ++I)
692 RemapInstruction(I, ValueMap);
694 // Rewrite the original preheader to select between versions of the loop.
695 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
696 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
697 "Preheader splitting did not work correctly!");
699 // Emit the new branch that selects between the two versions of this loop.
700 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
701 OldBR->eraseFromParent();
703 LoopProcessWorklist.push_back(NewLoop);
706 // Now we rewrite the original code to know that the condition is true and the
707 // new code to know that the condition is false.
708 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
710 // It's possible that simplifying one loop could cause the other to be
711 // deleted. If so, don't simplify it.
712 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
713 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
716 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
718 static void RemoveFromWorklist(Instruction *I,
719 std::vector<Instruction*> &Worklist) {
720 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
722 while (WI != Worklist.end()) {
723 unsigned Offset = WI-Worklist.begin();
725 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
729 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
730 /// program, replacing all uses with V and update the worklist.
731 static void ReplaceUsesOfWith(Instruction *I, Value *V,
732 std::vector<Instruction*> &Worklist) {
733 DOUT << "Replace with '" << *V << "': " << *I;
735 // Add uses to the worklist, which may be dead now.
736 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
737 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
738 Worklist.push_back(Use);
740 // Add users to the worklist which may be simplified now.
741 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
743 Worklist.push_back(cast<Instruction>(*UI));
744 I->replaceAllUsesWith(V);
745 I->eraseFromParent();
746 RemoveFromWorklist(I, Worklist);
750 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
751 /// information, and remove any dead successors it has.
753 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
754 std::vector<Instruction*> &Worklist) {
755 if (pred_begin(BB) != pred_end(BB)) {
756 // This block isn't dead, since an edge to BB was just removed, see if there
757 // are any easy simplifications we can do now.
758 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
759 // If it has one pred, fold phi nodes in BB.
760 while (isa<PHINode>(BB->begin()))
761 ReplaceUsesOfWith(BB->begin(),
762 cast<PHINode>(BB->begin())->getIncomingValue(0),
765 // If this is the header of a loop and the only pred is the latch, we now
766 // have an unreachable loop.
767 if (Loop *L = LI->getLoopFor(BB))
768 if (L->getHeader() == BB && L->contains(Pred)) {
769 // Remove the branch from the latch to the header block, this makes
770 // the header dead, which will make the latch dead (because the header
771 // dominates the latch).
772 Pred->getTerminator()->eraseFromParent();
773 new UnreachableInst(Pred);
775 // The loop is now broken, remove it from LI.
776 RemoveLoopFromHierarchy(L);
778 // Reprocess the header, which now IS dead.
779 RemoveBlockIfDead(BB, Worklist);
783 // If pred ends in a uncond branch, add uncond branch to worklist so that
784 // the two blocks will get merged.
785 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
786 if (BI->isUnconditional())
787 Worklist.push_back(BI);
792 DOUT << "Nuking dead block: " << *BB;
794 // Remove the instructions in the basic block from the worklist.
795 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
796 RemoveFromWorklist(I, Worklist);
798 // Anything that uses the instructions in this basic block should have their
799 // uses replaced with undefs.
801 I->replaceAllUsesWith(UndefValue::get(I->getType()));
804 // If this is the edge to the header block for a loop, remove the loop and
805 // promote all subloops.
806 if (Loop *BBLoop = LI->getLoopFor(BB)) {
807 if (BBLoop->getLoopLatch() == BB)
808 RemoveLoopFromHierarchy(BBLoop);
811 // Remove the block from the loop info, which removes it from any loops it
816 // Remove phi node entries in successors for this block.
817 TerminatorInst *TI = BB->getTerminator();
818 std::vector<BasicBlock*> Succs;
819 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
820 Succs.push_back(TI->getSuccessor(i));
821 TI->getSuccessor(i)->removePredecessor(BB);
824 // Unique the successors, remove anything with multiple uses.
825 std::sort(Succs.begin(), Succs.end());
826 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
828 // Remove the basic block, including all of the instructions contained in it.
829 BB->eraseFromParent();
831 // Remove successor blocks here that are not dead, so that we know we only
832 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
833 // then getting removed before we revisit them, which is badness.
835 for (unsigned i = 0; i != Succs.size(); ++i)
836 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
837 // One exception is loop headers. If this block was the preheader for a
838 // loop, then we DO want to visit the loop so the loop gets deleted.
839 // We know that if the successor is a loop header, that this loop had to
840 // be the preheader: the case where this was the latch block was handled
841 // above and headers can only have two predecessors.
842 if (!LI->isLoopHeader(Succs[i])) {
843 Succs.erase(Succs.begin()+i);
848 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
849 RemoveBlockIfDead(Succs[i], Worklist);
852 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
853 /// become unwrapped, either because the backedge was deleted, or because the
854 /// edge into the header was removed. If the edge into the header from the
855 /// latch block was removed, the loop is unwrapped but subloops are still alive,
856 /// so they just reparent loops. If the loops are actually dead, they will be
858 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
859 LPM->deleteLoopFromQueue(L);
860 RemoveLoopFromWorklist(L);
865 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
866 // the value specified by Val in the specified loop, or we know it does NOT have
867 // that value. Rewrite any uses of LIC or of properties correlated to it.
868 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
871 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
873 // FIXME: Support correlated properties, like:
880 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
881 // selects, switches.
882 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
883 std::vector<Instruction*> Worklist;
885 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
886 // in the loop with the appropriate one directly.
887 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
892 Replacement = ConstantInt::get(Type::Int1Ty,
893 !cast<ConstantInt>(Val)->getZExtValue());
895 for (unsigned i = 0, e = Users.size(); i != e; ++i)
896 if (Instruction *U = cast<Instruction>(Users[i])) {
897 if (!L->contains(U->getParent()))
899 U->replaceUsesOfWith(LIC, Replacement);
900 Worklist.push_back(U);
903 // Otherwise, we don't know the precise value of LIC, but we do know that it
904 // is certainly NOT "Val". As such, simplify any uses in the loop that we
905 // can. This case occurs when we unswitch switch statements.
906 for (unsigned i = 0, e = Users.size(); i != e; ++i)
907 if (Instruction *U = cast<Instruction>(Users[i])) {
908 if (!L->contains(U->getParent()))
911 Worklist.push_back(U);
913 // If we know that LIC is not Val, use this info to simplify code.
914 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
915 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
916 if (SI->getCaseValue(i) == Val) {
917 // Found a dead case value. Don't remove PHI nodes in the
918 // successor if they become single-entry, those PHI nodes may
919 // be in the Users list.
921 // FIXME: This is a hack. We need to keep the successor around
922 // and hooked up so as to preserve the loop structure, because
923 // trying to update it is complicated. So instead we preserve the
924 // loop structure and put the block on an dead code path.
926 BasicBlock* Old = SI->getParent();
927 BasicBlock* Split = SplitBlock(Old, SI, this);
929 Instruction* OldTerm = Old->getTerminator();
930 new BranchInst(Split, SI->getSuccessor(i),
931 ConstantInt::getTrue(), OldTerm);
933 Old->getTerminator()->eraseFromParent();
937 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
938 (PN = dyn_cast<PHINode>(II)); ++II) {
939 Value *InVal = PN->removeIncomingValue(Split, false);
940 PN->addIncoming(InVal, Old);
949 // TODO: We could do other simplifications, for example, turning
950 // LIC == Val -> false.
954 SimplifyCode(Worklist);
957 /// SimplifyCode - Okay, now that we have simplified some instructions in the
958 /// loop, walk over it and constant prop, dce, and fold control flow where
959 /// possible. Note that this is effectively a very simple loop-structure-aware
960 /// optimizer. During processing of this loop, L could very well be deleted, so
961 /// it must not be used.
963 /// FIXME: When the loop optimizer is more mature, separate this out to a new
966 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
967 while (!Worklist.empty()) {
968 Instruction *I = Worklist.back();
971 // Simple constant folding.
972 if (Constant *C = ConstantFoldInstruction(I)) {
973 ReplaceUsesOfWith(I, C, Worklist);
978 if (isInstructionTriviallyDead(I)) {
979 DOUT << "Remove dead instruction '" << *I;
981 // Add uses to the worklist, which may be dead now.
982 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
983 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
984 Worklist.push_back(Use);
985 I->eraseFromParent();
986 RemoveFromWorklist(I, Worklist);
991 // Special case hacks that appear commonly in unswitched code.
992 switch (I->getOpcode()) {
993 case Instruction::Select:
994 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
995 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
999 case Instruction::And:
1000 if (isa<ConstantInt>(I->getOperand(0)) &&
1001 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1002 cast<BinaryOperator>(I)->swapOperands();
1003 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1004 if (CB->getType() == Type::Int1Ty) {
1005 if (CB->isOne()) // X & 1 -> X
1006 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1008 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1012 case Instruction::Or:
1013 if (isa<ConstantInt>(I->getOperand(0)) &&
1014 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1015 cast<BinaryOperator>(I)->swapOperands();
1016 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1017 if (CB->getType() == Type::Int1Ty) {
1018 if (CB->isOne()) // X | 1 -> 1
1019 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1021 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1025 case Instruction::Br: {
1026 BranchInst *BI = cast<BranchInst>(I);
1027 if (BI->isUnconditional()) {
1028 // If BI's parent is the only pred of the successor, fold the two blocks
1030 BasicBlock *Pred = BI->getParent();
1031 BasicBlock *Succ = BI->getSuccessor(0);
1032 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1033 if (!SinglePred) continue; // Nothing to do.
1034 assert(SinglePred == Pred && "CFG broken");
1036 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1037 << Succ->getName() << "\n";
1039 // Resolve any single entry PHI nodes in Succ.
1040 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1041 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1043 // Move all of the successor contents from Succ to Pred.
1044 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1046 BI->eraseFromParent();
1047 RemoveFromWorklist(BI, Worklist);
1049 // If Succ has any successors with PHI nodes, update them to have
1050 // entries coming from Pred instead of Succ.
1051 Succ->replaceAllUsesWith(Pred);
1053 // Remove Succ from the loop tree.
1054 LI->removeBlock(Succ);
1055 Succ->eraseFromParent();
1057 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1058 // Conditional branch. Turn it into an unconditional branch, then
1059 // remove dead blocks.
1060 break; // FIXME: Enable.
1062 DOUT << "Folded branch: " << *BI;
1063 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1064 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1065 DeadSucc->removePredecessor(BI->getParent(), true);
1066 Worklist.push_back(new BranchInst(LiveSucc, BI));
1067 BI->eraseFromParent();
1068 RemoveFromWorklist(BI, Worklist);
1071 RemoveBlockIfDead(DeadSucc, Worklist);