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;
75 static char ID; // Pass ID, replacement for typeid
76 explicit LoopUnswitch(bool Os = false) :
77 LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false) {}
79 bool runOnLoop(Loop *L, LPPassManager &LPM);
80 bool processLoop(Loop *L);
82 /// This transformation requires natural loop information & requires that
83 /// loop preheaders be inserted into the CFG...
85 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequiredID(LoopSimplifyID);
87 AU.addPreservedID(LoopSimplifyID);
88 AU.addRequired<LoopInfo>();
89 AU.addPreserved<LoopInfo>();
90 AU.addRequiredID(LCSSAID);
91 AU.addPreservedID(LCSSAID);
92 AU.addPreserved<DominatorTree>();
93 AU.addPreserved<DominanceFrontier>();
98 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
100 void RemoveLoopFromWorklist(Loop *L) {
101 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
102 LoopProcessWorklist.end(), L);
103 if (I != LoopProcessWorklist.end())
104 LoopProcessWorklist.erase(I);
107 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
108 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
109 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
110 BasicBlock *ExitBlock);
111 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
113 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
114 Constant *Val, bool isEqual);
116 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
117 BasicBlock *TrueDest,
118 BasicBlock *FalseDest,
119 Instruction *InsertPt);
121 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
122 void RemoveBlockIfDead(BasicBlock *BB,
123 std::vector<Instruction*> &Worklist, Loop *l);
124 void RemoveLoopFromHierarchy(Loop *L);
126 char LoopUnswitch::ID = 0;
127 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
130 LoopPass *llvm::createLoopUnswitchPass(bool Os) {
131 return new LoopUnswitch(Os);
134 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
135 /// invariant in the loop, or has an invariant piece, return the invariant.
136 /// Otherwise, return null.
137 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
138 // Constants should be folded, not unswitched on!
139 if (isa<Constant>(Cond)) return false;
141 // TODO: Handle: br (VARIANT|INVARIANT).
142 // TODO: Hoist simple expressions out of loops.
143 if (L->isLoopInvariant(Cond)) return Cond;
145 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
146 if (BO->getOpcode() == Instruction::And ||
147 BO->getOpcode() == Instruction::Or) {
148 // If either the left or right side is invariant, we can unswitch on this,
149 // which will cause the branch to go away in one loop and the condition to
150 // simplify in the other one.
151 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
153 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
160 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
161 LI = &getAnalysis<LoopInfo>();
163 bool Changed = false;
167 Changed |= processLoop(L);
173 /// processLoop - Do actual work and unswitch loop if possible and profitable.
174 bool LoopUnswitch::processLoop(Loop *L) {
175 assert(L->isLCSSAForm());
176 bool Changed = false;
178 // Loop over all of the basic blocks in the loop. If we find an interior
179 // block that is branching on a loop-invariant condition, we can unswitch this
181 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
183 TerminatorInst *TI = (*I)->getTerminator();
184 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
185 // If this isn't branching on an invariant condition, we can't unswitch
187 if (BI->isConditional()) {
188 // See if this, or some part of it, is loop invariant. If so, we can
189 // unswitch on it if we desire.
190 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
191 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
197 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
198 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
199 if (LoopCond && SI->getNumCases() > 1) {
200 // Find a value to unswitch on:
201 // FIXME: this should chose the most expensive case!
202 Constant *UnswitchVal = SI->getCaseValue(1);
203 // Do not process same value again and again.
204 if (!UnswitchedVals.insert(UnswitchVal))
207 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
214 // Scan the instructions to check for unswitchable values.
215 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
217 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
218 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
219 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
227 assert(L->isLCSSAForm());
232 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
233 /// 1. Exit the loop with no side effects.
234 /// 2. Branch to the latch block with no side-effects.
236 /// If these conditions are true, we return true and set ExitBB to the block we
239 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
241 std::set<BasicBlock*> &Visited) {
242 if (!Visited.insert(BB).second) {
243 // Already visited and Ok, end of recursion.
245 } else if (!L->contains(BB)) {
246 // Otherwise, this is a loop exit, this is fine so long as this is the
248 if (ExitBB != 0) return false;
253 // Otherwise, this is an unvisited intra-loop node. Check all successors.
254 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
255 // Check to see if the successor is a trivial loop exit.
256 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
260 // Okay, everything after this looks good, check to make sure that this block
261 // doesn't include any side effects.
262 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
263 if (I->mayWriteToMemory())
269 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
270 /// leads to an exit from the specified loop, and has no side-effects in the
271 /// process. If so, return the block that is exited to, otherwise return null.
272 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
273 std::set<BasicBlock*> Visited;
274 Visited.insert(L->getHeader()); // Branches to header are ok.
275 BasicBlock *ExitBB = 0;
276 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
281 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
282 /// trivial: that is, that the condition controls whether or not the loop does
283 /// anything at all. If this is a trivial condition, unswitching produces no
284 /// code duplications (equivalently, it produces a simpler loop and a new empty
285 /// loop, which gets deleted).
287 /// If this is a trivial condition, return true, otherwise return false. When
288 /// returning true, this sets Cond and Val to the condition that controls the
289 /// trivial condition: when Cond dynamically equals Val, the loop is known to
290 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
293 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
294 BasicBlock **LoopExit = 0) {
295 BasicBlock *Header = L->getHeader();
296 TerminatorInst *HeaderTerm = Header->getTerminator();
298 BasicBlock *LoopExitBB = 0;
299 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
300 // If the header block doesn't end with a conditional branch on Cond, we
302 if (!BI->isConditional() || BI->getCondition() != Cond)
305 // Check to see if a successor of the branch is guaranteed to go to the
306 // latch block or exit through a one exit block without having any
307 // side-effects. If so, determine the value of Cond that causes it to do
309 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
310 if (Val) *Val = ConstantInt::getTrue();
311 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
312 if (Val) *Val = ConstantInt::getFalse();
314 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
315 // If this isn't a switch on Cond, we can't handle it.
316 if (SI->getCondition() != Cond) return false;
318 // Check to see if a successor of the switch is guaranteed to go to the
319 // latch block or exit through a one exit block without having any
320 // side-effects. If so, determine the value of Cond that causes it to do
321 // this. Note that we can't trivially unswitch on the default case.
322 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
323 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
324 // Okay, we found a trivial case, remember the value that is trivial.
325 if (Val) *Val = SI->getCaseValue(i);
330 // If we didn't find a single unique LoopExit block, or if the loop exit block
331 // contains phi nodes, this isn't trivial.
332 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
333 return false; // Can't handle this.
335 if (LoopExit) *LoopExit = LoopExitBB;
337 // We already know that nothing uses any scalar values defined inside of this
338 // loop. As such, we just have to check to see if this loop will execute any
339 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
340 // part of the loop that the code *would* execute. We already checked the
341 // tail, check the header now.
342 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
343 if (I->mayWriteToMemory())
348 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
349 /// we choose to unswitch the specified loop on the specified value.
351 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
352 // If the condition is trivial, always unswitch. There is no code growth for
354 if (IsTrivialUnswitchCondition(L, LIC))
357 // FIXME: This is really overly conservative. However, more liberal
358 // estimations have thus far resulted in excessive unswitching, which is bad
359 // both in compile time and in code size. This should be replaced once
360 // someone figures out how a good estimation.
361 return L->getBlocks().size();
364 // FIXME: this is brain dead. It should take into consideration code
366 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
369 // Do not include empty blocks in the cost calculation. This happen due to
370 // loop canonicalization and will be removed.
371 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
374 // Count basic blocks.
381 /// UnswitchIfProfitable - We have found that we can unswitch L when
382 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
383 /// unswitch the loop, reprocess the pieces, then return true.
384 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
385 // Check to see if it would be profitable to unswitch this loop.
386 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
388 // Do not do non-trivial unswitch while optimizing for size.
389 if (Cost && OptimizeForSize)
392 if (Cost > Threshold) {
393 // FIXME: this should estimate growth by the amount of code shared by the
394 // resultant unswitched loops.
396 DOUT << "NOT unswitching loop %"
397 << L->getHeader()->getName() << ", cost too high: "
398 << L->getBlocks().size() << "\n";
402 // If this is a trivial condition to unswitch (which results in no code
403 // duplication), do it now.
405 BasicBlock *ExitBlock;
406 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
407 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
409 UnswitchNontrivialCondition(LoopCond, Val, L);
415 // RemapInstruction - Convert the instruction operands from referencing the
416 // current values into those specified by ValueMap.
418 static inline void RemapInstruction(Instruction *I,
419 DenseMap<const Value *, Value*> &ValueMap) {
420 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
421 Value *Op = I->getOperand(op);
422 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
423 if (It != ValueMap.end()) Op = It->second;
424 I->setOperand(op, Op);
428 // CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator Info.
430 // If Orig block's immediate dominator is mapped in VM then use corresponding
431 // immediate dominator from the map. Otherwise Orig block's dominator is also
432 // NewBB's dominator.
434 // OrigPreheader is loop pre-header before this pass started
435 // updating CFG. NewPrehader is loops new pre-header. However, after CFG
436 // manipulation, loop L may not exist. So rely on input parameter NewPreheader.
437 void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
438 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
439 BasicBlock *OrigHeader,
440 DominatorTree *DT, DominanceFrontier *DF,
441 DenseMap<const Value*, Value*> &VM) {
443 // If NewBB alreay has found its place in domiantor tree then no need to do
445 if (DT->getNode(NewBB))
448 // If Orig does not have any immediate domiantor then its clone, NewBB, does
449 // not need any immediate dominator.
450 DomTreeNode *OrigNode = DT->getNode(Orig);
453 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
457 BasicBlock *OrigIDom = NULL;
459 // If Orig is original loop header then its immediate dominator is
461 if (Orig == OrigHeader)
462 OrigIDom = NewPreheader;
464 // If Orig is new pre-header then its immediate dominator is
465 // original pre-header.
466 else if (Orig == NewPreheader)
467 OrigIDom = OrigPreheader;
469 // Other as DT to find Orig's immediate dominator.
471 OrigIDom = OrigIDomNode->getBlock();
473 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
474 BasicBlock *NewIDom = OrigIDom;
475 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
477 NewIDom = cast<BasicBlock>(I->second);
479 // If NewIDom does not have corresponding dominatore tree node then
481 if (!DT->getNode(NewIDom))
482 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
483 OrigHeader, DT, DF, VM);
486 DT->addNewBlock(NewBB, NewIDom);
488 // Copy cloned dominance frontiner set
489 DominanceFrontier::DomSetType NewDFSet;
491 DominanceFrontier::iterator DFI = DF->find(Orig);
492 if ( DFI != DF->end()) {
493 DominanceFrontier::DomSetType S = DFI->second;
494 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
497 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
499 NewDFSet.insert(cast<BasicBlock>(IDM->second));
504 DF->addBasicBlock(NewBB, NewDFSet);
508 /// CloneLoop - Recursively clone the specified loop and all of its children,
509 /// mapping the blocks with the specified map.
510 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
511 LoopInfo *LI, LPPassManager *LPM) {
512 Loop *New = new Loop();
514 LPM->insertLoop(New, PL);
516 // Add all of the blocks in L to the new loop.
517 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
519 if (LI->getLoopFor(*I) == L)
520 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
522 // Add all of the subloops to the new loop.
523 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
524 CloneLoop(*I, New, VM, LI, LPM);
529 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
530 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
531 /// code immediately before InsertPt.
532 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
533 BasicBlock *TrueDest,
534 BasicBlock *FalseDest,
535 Instruction *InsertPt) {
536 // Insert a conditional branch on LIC to the two preheaders. The original
537 // code is the true version and the new code is the false version.
538 Value *BranchVal = LIC;
539 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
540 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
541 else if (Val != ConstantInt::getTrue())
542 // We want to enter the new loop when the condition is true.
543 std::swap(TrueDest, FalseDest);
545 // Insert the new branch.
546 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
551 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
552 /// condition in it (a cond branch from its header block to its latch block,
553 /// where the path through the loop that doesn't execute its body has no
554 /// side-effects), unswitch it. This doesn't involve any code duplication, just
555 /// moving the conditional branch outside of the loop and updating loop info.
556 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
558 BasicBlock *ExitBlock) {
559 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
560 << L->getHeader()->getName() << " [" << L->getBlocks().size()
561 << " blocks] in Function " << L->getHeader()->getParent()->getName()
562 << " on cond: " << *Val << " == " << *Cond << "\n";
564 // First step, split the preheader, so that we know that there is a safe place
565 // to insert the conditional branch. We will change 'OrigPH' to have a
566 // conditional branch on Cond.
567 BasicBlock *OrigPH = L->getLoopPreheader();
568 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader(), this);
570 // Now that we have a place to insert the conditional branch, create a place
571 // to branch to: this is the exit block out of the loop that we should
574 // Split this block now, so that the loop maintains its exit block, and so
575 // that the jump from the preheader can execute the contents of the exit block
576 // without actually branching to it (the exit block should be dominated by the
577 // loop header, not the preheader).
578 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
579 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
581 // Okay, now we have a position to branch from and a position to branch to,
582 // insert the new conditional branch.
583 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
584 OrigPH->getTerminator());
585 OrigPH->getTerminator()->eraseFromParent();
586 LPM->deleteSimpleAnalysisValue(OrigPH->getTerminator(), L);
588 // We need to reprocess this loop, it could be unswitched again.
591 // Now that we know that the loop is never entered when this condition is a
592 // particular value, rewrite the loop with this info. We know that this will
593 // at least eliminate the old branch.
594 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
598 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
599 /// equal Val. Split it into loop versions and test the condition outside of
600 /// either loop. Return the loops created as Out1/Out2.
601 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
603 Function *F = L->getHeader()->getParent();
604 DOUT << "loop-unswitch: Unswitching loop %"
605 << L->getHeader()->getName() << " [" << L->getBlocks().size()
606 << " blocks] in Function " << F->getName()
607 << " when '" << *Val << "' == " << *LIC << "\n";
609 // LoopBlocks contains all of the basic blocks of the loop, including the
610 // preheader of the loop, the body of the loop, and the exit blocks of the
611 // loop, in that order.
612 std::vector<BasicBlock*> LoopBlocks;
614 // First step, split the preheader and exit blocks, and add these blocks to
615 // the LoopBlocks list.
616 BasicBlock *OrigHeader = L->getHeader();
617 BasicBlock *OrigPreheader = L->getLoopPreheader();
618 BasicBlock *NewPreheader = SplitEdge(OrigPreheader, L->getHeader(), this);
619 LoopBlocks.push_back(NewPreheader);
621 // We want the loop to come after the preheader, but before the exit blocks.
622 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
624 std::vector<BasicBlock*> ExitBlocks;
625 L->getUniqueExitBlocks(ExitBlocks);
627 // Split all of the edges from inside the loop to their exit blocks. Update
628 // the appropriate Phi nodes as we do so.
629 SmallVector<BasicBlock *,8> MiddleBlocks;
630 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
631 BasicBlock *ExitBlock = ExitBlocks[i];
632 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
634 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
635 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
636 MiddleBlocks.push_back(MiddleBlock);
637 BasicBlock* StartBlock = Preds[j];
638 BasicBlock* EndBlock;
639 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
640 EndBlock = MiddleBlock;
641 MiddleBlock = EndBlock->getSinglePredecessor();;
643 EndBlock = ExitBlock;
646 std::set<PHINode*> InsertedPHIs;
647 PHINode* OldLCSSA = 0;
648 for (BasicBlock::iterator I = EndBlock->begin();
649 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
650 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
651 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
652 OldLCSSA->getName() + ".us-lcssa",
653 MiddleBlock->getTerminator());
654 NewLCSSA->addIncoming(OldValue, StartBlock);
655 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
657 InsertedPHIs.insert(NewLCSSA);
660 BasicBlock::iterator InsertPt = EndBlock->begin();
661 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
662 for (BasicBlock::iterator I = MiddleBlock->begin();
663 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
665 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
666 OldLCSSA->getName() + ".us-lcssa",
668 OldLCSSA->replaceAllUsesWith(NewLCSSA);
669 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
674 // The exit blocks may have been changed due to edge splitting, recompute.
676 L->getUniqueExitBlocks(ExitBlocks);
678 // Add exit blocks to the loop blocks.
679 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
681 DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>();
682 DominatorTree *DT = getAnalysisToUpdate<DominatorTree>();
684 // Next step, clone all of the basic blocks that make up the loop (including
685 // the loop preheader and exit blocks), keeping track of the mapping between
686 // the instructions and blocks.
687 std::vector<BasicBlock*> NewBlocks;
688 NewBlocks.reserve(LoopBlocks.size());
689 DenseMap<const Value*, Value*> ValueMap;
690 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
691 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
692 NewBlocks.push_back(New);
693 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
694 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
697 // OutSiders are basic block that are dominated by original header and
698 // at the same time they are not part of loop.
699 SmallPtrSet<BasicBlock *, 8> OutSiders;
701 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
702 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
703 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
704 BasicBlock *B = (*DI)->getBlock();
706 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
707 if (VI == ValueMap.end())
712 // Splice the newly inserted blocks into the function right before the
713 // original preheader.
714 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
715 NewBlocks[0], F->end());
717 // Now we create the new Loop object for the versioned loop.
718 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
719 Loop *ParentLoop = L->getParentLoop();
721 // Make sure to add the cloned preheader and exit blocks to the parent loop
723 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
726 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
727 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
728 // The new exit block should be in the same loop as the old one.
729 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
730 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
732 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
733 "Exit block should have been split to have one successor!");
734 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
736 // If the successor of the exit block had PHI nodes, add an entry for
739 for (BasicBlock::iterator I = ExitSucc->begin();
740 (PN = dyn_cast<PHINode>(I)); ++I) {
741 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
742 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
743 if (It != ValueMap.end()) V = It->second;
744 PN->addIncoming(V, NewExit);
748 // Rewrite the code to refer to itself.
749 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
750 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
751 E = NewBlocks[i]->end(); I != E; ++I)
752 RemapInstruction(I, ValueMap);
754 // Rewrite the original preheader to select between versions of the loop.
755 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
756 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
757 "Preheader splitting did not work correctly!");
759 // Emit the new branch that selects between the two versions of this loop.
760 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
761 OldBR->eraseFromParent();
762 LPM->deleteSimpleAnalysisValue(OldBR, L);
764 // Update dominator info
767 // Clone dominator info for all cloned basic block.
768 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
769 BasicBlock *LBB = LoopBlocks[i];
770 BasicBlock *NBB = NewBlocks[i];
771 CloneDomInfo(NBB, LBB, NewPreheader, OrigPreheader,
772 OrigHeader, DT, DF, ValueMap);
774 // Remove any OutSiders from LBB and NBB's dominance frontier.
775 DominanceFrontier::iterator LBBI = DF->find(LBB);
776 if (LBBI != DF->end()) {
777 DominanceFrontier::DomSetType &LBSet = LBBI->second;
778 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
779 LE = LBSet.end(); LI != LE; ++LI) {
781 if (OutSiders.count(B))
782 DF->removeFromFrontier(LBBI, B);
786 // Remove any OutSiders from LBB and NBB's dominance frontier.
787 DominanceFrontier::iterator NBBI = DF->find(NBB);
788 if (NBBI != DF->end()) {
789 DominanceFrontier::DomSetType NBSet = NBBI->second;
790 for (DominanceFrontier::DomSetType::iterator NI = NBSet.begin(),
791 NE = NBSet.end(); NI != NE; ++NI) {
793 if (OutSiders.count(B))
794 DF->removeFromFrontier(NBBI, B);
799 // MiddleBlocks are dominated by original pre header. SplitEdge updated
800 // MiddleBlocks' dominance frontier appropriately.
801 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
802 BasicBlock *MBB = MiddleBlocks[i];
803 DT->changeImmediateDominator(MBB, OrigPreheader);
806 // All Outsiders are now dominated by original pre header.
807 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
808 OE = OutSiders.end(); OI != OE; ++OI) {
809 BasicBlock *OB = *OI;
810 DT->changeImmediateDominator(OB, OrigPreheader);
813 // New loop headers are dominated by original preheader
814 DT->changeImmediateDominator(NewBlocks[0], OrigPreheader);
815 DT->changeImmediateDominator(LoopBlocks[0], OrigPreheader);
818 LoopProcessWorklist.push_back(NewLoop);
821 // Now we rewrite the original code to know that the condition is true and the
822 // new code to know that the condition is false.
823 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
825 // It's possible that simplifying one loop could cause the other to be
826 // deleted. If so, don't simplify it.
827 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
828 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
831 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
833 static void RemoveFromWorklist(Instruction *I,
834 std::vector<Instruction*> &Worklist) {
835 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
837 while (WI != Worklist.end()) {
838 unsigned Offset = WI-Worklist.begin();
840 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
844 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
845 /// program, replacing all uses with V and update the worklist.
846 static void ReplaceUsesOfWith(Instruction *I, Value *V,
847 std::vector<Instruction*> &Worklist,
848 Loop *L, LPPassManager *LPM) {
849 DOUT << "Replace with '" << *V << "': " << *I;
851 // Add uses to the worklist, which may be dead now.
852 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
853 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
854 Worklist.push_back(Use);
856 // Add users to the worklist which may be simplified now.
857 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
859 Worklist.push_back(cast<Instruction>(*UI));
860 I->replaceAllUsesWith(V);
861 I->eraseFromParent();
862 LPM->deleteSimpleAnalysisValue(I, L);
863 RemoveFromWorklist(I, Worklist);
867 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
868 /// information, and remove any dead successors it has.
870 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
871 std::vector<Instruction*> &Worklist,
873 if (pred_begin(BB) != pred_end(BB)) {
874 // This block isn't dead, since an edge to BB was just removed, see if there
875 // are any easy simplifications we can do now.
876 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
877 // If it has one pred, fold phi nodes in BB.
878 while (isa<PHINode>(BB->begin()))
879 ReplaceUsesOfWith(BB->begin(),
880 cast<PHINode>(BB->begin())->getIncomingValue(0),
883 // If this is the header of a loop and the only pred is the latch, we now
884 // have an unreachable loop.
885 if (Loop *L = LI->getLoopFor(BB))
886 if (L->getHeader() == BB && L->contains(Pred)) {
887 // Remove the branch from the latch to the header block, this makes
888 // the header dead, which will make the latch dead (because the header
889 // dominates the latch).
890 Pred->getTerminator()->eraseFromParent();
891 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
892 new UnreachableInst(Pred);
894 // The loop is now broken, remove it from LI.
895 RemoveLoopFromHierarchy(L);
897 // Reprocess the header, which now IS dead.
898 RemoveBlockIfDead(BB, Worklist, L);
902 // If pred ends in a uncond branch, add uncond branch to worklist so that
903 // the two blocks will get merged.
904 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
905 if (BI->isUnconditional())
906 Worklist.push_back(BI);
911 DOUT << "Nuking dead block: " << *BB;
913 // Remove the instructions in the basic block from the worklist.
914 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
915 RemoveFromWorklist(I, Worklist);
917 // Anything that uses the instructions in this basic block should have their
918 // uses replaced with undefs.
920 I->replaceAllUsesWith(UndefValue::get(I->getType()));
923 // If this is the edge to the header block for a loop, remove the loop and
924 // promote all subloops.
925 if (Loop *BBLoop = LI->getLoopFor(BB)) {
926 if (BBLoop->getLoopLatch() == BB)
927 RemoveLoopFromHierarchy(BBLoop);
930 // Remove the block from the loop info, which removes it from any loops it
935 // Remove phi node entries in successors for this block.
936 TerminatorInst *TI = BB->getTerminator();
937 std::vector<BasicBlock*> Succs;
938 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
939 Succs.push_back(TI->getSuccessor(i));
940 TI->getSuccessor(i)->removePredecessor(BB);
943 // Unique the successors, remove anything with multiple uses.
944 std::sort(Succs.begin(), Succs.end());
945 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
947 // Remove the basic block, including all of the instructions contained in it.
948 BB->eraseFromParent();
949 LPM->deleteSimpleAnalysisValue(BB, L);
950 // Remove successor blocks here that are not dead, so that we know we only
951 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
952 // then getting removed before we revisit them, which is badness.
954 for (unsigned i = 0; i != Succs.size(); ++i)
955 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
956 // One exception is loop headers. If this block was the preheader for a
957 // loop, then we DO want to visit the loop so the loop gets deleted.
958 // We know that if the successor is a loop header, that this loop had to
959 // be the preheader: the case where this was the latch block was handled
960 // above and headers can only have two predecessors.
961 if (!LI->isLoopHeader(Succs[i])) {
962 Succs.erase(Succs.begin()+i);
967 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
968 RemoveBlockIfDead(Succs[i], Worklist, L);
971 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
972 /// become unwrapped, either because the backedge was deleted, or because the
973 /// edge into the header was removed. If the edge into the header from the
974 /// latch block was removed, the loop is unwrapped but subloops are still alive,
975 /// so they just reparent loops. If the loops are actually dead, they will be
977 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
978 LPM->deleteLoopFromQueue(L);
979 RemoveLoopFromWorklist(L);
984 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
985 // the value specified by Val in the specified loop, or we know it does NOT have
986 // that value. Rewrite any uses of LIC or of properties correlated to it.
987 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
990 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
992 // FIXME: Support correlated properties, like:
999 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1000 // selects, switches.
1001 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
1002 std::vector<Instruction*> Worklist;
1004 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1005 // in the loop with the appropriate one directly.
1006 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
1011 Replacement = ConstantInt::get(Type::Int1Ty,
1012 !cast<ConstantInt>(Val)->getZExtValue());
1014 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1015 if (Instruction *U = cast<Instruction>(Users[i])) {
1016 if (!L->contains(U->getParent()))
1018 U->replaceUsesOfWith(LIC, Replacement);
1019 Worklist.push_back(U);
1022 // Otherwise, we don't know the precise value of LIC, but we do know that it
1023 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1024 // can. This case occurs when we unswitch switch statements.
1025 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1026 if (Instruction *U = cast<Instruction>(Users[i])) {
1027 if (!L->contains(U->getParent()))
1030 Worklist.push_back(U);
1032 // If we know that LIC is not Val, use this info to simplify code.
1033 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1034 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1035 if (SI->getCaseValue(i) == Val) {
1036 // Found a dead case value. Don't remove PHI nodes in the
1037 // successor if they become single-entry, those PHI nodes may
1038 // be in the Users list.
1040 // FIXME: This is a hack. We need to keep the successor around
1041 // and hooked up so as to preserve the loop structure, because
1042 // trying to update it is complicated. So instead we preserve the
1043 // loop structure and put the block on an dead code path.
1045 BasicBlock* Old = SI->getParent();
1046 BasicBlock* Split = SplitBlock(Old, SI, this);
1048 Instruction* OldTerm = Old->getTerminator();
1049 new BranchInst(Split, SI->getSuccessor(i),
1050 ConstantInt::getTrue(), OldTerm);
1052 Old->getTerminator()->eraseFromParent();
1056 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
1057 (PN = dyn_cast<PHINode>(II)); ++II) {
1058 Value *InVal = PN->removeIncomingValue(Split, false);
1059 PN->addIncoming(InVal, Old);
1068 // TODO: We could do other simplifications, for example, turning
1069 // LIC == Val -> false.
1073 SimplifyCode(Worklist, L);
1076 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1077 /// loop, walk over it and constant prop, dce, and fold control flow where
1078 /// possible. Note that this is effectively a very simple loop-structure-aware
1079 /// optimizer. During processing of this loop, L could very well be deleted, so
1080 /// it must not be used.
1082 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1085 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1086 while (!Worklist.empty()) {
1087 Instruction *I = Worklist.back();
1088 Worklist.pop_back();
1090 // Simple constant folding.
1091 if (Constant *C = ConstantFoldInstruction(I)) {
1092 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
1097 if (isInstructionTriviallyDead(I)) {
1098 DOUT << "Remove dead instruction '" << *I;
1100 // Add uses to the worklist, which may be dead now.
1101 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1102 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1103 Worklist.push_back(Use);
1104 I->eraseFromParent();
1105 LPM->deleteSimpleAnalysisValue(I, L);
1106 RemoveFromWorklist(I, Worklist);
1111 // Special case hacks that appear commonly in unswitched code.
1112 switch (I->getOpcode()) {
1113 case Instruction::Select:
1114 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1115 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L, LPM);
1119 case Instruction::And:
1120 if (isa<ConstantInt>(I->getOperand(0)) &&
1121 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1122 cast<BinaryOperator>(I)->swapOperands();
1123 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1124 if (CB->getType() == Type::Int1Ty) {
1125 if (CB->isOne()) // X & 1 -> X
1126 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1128 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1132 case Instruction::Or:
1133 if (isa<ConstantInt>(I->getOperand(0)) &&
1134 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1135 cast<BinaryOperator>(I)->swapOperands();
1136 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1137 if (CB->getType() == Type::Int1Ty) {
1138 if (CB->isOne()) // X | 1 -> 1
1139 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1141 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1145 case Instruction::Br: {
1146 BranchInst *BI = cast<BranchInst>(I);
1147 if (BI->isUnconditional()) {
1148 // If BI's parent is the only pred of the successor, fold the two blocks
1150 BasicBlock *Pred = BI->getParent();
1151 BasicBlock *Succ = BI->getSuccessor(0);
1152 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1153 if (!SinglePred) continue; // Nothing to do.
1154 assert(SinglePred == Pred && "CFG broken");
1156 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1157 << Succ->getName() << "\n";
1159 // Resolve any single entry PHI nodes in Succ.
1160 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1161 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1163 // Move all of the successor contents from Succ to Pred.
1164 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1166 BI->eraseFromParent();
1167 LPM->deleteSimpleAnalysisValue(BI, L);
1168 RemoveFromWorklist(BI, Worklist);
1170 // If Succ has any successors with PHI nodes, update them to have
1171 // entries coming from Pred instead of Succ.
1172 Succ->replaceAllUsesWith(Pred);
1174 // Remove Succ from the loop tree.
1175 LI->removeBlock(Succ);
1176 Succ->eraseFromParent();
1177 LPM->deleteSimpleAnalysisValue(Succ, L);
1179 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1180 // Conditional branch. Turn it into an unconditional branch, then
1181 // remove dead blocks.
1182 break; // FIXME: Enable.
1184 DOUT << "Folded branch: " << *BI;
1185 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1186 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1187 DeadSucc->removePredecessor(BI->getParent(), true);
1188 Worklist.push_back(new BranchInst(LiveSucc, BI));
1189 BI->eraseFromParent();
1190 LPM->deleteSimpleAnalysisValue(BI, L);
1191 RemoveFromWorklist(BI, Worklist);
1194 RemoveBlockIfDead(DeadSucc, Worklist, L);