1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
51 STATISTIC(NumBranches, "Number of branches unswitched");
52 STATISTIC(NumSwitches, "Number of switches unswitched");
53 STATISTIC(NumSelects , "Number of selects unswitched");
54 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
55 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
57 static cl::opt<unsigned>
58 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
59 cl::init(10), cl::Hidden);
62 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
63 LoopInfo *LI; // Loop information
66 // LoopProcessWorklist - Used to check if second loop needs processing
67 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
68 std::vector<Loop*> LoopProcessWorklist;
69 SmallPtrSet<Value *,8> UnswitchedVals;
75 DominanceFrontier *DF;
77 BasicBlock *loopHeader;
78 BasicBlock *loopPreheader;
80 /// LoopDF - Loop's dominance frontier. This set is a collection of
81 /// loop exiting blocks' DF member blocks. However this does set does not
82 /// includes basic blocks that are inside loop.
83 SmallPtrSet<BasicBlock *, 8> LoopDF;
85 /// OrigLoopExitMap - This is used to map loop exiting block with
86 /// corresponding loop exit block, before updating CFG.
87 DenseMap<BasicBlock *, BasicBlock *> OrigLoopExitMap;
89 // LoopBlocks contains all of the basic blocks of the loop, including the
90 // preheader of the loop, the body of the loop, and the exit blocks of the
91 // loop, in that order.
92 std::vector<BasicBlock*> LoopBlocks;
93 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
94 std::vector<BasicBlock*> NewBlocks;
96 static char ID; // Pass ID, replacement for typeid
97 explicit LoopUnswitch(bool Os = false) :
98 LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false),
99 currentLoop(NULL), DF(NULL), DT(NULL), loopHeader(NULL),
100 loopPreheader(NULL) {}
102 bool runOnLoop(Loop *L, LPPassManager &LPM);
103 bool processCurrentLoop();
105 /// This transformation requires natural loop information & requires that
106 /// loop preheaders be inserted into the CFG...
108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.addRequiredID(LoopSimplifyID);
110 AU.addPreservedID(LoopSimplifyID);
111 AU.addRequired<LoopInfo>();
112 AU.addPreserved<LoopInfo>();
113 AU.addRequiredID(LCSSAID);
114 AU.addPreservedID(LCSSAID);
115 AU.addPreserved<DominatorTree>();
116 AU.addPreserved<DominanceFrontier>();
121 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
123 void RemoveLoopFromWorklist(Loop *L) {
124 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
125 LoopProcessWorklist.end(), L);
126 if (I != LoopProcessWorklist.end())
127 LoopProcessWorklist.erase(I);
130 void initLoopData() {
131 loopHeader = currentLoop->getHeader();
132 loopPreheader = currentLoop->getLoopPreheader();
135 /// Split all of the edges from inside the loop to their exit blocks.
136 /// Update the appropriate Phi nodes as we do so.
137 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks,
138 SmallVector<BasicBlock *, 8> &MiddleBlocks);
140 /// If BB's dominance frontier has a member that is not part of loop L then
141 /// remove it. Add NewDFMember in BB's dominance frontier.
142 void ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
143 BasicBlock *NewDFMember);
145 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
146 unsigned getLoopUnswitchCost(Value *LIC);
147 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
148 BasicBlock *ExitBlock);
149 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
151 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
152 Constant *Val, bool isEqual);
154 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
155 BasicBlock *TrueDest,
156 BasicBlock *FalseDest,
157 Instruction *InsertPt);
159 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
160 void RemoveBlockIfDead(BasicBlock *BB,
161 std::vector<Instruction*> &Worklist, Loop *l);
162 void RemoveLoopFromHierarchy(Loop *L);
163 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
164 BasicBlock **LoopExit = 0);
168 char LoopUnswitch::ID = 0;
169 static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
171 LoopPass *llvm::createLoopUnswitchPass(bool Os) {
172 return new LoopUnswitch(Os);
175 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
176 /// invariant in the loop, or has an invariant piece, return the invariant.
177 /// Otherwise, return null.
178 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
179 // Constants should be folded, not unswitched on!
180 if (isa<Constant>(Cond)) return false;
182 // TODO: Handle: br (VARIANT|INVARIANT).
183 // TODO: Hoist simple expressions out of loops.
184 if (L->isLoopInvariant(Cond)) return Cond;
186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
187 if (BO->getOpcode() == Instruction::And ||
188 BO->getOpcode() == Instruction::Or) {
189 // If either the left or right side is invariant, we can unswitch on this,
190 // which will cause the branch to go away in one loop and the condition to
191 // simplify in the other one.
192 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
194 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
201 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
202 LI = &getAnalysis<LoopInfo>();
204 DF = getAnalysisToUpdate<DominanceFrontier>();
205 DT = getAnalysisToUpdate<DominatorTree>();
207 bool Changed = false;
209 assert(currentLoop->isLCSSAForm());
211 Changed |= processCurrentLoop();
217 /// processCurrentLoop - Do actual work and unswitch loop if possible
219 bool LoopUnswitch::processCurrentLoop() {
220 bool Changed = false;
222 // Loop over all of the basic blocks in the loop. If we find an interior
223 // block that is branching on a loop-invariant condition, we can unswitch this
225 for (Loop::block_iterator I = currentLoop->block_begin(),
226 E = currentLoop->block_end();
228 TerminatorInst *TI = (*I)->getTerminator();
229 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
230 // If this isn't branching on an invariant condition, we can't unswitch
232 if (BI->isConditional()) {
233 // See if this, or some part of it, is loop invariant. If so, we can
234 // unswitch on it if we desire.
235 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
236 currentLoop, Changed);
237 if (LoopCond && UnswitchIfProfitable(LoopCond,
238 ConstantInt::getTrue())) {
243 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
244 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
245 currentLoop, Changed);
246 if (LoopCond && SI->getNumCases() > 1) {
247 // Find a value to unswitch on:
248 // FIXME: this should chose the most expensive case!
249 Constant *UnswitchVal = SI->getCaseValue(1);
250 // Do not process same value again and again.
251 if (!UnswitchedVals.insert(UnswitchVal))
254 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
261 // Scan the instructions to check for unswitchable values.
262 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
264 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
265 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
266 currentLoop, Changed);
267 if (LoopCond && UnswitchIfProfitable(LoopCond,
268 ConstantInt::getTrue())) {
277 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
278 /// 1. Exit the loop with no side effects.
279 /// 2. Branch to the latch block with no side-effects.
281 /// If these conditions are true, we return true and set ExitBB to the block we
284 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
286 std::set<BasicBlock*> &Visited) {
287 if (!Visited.insert(BB).second) {
288 // Already visited and Ok, end of recursion.
290 } else if (!L->contains(BB)) {
291 // Otherwise, this is a loop exit, this is fine so long as this is the
293 if (ExitBB != 0) return false;
298 // Otherwise, this is an unvisited intra-loop node. Check all successors.
299 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
300 // Check to see if the successor is a trivial loop exit.
301 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
305 // Okay, everything after this looks good, check to make sure that this block
306 // doesn't include any side effects.
307 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
308 if (I->mayWriteToMemory())
314 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
315 /// leads to an exit from the specified loop, and has no side-effects in the
316 /// process. If so, return the block that is exited to, otherwise return null.
317 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
318 std::set<BasicBlock*> Visited;
319 Visited.insert(L->getHeader()); // Branches to header are ok.
320 BasicBlock *ExitBB = 0;
321 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
326 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
327 /// trivial: that is, that the condition controls whether or not the loop does
328 /// anything at all. If this is a trivial condition, unswitching produces no
329 /// code duplications (equivalently, it produces a simpler loop and a new empty
330 /// loop, which gets deleted).
332 /// If this is a trivial condition, return true, otherwise return false. When
333 /// returning true, this sets Cond and Val to the condition that controls the
334 /// trivial condition: when Cond dynamically equals Val, the loop is known to
335 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
338 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
339 BasicBlock **LoopExit) {
340 BasicBlock *Header = currentLoop->getHeader();
341 TerminatorInst *HeaderTerm = Header->getTerminator();
343 BasicBlock *LoopExitBB = 0;
344 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
345 // If the header block doesn't end with a conditional branch on Cond, we
347 if (!BI->isConditional() || BI->getCondition() != Cond)
350 // Check to see if a successor of the branch is guaranteed to go to the
351 // latch block or exit through a one exit block without having any
352 // side-effects. If so, determine the value of Cond that causes it to do
354 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
355 BI->getSuccessor(0)))) {
356 if (Val) *Val = ConstantInt::getTrue();
357 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
358 BI->getSuccessor(1)))) {
359 if (Val) *Val = ConstantInt::getFalse();
361 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
362 // If this isn't a switch on Cond, we can't handle it.
363 if (SI->getCondition() != Cond) return false;
365 // Check to see if a successor of the switch is guaranteed to go to the
366 // latch block or exit through a one exit block without having any
367 // side-effects. If so, determine the value of Cond that causes it to do
368 // this. Note that we can't trivially unswitch on the default case.
369 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
370 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
371 SI->getSuccessor(i)))) {
372 // Okay, we found a trivial case, remember the value that is trivial.
373 if (Val) *Val = SI->getCaseValue(i);
378 // If we didn't find a single unique LoopExit block, or if the loop exit block
379 // contains phi nodes, this isn't trivial.
380 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
381 return false; // Can't handle this.
383 if (LoopExit) *LoopExit = LoopExitBB;
385 // We already know that nothing uses any scalar values defined inside of this
386 // loop. As such, we just have to check to see if this loop will execute any
387 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
388 // part of the loop that the code *would* execute. We already checked the
389 // tail, check the header now.
390 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
391 if (I->mayWriteToMemory())
396 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
397 /// we choose to unswitch current loop on the specified value.
399 unsigned LoopUnswitch::getLoopUnswitchCost(Value *LIC) {
400 // If the condition is trivial, always unswitch. There is no code growth for
402 if (IsTrivialUnswitchCondition(LIC))
405 // FIXME: This is really overly conservative. However, more liberal
406 // estimations have thus far resulted in excessive unswitching, which is bad
407 // both in compile time and in code size. This should be replaced once
408 // someone figures out how a good estimation.
409 return currentLoop->getBlocks().size();
412 // FIXME: this is brain dead. It should take into consideration code
414 for (Loop::block_iterator I = currentLoop->block_begin(),
415 E = currentLoop->block_end();
418 // Do not include empty blocks in the cost calculation. This happen due to
419 // loop canonicalization and will be removed.
420 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
423 // Count basic blocks.
430 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
431 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
432 /// unswitch the loop, reprocess the pieces, then return true.
433 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
434 // Check to see if it would be profitable to unswitch current loop.
435 unsigned Cost = getLoopUnswitchCost(LoopCond);
437 // Do not do non-trivial unswitch while optimizing for size.
438 if (Cost && OptimizeForSize)
441 if (Cost > Threshold) {
442 // FIXME: this should estimate growth by the amount of code shared by the
443 // resultant unswitched loops.
445 DOUT << "NOT unswitching loop %"
446 << currentLoop->getHeader()->getName() << ", cost too high: "
447 << currentLoop->getBlocks().size() << "\n";
454 BasicBlock *ExitBlock;
455 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
456 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
458 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
461 // FIXME: Reconstruct dom info, because it is not preserved properly.
462 Function *F = loopHeader->getParent();
464 DT->runOnFunction(*F);
466 DF->runOnFunction(*F);
470 // RemapInstruction - Convert the instruction operands from referencing the
471 // current values into those specified by ValueMap.
473 static inline void RemapInstruction(Instruction *I,
474 DenseMap<const Value *, Value*> &ValueMap) {
475 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
476 Value *Op = I->getOperand(op);
477 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
478 if (It != ValueMap.end()) Op = It->second;
479 I->setOperand(op, Op);
483 // CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator
486 // If Orig block's immediate dominator is mapped in VM then use corresponding
487 // immediate dominator from the map. Otherwise Orig block's dominator is also
488 // NewBB's dominator.
490 // OrigPreheader is loop pre-header before this pass started
491 // updating CFG. NewPrehader is loops new pre-header. However, after CFG
492 // manipulation, loop L may not exist. So rely on input parameter NewPreheader.
493 static void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
494 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
495 BasicBlock *OrigHeader,
496 DominatorTree *DT, DominanceFrontier *DF,
497 DenseMap<const Value*, Value*> &VM) {
499 // If NewBB alreay has found its place in domiantor tree then no need to do
501 if (DT->getNode(NewBB))
504 // If Orig does not have any immediate domiantor then its clone, NewBB, does
505 // not need any immediate dominator.
506 DomTreeNode *OrigNode = DT->getNode(Orig);
509 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
513 BasicBlock *OrigIDom = NULL;
515 // If Orig is original loop header then its immediate dominator is
517 if (Orig == OrigHeader)
518 OrigIDom = NewPreheader;
520 // If Orig is new pre-header then its immediate dominator is
521 // original pre-header.
522 else if (Orig == NewPreheader)
523 OrigIDom = OrigPreheader;
525 // Otherwise ask DT to find Orig's immediate dominator.
527 OrigIDom = OrigIDomNode->getBlock();
529 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
530 BasicBlock *NewIDom = OrigIDom;
531 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
533 NewIDom = cast<BasicBlock>(I->second);
535 // If NewIDom does not have corresponding dominatore tree node then
537 if (!DT->getNode(NewIDom))
538 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
539 OrigHeader, DT, DF, VM);
542 DT->addNewBlock(NewBB, NewIDom);
544 // Copy cloned dominance frontiner set
545 DominanceFrontier::DomSetType NewDFSet;
547 DominanceFrontier::iterator DFI = DF->find(Orig);
548 if ( DFI != DF->end()) {
549 DominanceFrontier::DomSetType S = DFI->second;
550 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
553 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
555 NewDFSet.insert(cast<BasicBlock>(IDM->second));
560 DF->addBasicBlock(NewBB, NewDFSet);
564 /// CloneLoop - Recursively clone the specified loop and all of its children,
565 /// mapping the blocks with the specified map.
566 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
567 LoopInfo *LI, LPPassManager *LPM) {
568 Loop *New = new Loop();
570 LPM->insertLoop(New, PL);
572 // Add all of the blocks in L to the new loop.
573 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
575 if (LI->getLoopFor(*I) == L)
576 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
578 // Add all of the subloops to the new loop.
579 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
580 CloneLoop(*I, New, VM, LI, LPM);
585 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
586 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
587 /// code immediately before InsertPt.
588 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
589 BasicBlock *TrueDest,
590 BasicBlock *FalseDest,
591 Instruction *InsertPt) {
592 // Insert a conditional branch on LIC to the two preheaders. The original
593 // code is the true version and the new code is the false version.
594 Value *BranchVal = LIC;
595 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
596 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
597 else if (Val != ConstantInt::getTrue())
598 // We want to enter the new loop when the condition is true.
599 std::swap(TrueDest, FalseDest);
601 // Insert the new branch.
602 BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
606 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
607 /// condition in it (a cond branch from its header block to its latch block,
608 /// where the path through the loop that doesn't execute its body has no
609 /// side-effects), unswitch it. This doesn't involve any code duplication, just
610 /// moving the conditional branch outside of the loop and updating loop info.
611 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
613 BasicBlock *ExitBlock) {
614 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
615 << loopHeader->getName() << " [" << L->getBlocks().size()
616 << " blocks] in Function " << L->getHeader()->getParent()->getName()
617 << " on cond: " << *Val << " == " << *Cond << "\n";
619 // First step, split the preheader, so that we know that there is a safe place
620 // to insert the conditional branch. We will change loopPreheader to have a
621 // conditional branch on Cond.
622 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
624 // Now that we have a place to insert the conditional branch, create a place
625 // to branch to: this is the exit block out of the loop that we should
628 // Split this block now, so that the loop maintains its exit block, and so
629 // that the jump from the preheader can execute the contents of the exit block
630 // without actually branching to it (the exit block should be dominated by the
631 // loop header, not the preheader).
632 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
633 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
635 // Okay, now we have a position to branch from and a position to branch to,
636 // insert the new conditional branch.
637 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
638 loopPreheader->getTerminator());
640 DT->changeImmediateDominator(NewExit, loopPreheader);
641 DT->changeImmediateDominator(NewPH, loopPreheader);
645 // NewExit is now part of NewPH and Loop Header's dominance
647 DominanceFrontier::iterator DFI = DF->find(NewPH);
648 if (DFI != DF->end())
649 DF->addToFrontier(DFI, NewExit);
650 DFI = DF->find(loopHeader);
651 DF->addToFrontier(DFI, NewExit);
653 // ExitBlock does not have successors then NewExit is part of
654 // its dominance frontier.
655 if (succ_begin(ExitBlock) == succ_end(ExitBlock)) {
656 DFI = DF->find(ExitBlock);
657 DF->addToFrontier(DFI, NewExit);
660 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
661 loopPreheader->getTerminator()->eraseFromParent();
663 // We need to reprocess this loop, it could be unswitched again.
666 // Now that we know that the loop is never entered when this condition is a
667 // particular value, rewrite the loop with this info. We know that this will
668 // at least eliminate the old branch.
669 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
673 /// ReplaceLoopExternalDFMember -
674 /// If BB's dominance frontier has a member that is not part of loop L then
675 /// remove it. Add NewDFMember in BB's dominance frontier.
676 void LoopUnswitch::ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
677 BasicBlock *NewDFMember) {
679 DominanceFrontier::iterator DFI = DF->find(BB);
680 if (DFI == DF->end())
683 DominanceFrontier::DomSetType &DFSet = DFI->second;
684 for (DominanceFrontier::DomSetType::iterator DI = DFSet.begin(),
685 DE = DFSet.end(); DI != DE;) {
686 BasicBlock *B = *DI++;
690 DF->removeFromFrontier(DFI, B);
694 DF->addToFrontier(DFI, NewDFMember);
697 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
698 /// blocks. Update the appropriate Phi nodes as we do so.
699 void LoopUnswitch::SplitExitEdges(Loop *L,
700 const SmallVector<BasicBlock *, 8> &ExitBlocks,
701 SmallVector<BasicBlock *, 8> &MiddleBlocks) {
703 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
704 BasicBlock *ExitBlock = ExitBlocks[i];
705 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
707 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
708 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
709 MiddleBlocks.push_back(MiddleBlock);
710 BasicBlock* StartBlock = Preds[j];
711 BasicBlock* EndBlock;
712 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
713 EndBlock = MiddleBlock;
714 MiddleBlock = EndBlock->getSinglePredecessor();;
716 EndBlock = ExitBlock;
719 OrigLoopExitMap[StartBlock] = EndBlock;
721 std::set<PHINode*> InsertedPHIs;
722 PHINode* OldLCSSA = 0;
723 for (BasicBlock::iterator I = EndBlock->begin();
724 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
725 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
726 PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
727 OldLCSSA->getName() + ".us-lcssa",
728 MiddleBlock->getTerminator());
729 NewLCSSA->addIncoming(OldValue, StartBlock);
730 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
732 InsertedPHIs.insert(NewLCSSA);
735 BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
736 for (BasicBlock::iterator I = MiddleBlock->begin();
737 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
739 PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
740 OldLCSSA->getName() + ".us-lcssa",
742 OldLCSSA->replaceAllUsesWith(NewLCSSA);
743 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
747 // StartBlock -- > MiddleBlock -- > EndBlock
748 // StartBlock is loop exiting block. EndBlock will become merge point
749 // of two loop exits after loop unswitch.
751 // If StartBlock's DF member includes a block that is not loop member
752 // then replace that DF member with EndBlock.
754 // If MiddleBlock's DF member includes a block that is not loop member
755 // tnen replace that DF member with EndBlock.
757 ReplaceLoopExternalDFMember(L, StartBlock, EndBlock);
758 ReplaceLoopExternalDFMember(L, MiddleBlock, EndBlock);
765 /// addBBToDomFrontier - Helper function. Insert DFBB in Basic Block BB's
766 /// dominance frontier using iterator DFI.
767 static void addBBToDomFrontier(DominanceFrontier &DF,
768 DominanceFrontier::iterator &DFI,
769 BasicBlock *BB, BasicBlock *DFBB) {
770 if (DFI != DF.end()) {
771 DF.addToFrontier(DFI, DFBB);
775 DominanceFrontier::DomSetType NSet;
777 DF.addBasicBlock(BB, NSet);
781 /// UnswitchNontrivialCondition - We determined that the loop is profitable
782 /// to unswitch when LIC equal Val. Split it into loop versions and test the
783 /// condition outside of either loop. Return the loops created as Out1/Out2.
784 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
786 Function *F = loopHeader->getParent();
787 DOUT << "loop-unswitch: Unswitching loop %"
788 << loopHeader->getName() << " [" << L->getBlocks().size()
789 << " blocks] in Function " << F->getName()
790 << " when '" << *Val << "' == " << *LIC << "\n";
795 // First step, split the preheader and exit blocks, and add these blocks to
796 // the LoopBlocks list.
797 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
798 LoopBlocks.push_back(NewPreheader);
800 // We want the loop to come after the preheader, but before the exit blocks.
801 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
803 SmallVector<BasicBlock*, 8> ExitBlocks;
804 L->getUniqueExitBlocks(ExitBlocks);
806 // Split all of the edges from inside the loop to their exit blocks. Update
807 // the appropriate Phi nodes as we do so.
808 SmallVector<BasicBlock *,8> MiddleBlocks;
809 SplitExitEdges(L, ExitBlocks, MiddleBlocks);
811 // The exit blocks may have been changed due to edge splitting, recompute.
813 L->getUniqueExitBlocks(ExitBlocks);
815 // Add exit blocks to the loop blocks.
816 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
818 // Next step, clone all of the basic blocks that make up the loop (including
819 // the loop preheader and exit blocks), keeping track of the mapping between
820 // the instructions and blocks.
821 NewBlocks.reserve(LoopBlocks.size());
822 DenseMap<const Value*, Value*> ValueMap;
823 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
824 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
825 NewBlocks.push_back(New);
826 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
827 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
830 // OutSiders are basic block that are dominated by original header and
831 // at the same time they are not part of loop.
832 SmallPtrSet<BasicBlock *, 8> OutSiders;
834 DomTreeNode *OrigHeaderNode = DT->getNode(loopHeader);
835 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
836 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
837 BasicBlock *B = (*DI)->getBlock();
839 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
840 if (VI == ValueMap.end())
845 // Splice the newly inserted blocks into the function right before the
846 // original preheader.
847 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
848 NewBlocks[0], F->end());
850 // Now we create the new Loop object for the versioned loop.
851 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
852 Loop *ParentLoop = L->getParentLoop();
854 // Make sure to add the cloned preheader and exit blocks to the parent loop
856 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
859 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
860 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
861 // The new exit block should be in the same loop as the old one.
862 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
863 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
865 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
866 "Exit block should have been split to have one successor!");
867 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
869 // If the successor of the exit block had PHI nodes, add an entry for
872 for (BasicBlock::iterator I = ExitSucc->begin();
873 (PN = dyn_cast<PHINode>(I)); ++I) {
874 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
875 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
876 if (It != ValueMap.end()) V = It->second;
877 PN->addIncoming(V, NewExit);
881 // Rewrite the code to refer to itself.
882 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
883 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
884 E = NewBlocks[i]->end(); I != E; ++I)
885 RemapInstruction(I, ValueMap);
887 // Rewrite the original preheader to select between versions of the loop.
888 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
889 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
890 "Preheader splitting did not work correctly!");
892 // Emit the new branch that selects between the two versions of this loop.
893 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
894 LPM->deleteSimpleAnalysisValue(OldBR, L);
895 OldBR->eraseFromParent();
897 // Update dominator info
900 SmallVector<BasicBlock *,4> ExitingBlocks;
901 L->getExitingBlocks(ExitingBlocks);
903 // Clone dominator info for all cloned basic block.
904 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
905 BasicBlock *LBB = LoopBlocks[i];
906 BasicBlock *NBB = NewBlocks[i];
907 CloneDomInfo(NBB, LBB, NewPreheader, loopPreheader,
908 loopHeader, DT, DF, ValueMap);
910 // If LBB's dominance frontier includes DFMember
911 // such that DFMember is also a member of LoopDF then
912 // - Remove DFMember from LBB's dominance frontier
913 // - Copy loop exiting blocks', that are dominated by BB,
914 // dominance frontier member in BB's dominance frontier
916 DominanceFrontier::iterator LBBI = DF->find(LBB);
917 DominanceFrontier::iterator NBBI = DF->find(NBB);
918 if (LBBI == DF->end())
921 DominanceFrontier::DomSetType &LBSet = LBBI->second;
922 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
923 LE = LBSet.end(); LI != LE; /* NULL */) {
924 BasicBlock *B = *LI++;
925 if (B == LBB && B == loopHeader)
927 bool removeB = false;
928 if (!LoopDF.count(B))
931 // If LBB dominates loop exits then insert loop exit block's DF
933 for(SmallVector<BasicBlock *, 4>::iterator
934 LExitI = ExitingBlocks.begin(),
935 LExitE = ExitingBlocks.end(); LExitI != LExitE; ++LExitI) {
936 BasicBlock *E = *LExitI;
938 if (!DT->dominates(LBB,E))
941 DenseMap<BasicBlock *, BasicBlock *>::iterator DFBI =
942 OrigLoopExitMap.find(E);
943 if (DFBI == OrigLoopExitMap.end())
946 BasicBlock *DFB = DFBI->second;
947 DF->addToFrontier(LBBI, DFB);
948 DF->addToFrontier(NBBI, DFB);
952 // If B's replacement is inserted in DF then now is the time to remove
955 DF->removeFromFrontier(LBBI, B);
957 DF->removeFromFrontier(NBBI, cast<BasicBlock>(ValueMap[B]));
959 DF->removeFromFrontier(NBBI, B);
965 // MiddleBlocks are dominated by original pre header. SplitEdge updated
966 // MiddleBlocks' dominance frontier appropriately.
967 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
968 BasicBlock *MBB = MiddleBlocks[i];
969 if (!MBB->getSinglePredecessor())
970 DT->changeImmediateDominator(MBB, loopPreheader);
973 // All Outsiders are now dominated by original pre header.
974 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
975 OE = OutSiders.end(); OI != OE; ++OI) {
976 BasicBlock *OB = *OI;
977 DT->changeImmediateDominator(OB, loopPreheader);
980 // New loop headers are dominated by original preheader
981 DT->changeImmediateDominator(NewBlocks[0], loopPreheader);
982 DT->changeImmediateDominator(LoopBlocks[0], loopPreheader);
985 LoopProcessWorklist.push_back(NewLoop);
988 // Now we rewrite the original code to know that the condition is true and the
989 // new code to know that the condition is false.
990 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
992 // It's possible that simplifying one loop could cause the other to be
993 // deleted. If so, don't simplify it.
994 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
995 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
998 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
1000 static void RemoveFromWorklist(Instruction *I,
1001 std::vector<Instruction*> &Worklist) {
1002 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
1004 while (WI != Worklist.end()) {
1005 unsigned Offset = WI-Worklist.begin();
1007 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
1011 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
1012 /// program, replacing all uses with V and update the worklist.
1013 static void ReplaceUsesOfWith(Instruction *I, Value *V,
1014 std::vector<Instruction*> &Worklist,
1015 Loop *L, LPPassManager *LPM) {
1016 DOUT << "Replace with '" << *V << "': " << *I;
1018 // Add uses to the worklist, which may be dead now.
1019 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1020 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1021 Worklist.push_back(Use);
1023 // Add users to the worklist which may be simplified now.
1024 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1026 Worklist.push_back(cast<Instruction>(*UI));
1027 LPM->deleteSimpleAnalysisValue(I, L);
1028 RemoveFromWorklist(I, Worklist);
1029 I->replaceAllUsesWith(V);
1030 I->eraseFromParent();
1034 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
1035 /// information, and remove any dead successors it has.
1037 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
1038 std::vector<Instruction*> &Worklist,
1040 if (pred_begin(BB) != pred_end(BB)) {
1041 // This block isn't dead, since an edge to BB was just removed, see if there
1042 // are any easy simplifications we can do now.
1043 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1044 // If it has one pred, fold phi nodes in BB.
1045 while (isa<PHINode>(BB->begin()))
1046 ReplaceUsesOfWith(BB->begin(),
1047 cast<PHINode>(BB->begin())->getIncomingValue(0),
1050 // If this is the header of a loop and the only pred is the latch, we now
1051 // have an unreachable loop.
1052 if (Loop *L = LI->getLoopFor(BB))
1053 if (loopHeader == BB && L->contains(Pred)) {
1054 // Remove the branch from the latch to the header block, this makes
1055 // the header dead, which will make the latch dead (because the header
1056 // dominates the latch).
1057 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
1058 Pred->getTerminator()->eraseFromParent();
1059 new UnreachableInst(Pred);
1061 // The loop is now broken, remove it from LI.
1062 RemoveLoopFromHierarchy(L);
1064 // Reprocess the header, which now IS dead.
1065 RemoveBlockIfDead(BB, Worklist, L);
1069 // If pred ends in a uncond branch, add uncond branch to worklist so that
1070 // the two blocks will get merged.
1071 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
1072 if (BI->isUnconditional())
1073 Worklist.push_back(BI);
1078 DOUT << "Nuking dead block: " << *BB;
1080 // Remove the instructions in the basic block from the worklist.
1081 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1082 RemoveFromWorklist(I, Worklist);
1084 // Anything that uses the instructions in this basic block should have their
1085 // uses replaced with undefs.
1086 if (!I->use_empty())
1087 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1090 // If this is the edge to the header block for a loop, remove the loop and
1091 // promote all subloops.
1092 if (Loop *BBLoop = LI->getLoopFor(BB)) {
1093 if (BBLoop->getLoopLatch() == BB)
1094 RemoveLoopFromHierarchy(BBLoop);
1097 // Remove the block from the loop info, which removes it from any loops it
1099 LI->removeBlock(BB);
1102 // Remove phi node entries in successors for this block.
1103 TerminatorInst *TI = BB->getTerminator();
1104 std::vector<BasicBlock*> Succs;
1105 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1106 Succs.push_back(TI->getSuccessor(i));
1107 TI->getSuccessor(i)->removePredecessor(BB);
1110 // Unique the successors, remove anything with multiple uses.
1111 std::sort(Succs.begin(), Succs.end());
1112 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
1114 // Remove the basic block, including all of the instructions contained in it.
1115 LPM->deleteSimpleAnalysisValue(BB, L);
1116 BB->eraseFromParent();
1117 // Remove successor blocks here that are not dead, so that we know we only
1118 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
1119 // then getting removed before we revisit them, which is badness.
1121 for (unsigned i = 0; i != Succs.size(); ++i)
1122 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
1123 // One exception is loop headers. If this block was the preheader for a
1124 // loop, then we DO want to visit the loop so the loop gets deleted.
1125 // We know that if the successor is a loop header, that this loop had to
1126 // be the preheader: the case where this was the latch block was handled
1127 // above and headers can only have two predecessors.
1128 if (!LI->isLoopHeader(Succs[i])) {
1129 Succs.erase(Succs.begin()+i);
1134 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
1135 RemoveBlockIfDead(Succs[i], Worklist, L);
1138 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
1139 /// become unwrapped, either because the backedge was deleted, or because the
1140 /// edge into the header was removed. If the edge into the header from the
1141 /// latch block was removed, the loop is unwrapped but subloops are still alive,
1142 /// so they just reparent loops. If the loops are actually dead, they will be
1144 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
1145 LPM->deleteLoopFromQueue(L);
1146 RemoveLoopFromWorklist(L);
1151 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1152 // the value specified by Val in the specified loop, or we know it does NOT have
1153 // that value. Rewrite any uses of LIC or of properties correlated to it.
1154 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1157 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1159 // FIXME: Support correlated properties, like:
1166 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1167 // selects, switches.
1168 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
1169 std::vector<Instruction*> Worklist;
1171 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1172 // in the loop with the appropriate one directly.
1173 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
1178 Replacement = ConstantInt::get(Type::Int1Ty,
1179 !cast<ConstantInt>(Val)->getZExtValue());
1181 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1182 if (Instruction *U = cast<Instruction>(Users[i])) {
1183 if (!L->contains(U->getParent()))
1185 U->replaceUsesOfWith(LIC, Replacement);
1186 Worklist.push_back(U);
1189 // Otherwise, we don't know the precise value of LIC, but we do know that it
1190 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1191 // can. This case occurs when we unswitch switch statements.
1192 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1193 if (Instruction *U = cast<Instruction>(Users[i])) {
1194 if (!L->contains(U->getParent()))
1197 Worklist.push_back(U);
1199 // If we know that LIC is not Val, use this info to simplify code.
1200 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1201 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1202 if (SI->getCaseValue(i) == Val) {
1203 // Found a dead case value. Don't remove PHI nodes in the
1204 // successor if they become single-entry, those PHI nodes may
1205 // be in the Users list.
1207 // FIXME: This is a hack. We need to keep the successor around
1208 // and hooked up so as to preserve the loop structure, because
1209 // trying to update it is complicated. So instead we preserve the
1210 // loop structure and put the block on an dead code path.
1212 BasicBlock* Old = SI->getParent();
1213 BasicBlock* Split = SplitBlock(Old, SI, this);
1215 Instruction* OldTerm = Old->getTerminator();
1216 BranchInst::Create(Split, SI->getSuccessor(i),
1217 ConstantInt::getTrue(), OldTerm);
1219 LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
1220 Old->getTerminator()->eraseFromParent();
1223 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
1224 (PN = dyn_cast<PHINode>(II)); ++II) {
1225 Value *InVal = PN->removeIncomingValue(Split, false);
1226 PN->addIncoming(InVal, Old);
1235 // TODO: We could do other simplifications, for example, turning
1236 // LIC == Val -> false.
1240 SimplifyCode(Worklist, L);
1243 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1244 /// loop, walk over it and constant prop, dce, and fold control flow where
1245 /// possible. Note that this is effectively a very simple loop-structure-aware
1246 /// optimizer. During processing of this loop, L could very well be deleted, so
1247 /// it must not be used.
1249 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1252 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1253 while (!Worklist.empty()) {
1254 Instruction *I = Worklist.back();
1255 Worklist.pop_back();
1257 // Simple constant folding.
1258 if (Constant *C = ConstantFoldInstruction(I)) {
1259 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
1264 if (isInstructionTriviallyDead(I)) {
1265 DOUT << "Remove dead instruction '" << *I;
1267 // Add uses to the worklist, which may be dead now.
1268 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1269 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1270 Worklist.push_back(Use);
1271 LPM->deleteSimpleAnalysisValue(I, L);
1272 RemoveFromWorklist(I, Worklist);
1273 I->eraseFromParent();
1278 // Special case hacks that appear commonly in unswitched code.
1279 switch (I->getOpcode()) {
1280 case Instruction::Select:
1281 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1282 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1287 case Instruction::And:
1288 if (isa<ConstantInt>(I->getOperand(0)) &&
1289 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1290 cast<BinaryOperator>(I)->swapOperands();
1291 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1292 if (CB->getType() == Type::Int1Ty) {
1293 if (CB->isOne()) // X & 1 -> X
1294 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1296 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1300 case Instruction::Or:
1301 if (isa<ConstantInt>(I->getOperand(0)) &&
1302 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1303 cast<BinaryOperator>(I)->swapOperands();
1304 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1305 if (CB->getType() == Type::Int1Ty) {
1306 if (CB->isOne()) // X | 1 -> 1
1307 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1309 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1313 case Instruction::Br: {
1314 BranchInst *BI = cast<BranchInst>(I);
1315 if (BI->isUnconditional()) {
1316 // If BI's parent is the only pred of the successor, fold the two blocks
1318 BasicBlock *Pred = BI->getParent();
1319 BasicBlock *Succ = BI->getSuccessor(0);
1320 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1321 if (!SinglePred) continue; // Nothing to do.
1322 assert(SinglePred == Pred && "CFG broken");
1324 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1325 << Succ->getName() << "\n";
1327 // Resolve any single entry PHI nodes in Succ.
1328 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1329 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1331 // Move all of the successor contents from Succ to Pred.
1332 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1334 LPM->deleteSimpleAnalysisValue(BI, L);
1335 BI->eraseFromParent();
1336 RemoveFromWorklist(BI, Worklist);
1338 // If Succ has any successors with PHI nodes, update them to have
1339 // entries coming from Pred instead of Succ.
1340 Succ->replaceAllUsesWith(Pred);
1342 // Remove Succ from the loop tree.
1343 LI->removeBlock(Succ);
1344 LPM->deleteSimpleAnalysisValue(Succ, L);
1345 Succ->eraseFromParent();
1347 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1348 // Conditional branch. Turn it into an unconditional branch, then
1349 // remove dead blocks.
1350 break; // FIXME: Enable.
1352 DOUT << "Folded branch: " << *BI;
1353 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1354 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1355 DeadSucc->removePredecessor(BI->getParent(), true);
1356 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
1357 LPM->deleteSimpleAnalysisValue(BI, L);
1358 BI->eraseFromParent();
1359 RemoveFromWorklist(BI, Worklist);
1362 RemoveBlockIfDead(DeadSucc, Worklist, L);