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