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.addRequired<LoopInfo>();
87 AU.addPreserved<LoopInfo>();
88 AU.addRequiredID(LCSSAID);
92 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
94 void RemoveLoopFromWorklist(Loop *L) {
95 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
96 LoopProcessWorklist.end(), L);
97 if (I != LoopProcessWorklist.end())
98 LoopProcessWorklist.erase(I);
101 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
102 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
103 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
104 BasicBlock *ExitBlock);
105 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
107 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
108 Constant *Val, bool isEqual);
110 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
111 BasicBlock *TrueDest,
112 BasicBlock *FalseDest,
113 Instruction *InsertPt);
115 void SimplifyCode(std::vector<Instruction*> &Worklist);
116 void RemoveBlockIfDead(BasicBlock *BB,
117 std::vector<Instruction*> &Worklist);
118 void RemoveLoopFromHierarchy(Loop *L);
120 char LoopUnswitch::ID = 0;
121 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
124 LoopPass *llvm::createLoopUnswitchPass(bool Os) {
125 return new LoopUnswitch(Os);
128 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
129 /// invariant in the loop, or has an invariant piece, return the invariant.
130 /// Otherwise, return null.
131 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
132 // Constants should be folded, not unswitched on!
133 if (isa<Constant>(Cond)) return false;
135 // TODO: Handle: br (VARIANT|INVARIANT).
136 // TODO: Hoist simple expressions out of loops.
137 if (L->isLoopInvariant(Cond)) return Cond;
139 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
140 if (BO->getOpcode() == Instruction::And ||
141 BO->getOpcode() == Instruction::Or) {
142 // If either the left or right side is invariant, we can unswitch on this,
143 // which will cause the branch to go away in one loop and the condition to
144 // simplify in the other one.
145 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
147 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
154 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
155 assert(L->isLCSSAForm());
156 LI = &getAnalysis<LoopInfo>();
158 bool Changed = false;
160 // Loop over all of the basic blocks in the loop. If we find an interior
161 // block that is branching on a loop-invariant condition, we can unswitch this
163 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
165 TerminatorInst *TI = (*I)->getTerminator();
166 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
167 // If this isn't branching on an invariant condition, we can't unswitch
169 if (BI->isConditional()) {
170 // See if this, or some part of it, is loop invariant. If so, we can
171 // unswitch on it if we desire.
172 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
173 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
179 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
180 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
181 if (LoopCond && SI->getNumCases() > 1) {
182 // Find a value to unswitch on:
183 // FIXME: this should chose the most expensive case!
184 Constant *UnswitchVal = SI->getCaseValue(1);
185 // Do not process same value again and again.
186 if (!UnswitchedVals.insert(UnswitchVal))
189 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
196 // Scan the instructions to check for unswitchable values.
197 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
199 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
200 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
201 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
209 assert(L->isLCSSAForm());
214 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
215 /// 1. Exit the loop with no side effects.
216 /// 2. Branch to the latch block with no side-effects.
218 /// If these conditions are true, we return true and set ExitBB to the block we
221 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
223 std::set<BasicBlock*> &Visited) {
224 if (!Visited.insert(BB).second) {
225 // Already visited and Ok, end of recursion.
227 } else if (!L->contains(BB)) {
228 // Otherwise, this is a loop exit, this is fine so long as this is the
230 if (ExitBB != 0) return false;
235 // Otherwise, this is an unvisited intra-loop node. Check all successors.
236 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
237 // Check to see if the successor is a trivial loop exit.
238 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
242 // Okay, everything after this looks good, check to make sure that this block
243 // doesn't include any side effects.
244 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
245 if (I->mayWriteToMemory())
251 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
252 /// leads to an exit from the specified loop, and has no side-effects in the
253 /// process. If so, return the block that is exited to, otherwise return null.
254 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
255 std::set<BasicBlock*> Visited;
256 Visited.insert(L->getHeader()); // Branches to header are ok.
257 BasicBlock *ExitBB = 0;
258 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
263 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
264 /// trivial: that is, that the condition controls whether or not the loop does
265 /// anything at all. If this is a trivial condition, unswitching produces no
266 /// code duplications (equivalently, it produces a simpler loop and a new empty
267 /// loop, which gets deleted).
269 /// If this is a trivial condition, return true, otherwise return false. When
270 /// returning true, this sets Cond and Val to the condition that controls the
271 /// trivial condition: when Cond dynamically equals Val, the loop is known to
272 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
275 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
276 BasicBlock **LoopExit = 0) {
277 BasicBlock *Header = L->getHeader();
278 TerminatorInst *HeaderTerm = Header->getTerminator();
280 BasicBlock *LoopExitBB = 0;
281 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
282 // If the header block doesn't end with a conditional branch on Cond, we
284 if (!BI->isConditional() || BI->getCondition() != Cond)
287 // Check to see if a successor of the branch is guaranteed to go to the
288 // latch block or exit through a one exit block without having any
289 // side-effects. If so, determine the value of Cond that causes it to do
291 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
292 if (Val) *Val = ConstantInt::getTrue();
293 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
294 if (Val) *Val = ConstantInt::getFalse();
296 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
297 // If this isn't a switch on Cond, we can't handle it.
298 if (SI->getCondition() != Cond) return false;
300 // Check to see if a successor of the switch is guaranteed to go to the
301 // latch block or exit through a one exit block without having any
302 // side-effects. If so, determine the value of Cond that causes it to do
303 // this. Note that we can't trivially unswitch on the default case.
304 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
305 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
306 // Okay, we found a trivial case, remember the value that is trivial.
307 if (Val) *Val = SI->getCaseValue(i);
312 // If we didn't find a single unique LoopExit block, or if the loop exit block
313 // contains phi nodes, this isn't trivial.
314 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
315 return false; // Can't handle this.
317 if (LoopExit) *LoopExit = LoopExitBB;
319 // We already know that nothing uses any scalar values defined inside of this
320 // loop. As such, we just have to check to see if this loop will execute any
321 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
322 // part of the loop that the code *would* execute. We already checked the
323 // tail, check the header now.
324 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
325 if (I->mayWriteToMemory())
330 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
331 /// we choose to unswitch the specified loop on the specified value.
333 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
334 // If the condition is trivial, always unswitch. There is no code growth for
336 if (IsTrivialUnswitchCondition(L, LIC))
339 // FIXME: This is really overly conservative. However, more liberal
340 // estimations have thus far resulted in excessive unswitching, which is bad
341 // both in compile time and in code size. This should be replaced once
342 // someone figures out how a good estimation.
343 return L->getBlocks().size();
346 // FIXME: this is brain dead. It should take into consideration code
348 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
351 // Do not include empty blocks in the cost calculation. This happen due to
352 // loop canonicalization and will be removed.
353 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
356 // Count basic blocks.
363 /// UnswitchIfProfitable - We have found that we can unswitch L when
364 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
365 /// unswitch the loop, reprocess the pieces, then return true.
366 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
367 // Check to see if it would be profitable to unswitch this loop.
368 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
370 // Do not do non-trivial unswitch while optimizing for size.
371 if (Cost && OptimizeForSize)
374 if (Cost > Threshold) {
375 // FIXME: this should estimate growth by the amount of code shared by the
376 // resultant unswitched loops.
378 DOUT << "NOT unswitching loop %"
379 << L->getHeader()->getName() << ", cost too high: "
380 << L->getBlocks().size() << "\n";
384 // If this is a trivial condition to unswitch (which results in no code
385 // duplication), do it now.
387 BasicBlock *ExitBlock;
388 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
389 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
391 UnswitchNontrivialCondition(LoopCond, Val, L);
397 // RemapInstruction - Convert the instruction operands from referencing the
398 // current values into those specified by ValueMap.
400 static inline void RemapInstruction(Instruction *I,
401 DenseMap<const Value *, Value*> &ValueMap) {
402 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
403 Value *Op = I->getOperand(op);
404 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
405 if (It != ValueMap.end()) Op = It->second;
406 I->setOperand(op, Op);
410 // CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator Info.
412 // If Orig block's immediate dominator is mapped in VM then use corresponding
413 // immediate dominator from the map. Otherwise Orig block's dominator is also
414 // NewBB's dominator.
416 // OrigPreheader is loop pre-header before this pass started
417 // updating CFG. NewPrehader is loops new pre-header. However, after CFG
418 // manipulation, loop L may not exist. So rely on input parameter NewPreheader.
419 void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
420 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
421 BasicBlock *OrigHeader,
422 DominatorTree *DT, DominanceFrontier *DF,
423 DenseMap<const Value*, Value*> &VM) {
425 // If NewBB alreay has found its place in domiantor tree then no need to do
427 if (DT->getNode(NewBB))
430 // If Orig does not have any immediate domiantor then its clone, NewBB, does
431 // not need any immediate dominator.
432 DomTreeNode *OrigNode = DT->getNode(Orig);
435 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
439 BasicBlock *OrigIDom = NULL;
441 // If Orig is original loop header then its immediate dominator is
443 if (Orig == OrigHeader)
444 OrigIDom = NewPreheader;
446 // If Orig is new pre-header then its immediate dominator is
447 // original pre-header.
448 else if (Orig == NewPreheader)
449 OrigIDom = OrigPreheader;
451 // Other as DT to find Orig's immediate dominator.
453 OrigIDom = OrigIDomNode->getBlock();
455 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
456 BasicBlock *NewIDom = OrigIDom;
457 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
459 NewIDom = cast<BasicBlock>(I->second);
461 // If NewIDom does not have corresponding dominatore tree node then
463 if (!DT->getNode(NewIDom))
464 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
465 OrigHeader, DT, DF, VM);
468 DT->addNewBlock(NewBB, NewIDom);
470 // Copy cloned dominance frontiner set
471 DominanceFrontier::DomSetType NewDFSet;
473 DominanceFrontier::iterator DFI = DF->find(Orig);
474 if ( DFI != DF->end()) {
475 DominanceFrontier::DomSetType S = DFI->second;
476 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
479 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
481 NewDFSet.insert(cast<BasicBlock>(IDM->second));
486 DF->addBasicBlock(NewBB, NewDFSet);
490 /// CloneLoop - Recursively clone the specified loop and all of its children,
491 /// mapping the blocks with the specified map.
492 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
493 LoopInfo *LI, LPPassManager *LPM) {
494 Loop *New = new Loop();
496 LPM->insertLoop(New, PL);
498 // Add all of the blocks in L to the new loop.
499 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
501 if (LI->getLoopFor(*I) == L)
502 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
504 // Add all of the subloops to the new loop.
505 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
506 CloneLoop(*I, New, VM, LI, LPM);
511 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
512 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
513 /// code immediately before InsertPt.
514 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
515 BasicBlock *TrueDest,
516 BasicBlock *FalseDest,
517 Instruction *InsertPt) {
518 // Insert a conditional branch on LIC to the two preheaders. The original
519 // code is the true version and the new code is the false version.
520 Value *BranchVal = LIC;
521 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
522 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
523 else if (Val != ConstantInt::getTrue())
524 // We want to enter the new loop when the condition is true.
525 std::swap(TrueDest, FalseDest);
527 // Insert the new branch.
528 BranchInst *BRI = new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
530 // Update dominator info.
531 // BranchVal is a new preheader so it dominates true and false destination
533 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
534 DT->changeImmediateDominator(TrueDest, BRI->getParent());
535 DT->changeImmediateDominator(FalseDest, BRI->getParent());
537 // No need to update DominanceFrontier. BRI->getParent() dominated TrueDest
538 // and FalseDest anyway. Now it immediately dominates them.
542 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
543 /// condition in it (a cond branch from its header block to its latch block,
544 /// where the path through the loop that doesn't execute its body has no
545 /// side-effects), unswitch it. This doesn't involve any code duplication, just
546 /// moving the conditional branch outside of the loop and updating loop info.
547 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
549 BasicBlock *ExitBlock) {
550 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
551 << L->getHeader()->getName() << " [" << L->getBlocks().size()
552 << " blocks] in Function " << L->getHeader()->getParent()->getName()
553 << " on cond: " << *Val << " == " << *Cond << "\n";
555 // First step, split the preheader, so that we know that there is a safe place
556 // to insert the conditional branch. We will change 'OrigPH' to have a
557 // conditional branch on Cond.
558 BasicBlock *OrigPH = L->getLoopPreheader();
559 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader(), this);
561 // Now that we have a place to insert the conditional branch, create a place
562 // to branch to: this is the exit block out of the loop that we should
565 // Split this block now, so that the loop maintains its exit block, and so
566 // that the jump from the preheader can execute the contents of the exit block
567 // without actually branching to it (the exit block should be dominated by the
568 // loop header, not the preheader).
569 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
570 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
572 // Okay, now we have a position to branch from and a position to branch to,
573 // insert the new conditional branch.
574 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
575 OrigPH->getTerminator());
576 OrigPH->getTerminator()->eraseFromParent();
578 // We need to reprocess this loop, it could be unswitched again.
581 // Now that we know that the loop is never entered when this condition is a
582 // particular value, rewrite the loop with this info. We know that this will
583 // at least eliminate the old branch.
584 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
588 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
589 /// equal Val. Split it into loop versions and test the condition outside of
590 /// either loop. Return the loops created as Out1/Out2.
591 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
593 Function *F = L->getHeader()->getParent();
594 DOUT << "loop-unswitch: Unswitching loop %"
595 << L->getHeader()->getName() << " [" << L->getBlocks().size()
596 << " blocks] in Function " << F->getName()
597 << " when '" << *Val << "' == " << *LIC << "\n";
599 // LoopBlocks contains all of the basic blocks of the loop, including the
600 // preheader of the loop, the body of the loop, and the exit blocks of the
601 // loop, in that order.
602 std::vector<BasicBlock*> LoopBlocks;
604 // First step, split the preheader and exit blocks, and add these blocks to
605 // the LoopBlocks list.
606 BasicBlock *OrigHeader = L->getHeader();
607 BasicBlock *OrigPreheader = L->getLoopPreheader();
608 BasicBlock *NewPreheader = SplitEdge(OrigPreheader, L->getHeader(), this);
609 LoopBlocks.push_back(NewPreheader);
611 // We want the loop to come after the preheader, but before the exit blocks.
612 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
614 std::vector<BasicBlock*> ExitBlocks;
615 L->getUniqueExitBlocks(ExitBlocks);
617 // Split all of the edges from inside the loop to their exit blocks. Update
618 // the appropriate Phi nodes as we do so.
619 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
620 BasicBlock *ExitBlock = ExitBlocks[i];
621 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
623 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
624 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
625 BasicBlock* StartBlock = Preds[j];
626 BasicBlock* EndBlock;
627 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
628 EndBlock = MiddleBlock;
629 MiddleBlock = EndBlock->getSinglePredecessor();;
631 EndBlock = ExitBlock;
634 std::set<PHINode*> InsertedPHIs;
635 PHINode* OldLCSSA = 0;
636 for (BasicBlock::iterator I = EndBlock->begin();
637 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
638 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
639 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
640 OldLCSSA->getName() + ".us-lcssa",
641 MiddleBlock->getTerminator());
642 NewLCSSA->addIncoming(OldValue, StartBlock);
643 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
645 InsertedPHIs.insert(NewLCSSA);
648 BasicBlock::iterator InsertPt = EndBlock->begin();
649 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
650 for (BasicBlock::iterator I = MiddleBlock->begin();
651 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
653 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
654 OldLCSSA->getName() + ".us-lcssa",
656 OldLCSSA->replaceAllUsesWith(NewLCSSA);
657 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
662 // The exit blocks may have been changed due to edge splitting, recompute.
664 L->getUniqueExitBlocks(ExitBlocks);
666 // Add exit blocks to the loop blocks.
667 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
669 // Next step, clone all of the basic blocks that make up the loop (including
670 // the loop preheader and exit blocks), keeping track of the mapping between
671 // the instructions and blocks.
672 std::vector<BasicBlock*> NewBlocks;
673 NewBlocks.reserve(LoopBlocks.size());
674 DenseMap<const Value*, Value*> ValueMap;
675 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
676 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
677 NewBlocks.push_back(New);
678 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
681 // Update dominator info
682 DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>();
683 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>())
684 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
685 BasicBlock *LBB = LoopBlocks[i];
686 BasicBlock *NBB = NewBlocks[i];
687 CloneDomInfo(NBB, LBB, NewPreheader, OrigPreheader,
688 OrigHeader, DT, DF, ValueMap);
691 // Splice the newly inserted blocks into the function right before the
692 // original preheader.
693 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
694 NewBlocks[0], F->end());
696 // Now we create the new Loop object for the versioned loop.
697 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
698 Loop *ParentLoop = L->getParentLoop();
700 // Make sure to add the cloned preheader and exit blocks to the parent loop
702 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
705 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
706 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
707 // The new exit block should be in the same loop as the old one.
708 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
709 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
711 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
712 "Exit block should have been split to have one successor!");
713 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
715 // If the successor of the exit block had PHI nodes, add an entry for
718 for (BasicBlock::iterator I = ExitSucc->begin();
719 (PN = dyn_cast<PHINode>(I)); ++I) {
720 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
721 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
722 if (It != ValueMap.end()) V = It->second;
723 PN->addIncoming(V, NewExit);
727 // Rewrite the code to refer to itself.
728 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
729 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
730 E = NewBlocks[i]->end(); I != E; ++I)
731 RemapInstruction(I, ValueMap);
733 // Rewrite the original preheader to select between versions of the loop.
734 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
735 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
736 "Preheader splitting did not work correctly!");
738 // Emit the new branch that selects between the two versions of this loop.
739 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
740 OldBR->eraseFromParent();
742 LoopProcessWorklist.push_back(NewLoop);
745 // Now we rewrite the original code to know that the condition is true and the
746 // new code to know that the condition is false.
747 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
749 // It's possible that simplifying one loop could cause the other to be
750 // deleted. If so, don't simplify it.
751 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
752 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
755 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
757 static void RemoveFromWorklist(Instruction *I,
758 std::vector<Instruction*> &Worklist) {
759 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
761 while (WI != Worklist.end()) {
762 unsigned Offset = WI-Worklist.begin();
764 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
768 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
769 /// program, replacing all uses with V and update the worklist.
770 static void ReplaceUsesOfWith(Instruction *I, Value *V,
771 std::vector<Instruction*> &Worklist) {
772 DOUT << "Replace with '" << *V << "': " << *I;
774 // Add uses to the worklist, which may be dead now.
775 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
776 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
777 Worklist.push_back(Use);
779 // Add users to the worklist which may be simplified now.
780 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
782 Worklist.push_back(cast<Instruction>(*UI));
783 I->replaceAllUsesWith(V);
784 I->eraseFromParent();
785 RemoveFromWorklist(I, Worklist);
789 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
790 /// information, and remove any dead successors it has.
792 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
793 std::vector<Instruction*> &Worklist) {
794 if (pred_begin(BB) != pred_end(BB)) {
795 // This block isn't dead, since an edge to BB was just removed, see if there
796 // are any easy simplifications we can do now.
797 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
798 // If it has one pred, fold phi nodes in BB.
799 while (isa<PHINode>(BB->begin()))
800 ReplaceUsesOfWith(BB->begin(),
801 cast<PHINode>(BB->begin())->getIncomingValue(0),
804 // If this is the header of a loop and the only pred is the latch, we now
805 // have an unreachable loop.
806 if (Loop *L = LI->getLoopFor(BB))
807 if (L->getHeader() == BB && L->contains(Pred)) {
808 // Remove the branch from the latch to the header block, this makes
809 // the header dead, which will make the latch dead (because the header
810 // dominates the latch).
811 Pred->getTerminator()->eraseFromParent();
812 new UnreachableInst(Pred);
814 // The loop is now broken, remove it from LI.
815 RemoveLoopFromHierarchy(L);
817 // Reprocess the header, which now IS dead.
818 RemoveBlockIfDead(BB, Worklist);
822 // If pred ends in a uncond branch, add uncond branch to worklist so that
823 // the two blocks will get merged.
824 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
825 if (BI->isUnconditional())
826 Worklist.push_back(BI);
831 DOUT << "Nuking dead block: " << *BB;
833 // Remove the instructions in the basic block from the worklist.
834 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
835 RemoveFromWorklist(I, Worklist);
837 // Anything that uses the instructions in this basic block should have their
838 // uses replaced with undefs.
840 I->replaceAllUsesWith(UndefValue::get(I->getType()));
843 // If this is the edge to the header block for a loop, remove the loop and
844 // promote all subloops.
845 if (Loop *BBLoop = LI->getLoopFor(BB)) {
846 if (BBLoop->getLoopLatch() == BB)
847 RemoveLoopFromHierarchy(BBLoop);
850 // Remove the block from the loop info, which removes it from any loops it
855 // Remove phi node entries in successors for this block.
856 TerminatorInst *TI = BB->getTerminator();
857 std::vector<BasicBlock*> Succs;
858 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
859 Succs.push_back(TI->getSuccessor(i));
860 TI->getSuccessor(i)->removePredecessor(BB);
863 // Unique the successors, remove anything with multiple uses.
864 std::sort(Succs.begin(), Succs.end());
865 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
867 // Remove the basic block, including all of the instructions contained in it.
868 BB->eraseFromParent();
870 // Remove successor blocks here that are not dead, so that we know we only
871 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
872 // then getting removed before we revisit them, which is badness.
874 for (unsigned i = 0; i != Succs.size(); ++i)
875 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
876 // One exception is loop headers. If this block was the preheader for a
877 // loop, then we DO want to visit the loop so the loop gets deleted.
878 // We know that if the successor is a loop header, that this loop had to
879 // be the preheader: the case where this was the latch block was handled
880 // above and headers can only have two predecessors.
881 if (!LI->isLoopHeader(Succs[i])) {
882 Succs.erase(Succs.begin()+i);
887 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
888 RemoveBlockIfDead(Succs[i], Worklist);
891 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
892 /// become unwrapped, either because the backedge was deleted, or because the
893 /// edge into the header was removed. If the edge into the header from the
894 /// latch block was removed, the loop is unwrapped but subloops are still alive,
895 /// so they just reparent loops. If the loops are actually dead, they will be
897 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
898 LPM->deleteLoopFromQueue(L);
899 RemoveLoopFromWorklist(L);
904 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
905 // the value specified by Val in the specified loop, or we know it does NOT have
906 // that value. Rewrite any uses of LIC or of properties correlated to it.
907 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
910 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
912 // FIXME: Support correlated properties, like:
919 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
920 // selects, switches.
921 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
922 std::vector<Instruction*> Worklist;
924 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
925 // in the loop with the appropriate one directly.
926 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
931 Replacement = ConstantInt::get(Type::Int1Ty,
932 !cast<ConstantInt>(Val)->getZExtValue());
934 for (unsigned i = 0, e = Users.size(); i != e; ++i)
935 if (Instruction *U = cast<Instruction>(Users[i])) {
936 if (!L->contains(U->getParent()))
938 U->replaceUsesOfWith(LIC, Replacement);
939 Worklist.push_back(U);
942 // Otherwise, we don't know the precise value of LIC, but we do know that it
943 // is certainly NOT "Val". As such, simplify any uses in the loop that we
944 // can. This case occurs when we unswitch switch statements.
945 for (unsigned i = 0, e = Users.size(); i != e; ++i)
946 if (Instruction *U = cast<Instruction>(Users[i])) {
947 if (!L->contains(U->getParent()))
950 Worklist.push_back(U);
952 // If we know that LIC is not Val, use this info to simplify code.
953 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
954 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
955 if (SI->getCaseValue(i) == Val) {
956 // Found a dead case value. Don't remove PHI nodes in the
957 // successor if they become single-entry, those PHI nodes may
958 // be in the Users list.
960 // FIXME: This is a hack. We need to keep the successor around
961 // and hooked up so as to preserve the loop structure, because
962 // trying to update it is complicated. So instead we preserve the
963 // loop structure and put the block on an dead code path.
965 BasicBlock* Old = SI->getParent();
966 BasicBlock* Split = SplitBlock(Old, SI, this);
968 Instruction* OldTerm = Old->getTerminator();
969 new BranchInst(Split, SI->getSuccessor(i),
970 ConstantInt::getTrue(), OldTerm);
972 Old->getTerminator()->eraseFromParent();
976 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
977 (PN = dyn_cast<PHINode>(II)); ++II) {
978 Value *InVal = PN->removeIncomingValue(Split, false);
979 PN->addIncoming(InVal, Old);
988 // TODO: We could do other simplifications, for example, turning
989 // LIC == Val -> false.
993 SimplifyCode(Worklist);
996 /// SimplifyCode - Okay, now that we have simplified some instructions in the
997 /// loop, walk over it and constant prop, dce, and fold control flow where
998 /// possible. Note that this is effectively a very simple loop-structure-aware
999 /// optimizer. During processing of this loop, L could very well be deleted, so
1000 /// it must not be used.
1002 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1005 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
1006 while (!Worklist.empty()) {
1007 Instruction *I = Worklist.back();
1008 Worklist.pop_back();
1010 // Simple constant folding.
1011 if (Constant *C = ConstantFoldInstruction(I)) {
1012 ReplaceUsesOfWith(I, C, Worklist);
1017 if (isInstructionTriviallyDead(I)) {
1018 DOUT << "Remove dead instruction '" << *I;
1020 // Add uses to the worklist, which may be dead now.
1021 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1022 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1023 Worklist.push_back(Use);
1024 I->eraseFromParent();
1025 RemoveFromWorklist(I, Worklist);
1030 // Special case hacks that appear commonly in unswitched code.
1031 switch (I->getOpcode()) {
1032 case Instruction::Select:
1033 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1034 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
1038 case Instruction::And:
1039 if (isa<ConstantInt>(I->getOperand(0)) &&
1040 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1041 cast<BinaryOperator>(I)->swapOperands();
1042 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1043 if (CB->getType() == Type::Int1Ty) {
1044 if (CB->isOne()) // X & 1 -> X
1045 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1047 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1051 case Instruction::Or:
1052 if (isa<ConstantInt>(I->getOperand(0)) &&
1053 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1054 cast<BinaryOperator>(I)->swapOperands();
1055 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1056 if (CB->getType() == Type::Int1Ty) {
1057 if (CB->isOne()) // X | 1 -> 1
1058 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1060 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1064 case Instruction::Br: {
1065 BranchInst *BI = cast<BranchInst>(I);
1066 if (BI->isUnconditional()) {
1067 // If BI's parent is the only pred of the successor, fold the two blocks
1069 BasicBlock *Pred = BI->getParent();
1070 BasicBlock *Succ = BI->getSuccessor(0);
1071 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1072 if (!SinglePred) continue; // Nothing to do.
1073 assert(SinglePred == Pred && "CFG broken");
1075 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1076 << Succ->getName() << "\n";
1078 // Resolve any single entry PHI nodes in Succ.
1079 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1080 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1082 // Move all of the successor contents from Succ to Pred.
1083 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1085 BI->eraseFromParent();
1086 RemoveFromWorklist(BI, Worklist);
1088 // If Succ has any successors with PHI nodes, update them to have
1089 // entries coming from Pred instead of Succ.
1090 Succ->replaceAllUsesWith(Pred);
1092 // Remove Succ from the loop tree.
1093 LI->removeBlock(Succ);
1094 Succ->eraseFromParent();
1096 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1097 // Conditional branch. Turn it into an unconditional branch, then
1098 // remove dead blocks.
1099 break; // FIXME: Enable.
1101 DOUT << "Folded branch: " << *BI;
1102 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1103 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1104 DeadSucc->removePredecessor(BI->getParent(), true);
1105 Worklist.push_back(new BranchInst(LiveSucc, BI));
1106 BI->eraseFromParent();
1107 RemoveFromWorklist(BI, Worklist);
1110 RemoveBlockIfDead(DeadSucc, Worklist);