initial trivial support for folding branches that have now-constant destinations.
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnswitch.cpp
1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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:
12 //
13 //  for (...)                  if (lic)
14 //    A                          for (...)
15 //    if (lic)                     A; B; C
16 //      B                      else
17 //    C                          for (...)
18 //                                 A; C
19 //
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.
23 //
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.
26 //
27 //===----------------------------------------------------------------------===//
28
29 #define DEBUG_TYPE "loop-unswitch"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Constants.h"
32 #include "llvm/Function.h"
33 #include "llvm/Instructions.h"
34 #include "llvm/Analysis/LoopInfo.h"
35 #include "llvm/Transforms/Utils/Cloning.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/CommandLine.h"
41 #include <algorithm>
42 #include <iostream>
43 #include <set>
44 using namespace llvm;
45
46 namespace {
47   Statistic<> NumBranches("loop-unswitch", "Number of branches unswitched");
48   Statistic<> NumSwitches("loop-unswitch", "Number of switches unswitched");
49   Statistic<> NumSelects ("loop-unswitch", "Number of selects unswitched");
50   Statistic<> NumTrivial ("loop-unswitch",
51                           "Number of unswitches that are trivial");
52   Statistic<> NumSimplify("loop-unswitch", 
53                           "Number of simplifications of unswitched code");
54   cl::opt<unsigned>
55   Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
56             cl::init(10), cl::Hidden);
57   
58   class LoopUnswitch : public FunctionPass {
59     LoopInfo *LI;  // Loop information
60   public:
61     virtual bool runOnFunction(Function &F);
62     bool visitLoop(Loop *L);
63
64     /// This transformation requires natural loop information & requires that
65     /// loop preheaders be inserted into the CFG...
66     ///
67     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68       AU.addRequiredID(LoopSimplifyID);
69       AU.addPreservedID(LoopSimplifyID);
70       AU.addRequired<LoopInfo>();
71       AU.addPreserved<LoopInfo>();
72     }
73
74   private:
75     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
76     unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
77     void VersionLoop(Value *LIC, Constant *OnVal,
78                      Loop *L, Loop *&Out1, Loop *&Out2);
79     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
80                                   bool EntersWhenTrue, BasicBlock *ExitBlock);
81     BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
82     BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
83     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,Constant *Val,
84                                               bool isEqual);
85     bool TryToRemoveEdge(TerminatorInst *TI, unsigned SuccNo,
86                          std::vector<Instruction*> &Worklist);
87   };
88   RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
89 }
90
91 FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
92
93 bool LoopUnswitch::runOnFunction(Function &F) {
94   bool Changed = false;
95   LI = &getAnalysis<LoopInfo>();
96
97   // Transform all the top-level loops.  Copy the loop list so that the child
98   // can update the loop tree if it needs to delete the loop.
99   std::vector<Loop*> SubLoops(LI->begin(), LI->end());
100   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
101     Changed |= visitLoop(SubLoops[i]);
102
103   return Changed;
104 }
105
106
107 /// LoopValuesUsedOutsideLoop - Return true if there are any values defined in
108 /// the loop that are used by instructions outside of it.
109 static bool LoopValuesUsedOutsideLoop(Loop *L) {
110   // We will be doing lots of "loop contains block" queries.  Loop::contains is
111   // linear time, use a set to speed this up.
112   std::set<BasicBlock*> LoopBlocks;
113
114   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
115        BB != E; ++BB)
116     LoopBlocks.insert(*BB);
117   
118   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
119        BB != E; ++BB) {
120     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
121       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
122            ++UI) {
123         BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
124         if (!LoopBlocks.count(UserBB))
125           return true;
126       }
127   }
128   return false;
129 }
130
131 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
132 ///   1. Exit the loop with no side effects.
133 ///   2. Branch to the latch block with no side-effects.
134 ///
135 /// If these conditions are true, we return true and set ExitBB to the block we
136 /// exit through.
137 ///
138 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
139                                          BasicBlock *&ExitBB,
140                                          std::set<BasicBlock*> &Visited) {
141   if (!Visited.insert(BB).second) {
142     // Already visited and Ok, end of recursion.
143     return true;
144   } else if (!L->contains(BB)) {
145     // Otherwise, this is a loop exit, this is fine so long as this is the
146     // first exit.
147     if (ExitBB != 0) return false;
148     ExitBB = BB;
149     return true;
150   }
151   
152   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
153   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
154     // Check to see if the successor is a trivial loop exit.
155     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
156       return false;
157   }
158
159   // Okay, everything after this looks good, check to make sure that this block
160   // doesn't include any side effects.
161   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
162     if (I->mayWriteToMemory())
163       return false;
164   
165   return true;
166 }
167
168 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
169   std::set<BasicBlock*> Visited;
170   Visited.insert(L->getHeader());  // Branches to header are ok.
171   Visited.insert(BB);              // Don't revisit BB after we do.
172   BasicBlock *ExitBB = 0;
173   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
174     return ExitBB;
175   return 0;
176 }
177
178 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
179 /// trivial: that is, that the condition controls whether or not the loop does
180 /// anything at all.  If this is a trivial condition, unswitching produces no
181 /// code duplications (equivalently, it produces a simpler loop and a new empty
182 /// loop, which gets deleted).
183 ///
184 /// If this is a trivial condition, return ConstantBool::True if the loop body
185 /// runs when the condition is true, False if the loop body executes when the
186 /// condition is false.  Otherwise, return null to indicate a complex condition.
187 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond,
188                                        Constant **Val = 0,
189                                        bool *EntersWhenTrue = 0,
190                                        BasicBlock **LoopExit = 0) {
191   BasicBlock *Header = L->getHeader();
192   TerminatorInst *HeaderTerm = Header->getTerminator();
193
194   BasicBlock *LoopExitBB = 0;
195   if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
196     // If the header block doesn't end with a conditional branch on Cond, we
197     // can't handle it.
198     if (!BI->isConditional() || BI->getCondition() != Cond)
199       return false;
200   
201     // Check to see if a successor of the branch is guaranteed to go to the
202     // latch block or exit through a one exit block without having any 
203     // side-effects.  If so, determine the value of Cond that causes it to do
204     // this.
205     if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
206       if (Val) *Val = ConstantBool::False;
207     } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
208       if (Val) *Val = ConstantBool::True;
209     }
210   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
211     // If this isn't a switch on Cond, we can't handle it.
212     if (SI->getCondition() != Cond) return false;
213     
214     // Check to see if a successor of the switch is guaranteed to go to the
215     // latch block or exit through a one exit block without having any 
216     // side-effects.  If so, determine the value of Cond that causes it to do
217     // this.  Note that we can't trivially unswitch on the default case.
218     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
219       if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
220         // Okay, we found a trivial case, remember the value that is trivial.
221         if (Val) *Val = SI->getCaseValue(i);
222         if (EntersWhenTrue) *EntersWhenTrue = false;
223         break;
224       }
225   }
226
227   if (!LoopExitBB)
228     return false;   // Can't handle this.
229   
230   if (LoopExit) *LoopExit = LoopExitBB;
231   
232   // We already know that nothing uses any scalar values defined inside of this
233   // loop.  As such, we just have to check to see if this loop will execute any
234   // side-effecting instructions (e.g. stores, calls, volatile loads) in the
235   // part of the loop that the code *would* execute.  We already checked the
236   // tail, check the header now.
237   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
238     if (I->mayWriteToMemory())
239       return false;
240   return true;
241 }
242
243 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
244 /// we choose to unswitch the specified loop on the specified value.
245 ///
246 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
247   // If the condition is trivial, always unswitch.  There is no code growth for
248   // this case.
249   if (IsTrivialUnswitchCondition(L, LIC))
250     return 0;
251   
252   unsigned Cost = 0;
253   // FIXME: this is brain dead.  It should take into consideration code
254   // shrinkage.
255   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
256        I != E; ++I) {
257     BasicBlock *BB = *I;
258     // Do not include empty blocks in the cost calculation.  This happen due to
259     // loop canonicalization and will be removed.
260     if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
261       continue;
262     
263     // Count basic blocks.
264     ++Cost;
265   }
266
267   return Cost;
268 }
269
270 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
271 /// invariant in the loop, or has an invariant piece, return the invariant.
272 /// Otherwise, return null.
273 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
274   // Constants should be folded, not unswitched on!
275   if (isa<Constant>(Cond)) return false;
276   
277   // TODO: Handle: br (VARIANT|INVARIANT).
278   // TODO: Hoist simple expressions out of loops.
279   if (L->isLoopInvariant(Cond)) return Cond;
280   
281   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
282     if (BO->getOpcode() == Instruction::And ||
283         BO->getOpcode() == Instruction::Or) {
284       // If either the left or right side is invariant, we can unswitch on this,
285       // which will cause the branch to go away in one loop and the condition to
286       // simplify in the other one.
287       if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
288         return LHS;
289       if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
290         return RHS;
291     }
292   
293   return 0;
294 }
295
296 bool LoopUnswitch::visitLoop(Loop *L) {
297   bool Changed = false;
298
299   // Recurse through all subloops before we process this loop.  Copy the loop
300   // list so that the child can update the loop tree if it needs to delete the
301   // loop.
302   std::vector<Loop*> SubLoops(L->begin(), L->end());
303   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
304     Changed |= visitLoop(SubLoops[i]);
305
306   // Loop over all of the basic blocks in the loop.  If we find an interior
307   // block that is branching on a loop-invariant condition, we can unswitch this
308   // loop.
309   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
310        I != E; ++I) {
311     TerminatorInst *TI = (*I)->getTerminator();
312     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
313       // If this isn't branching on an invariant condition, we can't unswitch
314       // it.
315       if (BI->isConditional()) {
316         // See if this, or some part of it, is loop invariant.  If so, we can
317         // unswitch on it if we desire.
318         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
319         if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
320           ++NumBranches;
321           return true;
322         }
323       }      
324     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
325       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
326       if (LoopCond && SI->getNumCases() > 1) {
327         // Find a value to unswitch on:
328         // FIXME: this should chose the most expensive case!
329         Constant *UnswitchVal = SI->getCaseValue(1);
330         if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
331           ++NumSwitches;
332           return true;
333         }
334       }
335     }
336     
337     // Scan the instructions to check for unswitchable values.
338     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); 
339          BBI != E; ++BBI)
340       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
341         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
342         if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
343           ++NumSelects;
344           return true;
345         }
346       }
347   }
348     
349   return Changed;
350 }
351
352 /// UnswitchIfProfitable - We have found that we can unswitch L when
353 /// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
354 /// unswitch the loop, reprocess the pieces, then return true.
355 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
356   // Check to see if it would be profitable to unswitch this loop.
357   if (getLoopUnswitchCost(L, LoopCond) > Threshold) {
358     // FIXME: this should estimate growth by the amount of code shared by the
359     // resultant unswitched loops.
360     //
361     DEBUG(std::cerr << "NOT unswitching loop %"
362                     << L->getHeader()->getName() << ", cost too high: "
363                     << L->getBlocks().size() << "\n");
364     return false;
365   }
366     
367   // If this loop has live-out values, we can't unswitch it. We need something
368   // like loop-closed SSA form in order to know how to insert PHI nodes for
369   // these values.
370   if (LoopValuesUsedOutsideLoop(L)) {
371     DEBUG(std::cerr << "NOT unswitching loop %" << L->getHeader()->getName()
372                     << ", a loop value is used outside loop!\n");
373     return false;
374   }
375       
376   //std::cerr << "BEFORE:\n"; LI->dump();
377   Loop *NewLoop1 = 0, *NewLoop2 = 0;
378  
379   // If this is a trivial condition to unswitch (which results in no code
380   // duplication), do it now.
381   Constant *CondVal;
382   bool EntersWhenTrue = true;
383   BasicBlock *ExitBlock;
384   if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal,
385                                  &EntersWhenTrue, &ExitBlock)) {
386     UnswitchTrivialCondition(L, LoopCond, CondVal, EntersWhenTrue, ExitBlock);
387     NewLoop1 = L;
388   } else {
389     VersionLoop(LoopCond, Val, L, NewLoop1, NewLoop2);
390   }
391   
392   //std::cerr << "AFTER:\n"; LI->dump();
393   
394   // Try to unswitch each of our new loops now!
395   if (NewLoop1) visitLoop(NewLoop1);
396   if (NewLoop2) visitLoop(NewLoop2);
397   return true;
398 }
399
400 /// SplitBlock - Split the specified block at the specified instruction - every
401 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
402 /// to a new block.  The two blocks are joined by an unconditional branch and
403 /// the loop info is updated.
404 ///
405 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
406   BasicBlock::iterator SplitIt = SplitPt;
407   while (isa<PHINode>(SplitIt))
408     ++SplitIt;
409   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
410
411   // The new block lives in whichever loop the old one did.
412   if (Loop *L = LI->getLoopFor(Old))
413     L->addBasicBlockToLoop(New, *LI);
414   
415   return New;
416 }
417
418
419 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
420   TerminatorInst *LatchTerm = BB->getTerminator();
421   unsigned SuccNum = 0;
422   for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
423     assert(i != e && "Didn't find edge?");
424     if (LatchTerm->getSuccessor(i) == Succ) {
425       SuccNum = i;
426       break;
427     }
428   }
429   
430   // If this is a critical edge, let SplitCriticalEdge do it.
431   if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
432     return LatchTerm->getSuccessor(SuccNum);
433
434   // If the edge isn't critical, then BB has a single successor or Succ has a
435   // single pred.  Split the block.
436   BasicBlock::iterator SplitPoint;
437   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
438     // If the successor only has a single pred, split the top of the successor
439     // block.
440     assert(SP == BB && "CFG broken");
441     return SplitBlock(Succ, Succ->begin());
442   } else {
443     // Otherwise, if BB has a single successor, split it at the bottom of the
444     // block.
445     assert(BB->getTerminator()->getNumSuccessors() == 1 &&
446            "Should have a single succ!"); 
447     return SplitBlock(BB, BB->getTerminator());
448   }
449 }
450   
451
452
453 // RemapInstruction - Convert the instruction operands from referencing the
454 // current values into those specified by ValueMap.
455 //
456 static inline void RemapInstruction(Instruction *I,
457                                     std::map<const Value *, Value*> &ValueMap) {
458   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
459     Value *Op = I->getOperand(op);
460     std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
461     if (It != ValueMap.end()) Op = It->second;
462     I->setOperand(op, Op);
463   }
464 }
465
466 /// CloneLoop - Recursively clone the specified loop and all of its children,
467 /// mapping the blocks with the specified map.
468 static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
469                        LoopInfo *LI) {
470   Loop *New = new Loop();
471
472   if (PL)
473     PL->addChildLoop(New);
474   else
475     LI->addTopLevelLoop(New);
476
477   // Add all of the blocks in L to the new loop.
478   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
479        I != E; ++I)
480     if (LI->getLoopFor(*I) == L)
481       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
482
483   // Add all of the subloops to the new loop.
484   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
485     CloneLoop(*I, New, VM, LI);
486
487   return New;
488 }
489
490 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
491 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest.  Insert the
492 /// code immediately before InsertPt.
493 static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
494                                            BasicBlock *TrueDest,
495                                            BasicBlock *FalseDest,
496                                            Instruction *InsertPt) {
497   // Insert a conditional branch on LIC to the two preheaders.  The original
498   // code is the true version and the new code is the false version.
499   Value *BranchVal = LIC;
500   if (!isa<ConstantBool>(Val)) {
501     BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt);
502   } else if (Val != ConstantBool::True) {
503     // We want to enter the new loop when the condition is true.
504     std::swap(TrueDest, FalseDest);
505   }
506
507   // Insert the new branch.
508   new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
509 }
510
511
512 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
513 /// condition in it (a cond branch from its header block to its latch block,
514 /// where the path through the loop that doesn't execute its body has no 
515 /// side-effects), unswitch it.  This doesn't involve any code duplication, just
516 /// moving the conditional branch outside of the loop and updating loop info.
517 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, 
518                                             Constant *Val, bool EntersWhenTrue,
519                                             BasicBlock *ExitBlock) {
520   DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
521         << L->getHeader()->getName() << " [" << L->getBlocks().size()
522         << " blocks] in Function " << L->getHeader()->getParent()->getName()
523         << " on cond: " << *Val << (EntersWhenTrue ? " == " : " != ") << 
524         *Cond << "\n");
525   
526   // First step, split the preheader, so that we know that there is a safe place
527   // to insert the conditional branch.  We will change 'OrigPH' to have a
528   // conditional branch on Cond.
529   BasicBlock *OrigPH = L->getLoopPreheader();
530   BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
531
532   // Now that we have a place to insert the conditional branch, create a place
533   // to branch to: this is the exit block out of the loop that we should
534   // short-circuit to.
535   
536   // Split this block now, so that the loop maintains its exit block, and so
537   // that the jump from the preheader can execute the contents of the exit block
538   // without actually branching to it (the exit block should be dominated by the
539   // loop header, not the preheader).
540   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
541   BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
542     
543   // Okay, now we have a position to branch from and a position to branch to, 
544   // insert the new conditional branch.
545   {
546     BasicBlock *TrueDest = NewPH, *FalseDest = NewExit;
547     if (!EntersWhenTrue) std::swap(TrueDest, FalseDest);
548     EmitPreheaderBranchOnCondition(Cond, Val, TrueDest, FalseDest, 
549                                    OrigPH->getTerminator());
550   }
551   OrigPH->getTerminator()->eraseFromParent();
552
553   // Now that we know that the loop is never entered when this condition is a
554   // particular value, rewrite the loop with this info.  We know that this will
555   // at least eliminate the old branch.
556   RewriteLoopBodyWithConditionConstant(L, Cond, Val, EntersWhenTrue);
557   ++NumTrivial;
558 }
559
560
561 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
562 /// equal Val.  Split it into loop versions and test the condition outside of
563 /// either loop.  Return the loops created as Out1/Out2.
564 void LoopUnswitch::VersionLoop(Value *LIC, Constant *Val, Loop *L,
565                                Loop *&Out1, Loop *&Out2) {
566   Function *F = L->getHeader()->getParent();
567   
568   DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
569                   << L->getHeader()->getName() << " [" << L->getBlocks().size()
570                   << " blocks] in Function " << F->getName()
571                   << " when '" << *Val << "' == " << *LIC << "\n");
572
573   // LoopBlocks contains all of the basic blocks of the loop, including the
574   // preheader of the loop, the body of the loop, and the exit blocks of the 
575   // loop, in that order.
576   std::vector<BasicBlock*> LoopBlocks;
577
578   // First step, split the preheader and exit blocks, and add these blocks to
579   // the LoopBlocks list.
580   BasicBlock *OrigPreheader = L->getLoopPreheader();
581   LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
582
583   // We want the loop to come after the preheader, but before the exit blocks.
584   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
585
586   std::vector<BasicBlock*> ExitBlocks;
587   L->getExitBlocks(ExitBlocks);
588   std::sort(ExitBlocks.begin(), ExitBlocks.end());
589   ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
590                    ExitBlocks.end());
591   
592   // Split all of the edges from inside the loop to their exit blocks.  This
593   // unswitching trivial: no phi nodes to update.
594   unsigned NumBlocks = L->getBlocks().size();
595   
596   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
597     BasicBlock *ExitBlock = ExitBlocks[i];
598     std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
599
600     for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
601       assert(L->contains(Preds[j]) &&
602              "All preds of loop exit blocks must be the same loop!");
603       SplitEdge(Preds[j], ExitBlock);
604     }
605   }
606   
607   // The exit blocks may have been changed due to edge splitting, recompute.
608   ExitBlocks.clear();
609   L->getExitBlocks(ExitBlocks);
610   std::sort(ExitBlocks.begin(), ExitBlocks.end());
611   ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
612                    ExitBlocks.end());
613   
614   // Add exit blocks to the loop blocks.
615   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
616
617   // Next step, clone all of the basic blocks that make up the loop (including
618   // the loop preheader and exit blocks), keeping track of the mapping between
619   // the instructions and blocks.
620   std::vector<BasicBlock*> NewBlocks;
621   NewBlocks.reserve(LoopBlocks.size());
622   std::map<const Value*, Value*> ValueMap;
623   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
624     BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
625     NewBlocks.push_back(New);
626     ValueMap[LoopBlocks[i]] = New;  // Keep the BB mapping.
627   }
628
629   // Splice the newly inserted blocks into the function right before the
630   // original preheader.
631   F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
632                                 NewBlocks[0], F->end());
633
634   // Now we create the new Loop object for the versioned loop.
635   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
636   Loop *ParentLoop = L->getParentLoop();
637   if (ParentLoop) {
638     // Make sure to add the cloned preheader and exit blocks to the parent loop
639     // as well.
640     ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
641   }
642   
643   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
644     BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
645     // The new exit block should be in the same loop as the old one.
646     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
647       ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
648     
649     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
650            "Exit block should have been split to have one successor!");
651     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
652     
653     // If the successor of the exit block had PHI nodes, add an entry for
654     // NewExit.
655     PHINode *PN;
656     for (BasicBlock::iterator I = ExitSucc->begin();
657          (PN = dyn_cast<PHINode>(I)); ++I) {
658       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
659       std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
660       if (It != ValueMap.end()) V = It->second;
661       PN->addIncoming(V, NewExit);
662     }
663   }
664
665   // Rewrite the code to refer to itself.
666   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
667     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
668            E = NewBlocks[i]->end(); I != E; ++I)
669       RemapInstruction(I, ValueMap);
670   
671   // Rewrite the original preheader to select between versions of the loop.
672   BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
673   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
674          "Preheader splitting did not work correctly!");
675
676   // Emit the new branch that selects between the two versions of this loop.
677   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
678   OldBR->eraseFromParent();
679
680   // Now we rewrite the original code to know that the condition is true and the
681   // new code to know that the condition is false.
682   RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
683   RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
684   Out1 = L;
685   Out2 = NewLoop;
686 }
687
688 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
689 /// specified.
690 static void RemoveFromWorklist(Instruction *I, 
691                                std::vector<Instruction*> &Worklist) {
692   std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
693                                                      Worklist.end(), I);
694   while (WI != Worklist.end()) {
695     unsigned Offset = WI-Worklist.begin();
696     Worklist.erase(WI);
697     WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
698   }
699 }
700
701 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
702 /// program, replacing all uses with V and update the worklist.
703 static void ReplaceUsesOfWith(Instruction *I, Value *V, 
704                               std::vector<Instruction*> &Worklist) {
705   DEBUG(std::cerr << "Replace with '" << *V << "': " << *I);
706
707   // Add uses to the worklist, which may be dead now.
708   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
709     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
710       Worklist.push_back(Use);
711
712   // Add users to the worklist which may be simplified now.
713   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
714        UI != E; ++UI)
715     Worklist.push_back(cast<Instruction>(*UI));
716   I->replaceAllUsesWith(V);
717   I->eraseFromParent();
718   RemoveFromWorklist(I, Worklist);
719   ++NumSimplify;
720 }
721
722 /// TryToRemoveEdge - Determine whether this is a case where we're smart enough
723 /// to remove the specified edge from the CFG and know how to update loop
724 /// information.  If it is, update SSA and the loop information for the future
725 /// change, then return true.  If not, return false.
726 bool LoopUnswitch::TryToRemoveEdge(TerminatorInst *TI, unsigned DeadSuccNo,
727                                    std::vector<Instruction*> &Worklist) {
728   BasicBlock *BB = TI->getParent(), *Succ = TI->getSuccessor(DeadSuccNo);
729   Loop *BBLoop = LI->getLoopFor(BB);
730   Loop *SuccLoop = LI->getLoopFor(Succ);
731
732   // If this edge is not in a loop, or if this edge is leaving a loop to a 
733   // non-loop area, this is trivial.
734   if (SuccLoop == 0) {
735     Succ->removePredecessor(BB, true);
736     return true;
737   }
738   
739   return false;
740 }
741
742 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
743 // the value specified by Val in the specified loop, or we know it does NOT have
744 // that value.  Rewrite any uses of LIC or of properties correlated to it.
745 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
746                                                         Constant *Val,
747                                                         bool IsEqual) {
748   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
749   
750   // FIXME: Support correlated properties, like:
751   //  for (...)
752   //    if (li1 < li2)
753   //      ...
754   //    if (li1 > li2)
755   //      ...
756
757   // NotVal - If Val is a bool, this contains its inverse.
758   Constant *NotVal = 0;
759   if (ConstantBool *CB = dyn_cast<ConstantBool>(Val))
760     NotVal = ConstantBool::get(!CB->getValue());
761   
762   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
763   // selects, switches.
764   std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
765
766   std::vector<Instruction*> Worklist;
767   
768   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
769   // in the loop with the appropriate one directly.
770   if (IsEqual || NotVal) {
771     Value *Replacement = NotVal ? NotVal : Val;
772     
773     for (unsigned i = 0, e = Users.size(); i != e; ++i)
774       if (Instruction *U = cast<Instruction>(Users[i])) {
775         if (!L->contains(U->getParent()))
776           continue;
777         U->replaceUsesOfWith(LIC, Replacement);
778         Worklist.push_back(U);
779       }
780   } else {
781     // Otherwise, we don't know the precise value of LIC, but we do know that it
782     // is certainly NOT "Val".  As such, simplify any uses in the loop that we
783     // can.  This case occurs when we unswitch switch statements.
784     for (unsigned i = 0, e = Users.size(); i != e; ++i)
785       if (Instruction *U = cast<Instruction>(Users[i])) {
786         if (!L->contains(U->getParent()))
787           continue;
788
789         Worklist.push_back(U);
790
791         // If we know that LIC is not Val, use this info to simplify code.
792         if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
793           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
794             if (SI->getCaseValue(i) == Val) {
795               // Found a dead case value.  Don't remove PHI nodes in the 
796               // successor if they become single-entry, those PHI nodes may
797               // be in the Users list.
798               SI->getSuccessor(i)->removePredecessor(SI->getParent(), true);
799               SI->removeCase(i);
800               break;
801             }
802           }
803         }
804         
805         // TODO: We could do other simplifications, for example, turning 
806         // LIC == Val -> false.
807       }
808   }
809     
810   // Okay, now that we have simplified some instructions in the loop, walk over
811   // it and constant prop, dce, and fold control flow where possible.  Note that
812   // this is effectively a very simple loop-structure-aware optimizer.
813   while (!Worklist.empty()) {
814     Instruction *I = Worklist.back();
815     Worklist.pop_back();
816     
817     // Simple constant folding.
818     if (Constant *C = ConstantFoldInstruction(I)) {
819       ReplaceUsesOfWith(I, C, Worklist);
820       continue;
821     }
822     
823     // Simple DCE.
824     if (isInstructionTriviallyDead(I)) {
825       DEBUG(std::cerr << "Remove dead instruction '" << *I);
826       
827       // Add uses to the worklist, which may be dead now.
828       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
829         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
830           Worklist.push_back(Use);
831       I->eraseFromParent();
832       RemoveFromWorklist(I, Worklist);
833       ++NumSimplify;
834       continue;
835     }
836     
837     // Special case hacks that appear commonly in unswitched code.
838     switch (I->getOpcode()) {
839     case Instruction::Select:
840       if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
841         ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
842         continue;
843       }
844       break;
845     case Instruction::And:
846       if (isa<ConstantBool>(I->getOperand(0)))   // constant -> RHS
847         cast<BinaryOperator>(I)->swapOperands();
848       if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
849         if (CB->getValue())   // X & 1 -> X
850           ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
851         else                  // X & 0 -> 0
852           ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
853         continue;
854       }
855       break;
856     case Instruction::Or:
857       if (isa<ConstantBool>(I->getOperand(0)))   // constant -> RHS
858         cast<BinaryOperator>(I)->swapOperands();
859       if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
860         if (CB->getValue())   // X | 1 -> 1
861           ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
862         else                  // X | 0 -> X
863           ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
864         continue;
865       }
866       break;
867     case Instruction::Br: {
868       BranchInst *BI = cast<BranchInst>(I);
869       if (BI->isUnconditional()) {
870         // If BI's parent is the only pred of the successor, fold the two blocks
871         // together.
872         BasicBlock *Pred = BI->getParent();
873         BasicBlock *Succ = BI->getSuccessor(0);
874         BasicBlock *SinglePred = Succ->getSinglePredecessor();
875         if (!SinglePred) continue;  // Nothing to do.
876         assert(SinglePred == Pred && "CFG broken");
877
878         DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- " 
879                         << Succ->getName() << "\n");
880         
881         // Resolve any single entry PHI nodes in Succ.
882         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
883           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
884         
885         // Move all of the successor contents from Succ to Pred.
886         Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
887                                    Succ->end());
888         BI->eraseFromParent();
889         RemoveFromWorklist(BI, Worklist);
890         
891         // If Succ has any successors with PHI nodes, update them to have
892         // entries coming from Pred instead of Succ.
893         Succ->replaceAllUsesWith(Pred);
894         
895         // Remove Succ from the loop tree.
896         LI->removeBlock(Succ);
897         Succ->eraseFromParent();
898         ++NumSimplify;
899         break;
900       } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
901         // Conditional branch.
902         if (TryToRemoveEdge(BI, CB->getValue(), Worklist)) {
903           DEBUG(std::cerr << "Folded branch: " << *BI);
904           new BranchInst(BI->getSuccessor(!CB->getValue()), BI);
905           BI->eraseFromParent();
906           RemoveFromWorklist(BI, Worklist);
907           ++NumSimplify;
908           break;
909         }
910       }
911       break;
912     }
913     }
914   }
915 }