implement unswitching of loops with switch stmts and selects in them
[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<> NumUnswitched("loop-unswitch", "Number of loops unswitched");
48   cl::opt<unsigned>
49   Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
50             cl::init(10), cl::Hidden);
51   
52   class LoopUnswitch : public FunctionPass {
53     LoopInfo *LI;  // Loop information
54   public:
55     virtual bool runOnFunction(Function &F);
56     bool visitLoop(Loop *L);
57
58     /// This transformation requires natural loop information & requires that
59     /// loop preheaders be inserted into the CFG...
60     ///
61     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62       AU.addRequiredID(LoopSimplifyID);
63       AU.addPreservedID(LoopSimplifyID);
64       AU.addRequired<LoopInfo>();
65       AU.addPreserved<LoopInfo>();
66     }
67
68   private:
69     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
70     unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
71     void VersionLoop(Value *LIC, Constant *OnVal,
72                      Loop *L, Loop *&Out1, Loop *&Out2);
73     BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
74     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,Constant *Val,
75                                               bool isEqual);
76     void UnswitchTrivialCondition(Loop *L, Value *Cond, bool EntersLoopOnCond,
77                                   BasicBlock *ExitBlock);
78   };
79   RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
80 }
81
82 FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
83
84 bool LoopUnswitch::runOnFunction(Function &F) {
85   bool Changed = false;
86   LI = &getAnalysis<LoopInfo>();
87
88   // Transform all the top-level loops.  Copy the loop list so that the child
89   // can update the loop tree if it needs to delete the loop.
90   std::vector<Loop*> SubLoops(LI->begin(), LI->end());
91   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
92     Changed |= visitLoop(SubLoops[i]);
93
94   return Changed;
95 }
96
97
98 /// LoopValuesUsedOutsideLoop - Return true if there are any values defined in
99 /// the loop that are used by instructions outside of it.
100 static bool LoopValuesUsedOutsideLoop(Loop *L) {
101   // We will be doing lots of "loop contains block" queries.  Loop::contains is
102   // linear time, use a set to speed this up.
103   std::set<BasicBlock*> LoopBlocks;
104
105   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
106        BB != E; ++BB)
107     LoopBlocks.insert(*BB);
108   
109   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
110        BB != E; ++BB) {
111     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
112       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
113            ++UI) {
114         BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
115         if (!LoopBlocks.count(UserBB))
116           return true;
117       }
118   }
119   return false;
120 }
121
122 /// FindTrivialLoopExitBlock - We know that we have a branch from the loop
123 /// header to the specified latch block.   See if one of the successors of the
124 /// latch block is an exit, and if so what block it is.
125 static BasicBlock *FindTrivialLoopExitBlock(Loop *L, BasicBlock *Latch) {
126   BasicBlock *Header = L->getHeader();
127   BranchInst *LatchBranch = dyn_cast<BranchInst>(Latch->getTerminator());
128   if (!LatchBranch || !LatchBranch->isConditional()) return 0;
129   
130   // Simple case, the latch block is a conditional branch.  The target that
131   // doesn't go to the loop header is our block if it is not in the loop.
132   if (LatchBranch->getSuccessor(0) == Header) {
133     if (L->contains(LatchBranch->getSuccessor(1))) return false;
134     return LatchBranch->getSuccessor(1);
135   } else {
136     assert(LatchBranch->getSuccessor(1) == Header);
137     if (L->contains(LatchBranch->getSuccessor(0))) return false;
138     return LatchBranch->getSuccessor(0);
139   }
140 }
141
142
143 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
144 /// trivial: that is, that the condition controls whether or not the loop does
145 /// anything at all.  If this is a trivial condition, unswitching produces no
146 /// code duplications (equivalently, it produces a simpler loop and a new empty
147 /// loop, which gets deleted).
148 ///
149 /// If this is a trivial condition, return ConstantBool::True if the loop body
150 /// runs when the condition is true, False if the loop body executes when the
151 /// condition is false.  Otherwise, return null to indicate a complex condition.
152 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond,
153                                        bool *CondEntersLoop = 0,
154                                        BasicBlock **LoopExit = 0) {
155   BasicBlock *Header = L->getHeader();
156   BranchInst *HeaderTerm = dyn_cast<BranchInst>(Header->getTerminator());
157   
158   // If the header block doesn't end with a conditional branch on Cond, we can't
159   // handle it.
160   if (!HeaderTerm || !HeaderTerm->isConditional() ||
161       HeaderTerm->getCondition() != Cond)
162     return false;
163   
164   // Check to see if the conditional branch goes to the latch block.  If not,
165   // it's not trivial.  This also determines the value of Cond that will execute
166   // the loop.
167   BasicBlock *Latch = L->getLoopLatch();
168   if (HeaderTerm->getSuccessor(1) == Latch) {
169     if (CondEntersLoop) *CondEntersLoop = true;
170   } else if (HeaderTerm->getSuccessor(0) == Latch)
171     if (CondEntersLoop) *CondEntersLoop = false;
172   else
173     return false;  // Doesn't branch to latch block.
174   
175   // The latch block must end with a conditional branch where one edge goes to
176   // the header (this much we know) and one edge goes OUT of the loop.
177   BasicBlock *LoopExitBlock = FindTrivialLoopExitBlock(L, Latch);
178   if (!LoopExitBlock) return 0;
179   if (LoopExit) *LoopExit = LoopExitBlock;
180   
181   // We already know that nothing uses any scalar values defined inside of this
182   // loop.  As such, we just have to check to see if this loop will execute any
183   // side-effecting instructions (e.g. stores, calls, volatile loads) in the
184   // part of the loop that the code *would* execute.
185   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
186     if (I->mayWriteToMemory())
187       return false;
188   for (BasicBlock::iterator I = Latch->begin(), E = Latch->end(); I != E; ++I)
189     if (I->mayWriteToMemory())
190       return false;
191   return true;
192 }
193
194 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
195 /// we choose to unswitch the specified loop on the specified value.
196 ///
197 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
198   // If the condition is trivial, always unswitch.  There is no code growth for
199   // this case.
200   if (IsTrivialUnswitchCondition(L, LIC))
201     return 0;
202   
203   unsigned Cost = 0;
204   // FIXME: this is brain dead.  It should take into consideration code
205   // shrinkage.
206   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
207        I != E; ++I) {
208     BasicBlock *BB = *I;
209     // Do not include empty blocks in the cost calculation.  This happen due to
210     // loop canonicalization and will be removed.
211     if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
212       continue;
213     
214     // Count basic blocks.
215     ++Cost;
216   }
217
218   return Cost;
219 }
220
221 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
222 /// invariant in the loop, or has an invariant piece, return the invariant.
223 /// Otherwise, return null.
224 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
225   // Constants should be folded, not unswitched on!
226   if (isa<Constant>(Cond)) return false;
227   
228   // TODO: Handle: br (VARIANT|INVARIANT).
229   // TODO: Hoist simple expressions out of loops.
230   if (L->isLoopInvariant(Cond)) return Cond;
231   
232   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
233     if (BO->getOpcode() == Instruction::And ||
234         BO->getOpcode() == Instruction::Or) {
235       // If either the left or right side is invariant, we can unswitch on this,
236       // which will cause the branch to go away in one loop and the condition to
237       // simplify in the other one.
238       if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
239         return LHS;
240       if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
241         return RHS;
242     }
243   
244   return 0;
245 }
246
247 bool LoopUnswitch::visitLoop(Loop *L) {
248   bool Changed = false;
249
250   // Recurse through all subloops before we process this loop.  Copy the loop
251   // list so that the child can update the loop tree if it needs to delete the
252   // loop.
253   std::vector<Loop*> SubLoops(L->begin(), L->end());
254   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
255     Changed |= visitLoop(SubLoops[i]);
256
257   // Loop over all of the basic blocks in the loop.  If we find an interior
258   // block that is branching on a loop-invariant condition, we can unswitch this
259   // loop.
260   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
261        I != E; ++I) {
262     TerminatorInst *TI = (*I)->getTerminator();
263     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
264       // If this isn't branching on an invariant condition, we can't unswitch
265       // it.
266       if (BI->isConditional()) {
267         // See if this, or some part of it, is loop invariant.  If so, we can
268         // unswitch on it if we desire.
269         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
270         if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L))
271           return true;
272       }      
273     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
274       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
275       if (LoopCond && SI->getNumCases() > 1) {
276         // Find a value to unswitch on:
277         // FIXME: this should chose the most expensive case!
278         Constant *UnswitchVal = SI->getCaseValue(1);
279         if (UnswitchIfProfitable(LoopCond, UnswitchVal, L))
280           return true;
281       }
282     }
283     
284     // Scan the instructions to check for unswitchable values.
285     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); 
286          BBI != E; ++BBI)
287       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
288         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
289         if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L))
290           return true;
291       }
292   }
293     
294   return Changed;
295 }
296
297 /// UnswitchIfProfitable - We have found that we can unswitch L when
298 /// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
299 /// unswitch the loop, reprocess the pieces, then return true.
300 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
301   // Check to see if it would be profitable to unswitch this loop.
302   if (getLoopUnswitchCost(L, LoopCond) > Threshold) {
303     // FIXME: this should estimate growth by the amount of code shared by the
304     // resultant unswitched loops.
305     //
306     DEBUG(std::cerr << "NOT unswitching loop %"
307                     << L->getHeader()->getName() << ", cost too high: "
308                     << L->getBlocks().size() << "\n");
309     return false;
310   }
311     
312   // If this loop has live-out values, we can't unswitch it. We need something
313   // like loop-closed SSA form in order to know how to insert PHI nodes for
314   // these values.
315   if (LoopValuesUsedOutsideLoop(L)) {
316     DEBUG(std::cerr << "NOT unswitching loop %" << L->getHeader()->getName()
317                     << ", a loop value is used outside loop!\n");
318     return false;
319   }
320       
321   //std::cerr << "BEFORE:\n"; LI->dump();
322   Loop *NewLoop1 = 0, *NewLoop2 = 0;
323  
324   // If this is a trivial condition to unswitch (which results in no code
325   // duplication), do it now.
326   bool EntersLoopOnCond;
327   BasicBlock *ExitBlock;
328   if (IsTrivialUnswitchCondition(L, LoopCond, &EntersLoopOnCond, &ExitBlock)){
329     UnswitchTrivialCondition(L, LoopCond, EntersLoopOnCond, ExitBlock);
330     NewLoop1 = L;
331   } else {
332     VersionLoop(LoopCond, Val, L, NewLoop1, NewLoop2);
333   }
334   ++NumUnswitched;
335   
336   //std::cerr << "AFTER:\n"; LI->dump();
337   
338   // Try to unswitch each of our new loops now!
339   if (NewLoop1) visitLoop(NewLoop1);
340   if (NewLoop2) visitLoop(NewLoop2);
341   return true;
342 }
343
344 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
345   TerminatorInst *LatchTerm = BB->getTerminator();
346   unsigned SuccNum = 0;
347   for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
348     assert(i != e && "Didn't find edge?");
349     if (LatchTerm->getSuccessor(i) == Succ) {
350       SuccNum = i;
351       break;
352     }
353   }
354   
355   // If this is a critical edge, let SplitCriticalEdge do it.
356   if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
357     return LatchTerm->getSuccessor(SuccNum);
358
359   // If the edge isn't critical, then BB has a single successor or Succ has a
360   // single pred.  Split the block.
361   BasicBlock *BlockToSplit;
362   BasicBlock::iterator SplitPoint;
363   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
364     // If the successor only has a single pred, split the top of the successor
365     // block.
366     assert(SP == BB && "CFG broken");
367     BlockToSplit = Succ;
368     SplitPoint = Succ->begin();
369   } else {
370     // Otherwise, if BB has a single successor, split it at the bottom of the
371     // block.
372     assert(BB->getTerminator()->getNumSuccessors() == 1 &&
373            "Should have a single succ!"); 
374     BlockToSplit = BB;
375     SplitPoint = BB->getTerminator();
376   }
377
378   BasicBlock *New =
379     BlockToSplit->splitBasicBlock(SplitPoint, 
380                                   BlockToSplit->getName()+".tail");
381   // New now lives in whichever loop that BB used to.
382   if (Loop *L = LI->getLoopFor(BlockToSplit))
383     L->addBasicBlockToLoop(New, *LI);
384   return New;
385 }
386   
387
388
389 // RemapInstruction - Convert the instruction operands from referencing the
390 // current values into those specified by ValueMap.
391 //
392 static inline void RemapInstruction(Instruction *I,
393                                     std::map<const Value *, Value*> &ValueMap) {
394   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
395     Value *Op = I->getOperand(op);
396     std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
397     if (It != ValueMap.end()) Op = It->second;
398     I->setOperand(op, Op);
399   }
400 }
401
402 /// CloneLoop - Recursively clone the specified loop and all of its children,
403 /// mapping the blocks with the specified map.
404 static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
405                        LoopInfo *LI) {
406   Loop *New = new Loop();
407
408   if (PL)
409     PL->addChildLoop(New);
410   else
411     LI->addTopLevelLoop(New);
412
413   // Add all of the blocks in L to the new loop.
414   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
415        I != E; ++I)
416     if (LI->getLoopFor(*I) == L)
417       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
418
419   // Add all of the subloops to the new loop.
420   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
421     CloneLoop(*I, New, VM, LI);
422
423   return New;
424 }
425
426 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
427 /// condition in it (a cond branch from its header block to its latch block,
428 /// where the path through the loop that doesn't execute its body has no 
429 /// side-effects), unswitch it.  This doesn't involve any code duplication, just
430 /// moving the conditional branch outside of the loop and updating loop info.
431 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, 
432                                             bool EnterOnCond,
433                                             BasicBlock *ExitBlock) {
434   DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
435         << L->getHeader()->getName() << " [" << L->getBlocks().size()
436         << " blocks] in Function " << L->getHeader()->getParent()->getName()
437         << " on cond:" << *Cond << "\n");
438   
439   // First step, split the preheader, so that we know that there is a safe place
440   // to insert the conditional branch.  We will change 'OrigPH' to have a
441   // conditional branch on Cond.
442   BasicBlock *OrigPH = L->getLoopPreheader();
443   BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
444
445   // Now that we have a place to insert the conditional branch, create a place
446   // to branch to: this is the exit block out of the loop that we should
447   // short-circuit to.
448   
449   // Split this edge now, so that the loop maintains its exit block.
450   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
451   BasicBlock *NewExit = SplitEdge(L->getLoopLatch(), ExitBlock);
452   assert(NewExit != ExitBlock && "Edge not split!");
453     
454   // Okay, now we have a position to branch from and a position to branch to, 
455   // insert the new conditional branch.
456   new BranchInst(EnterOnCond ? NewPH : NewExit, EnterOnCond ? NewExit : NewPH,
457                  Cond, OrigPH->getTerminator());
458   OrigPH->getTerminator()->eraseFromParent();
459
460   // Now that we know that the loop is never entered when this condition is a
461   // particular value, rewrite the loop with this info.  We know that this will
462   // at least eliminate the old branch.
463   RewriteLoopBodyWithConditionConstant(L, Cond, ConstantBool::get(EnterOnCond),
464                                        true);
465 }
466
467
468 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
469 /// equal Val.  Split it into loop versions and test the condition outside of
470 /// either loop.  Return the loops created as Out1/Out2.
471 void LoopUnswitch::VersionLoop(Value *LIC, Constant *Val, Loop *L,
472                                Loop *&Out1, Loop *&Out2) {
473   Function *F = L->getHeader()->getParent();
474   
475   DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
476                   << L->getHeader()->getName() << " [" << L->getBlocks().size()
477                   << " blocks] in Function " << F->getName()
478                   << " when '" << *Val << "' == " << *LIC << "\n");
479
480   // LoopBlocks contains all of the basic blocks of the loop, including the
481   // preheader of the loop, the body of the loop, and the exit blocks of the 
482   // loop, in that order.
483   std::vector<BasicBlock*> LoopBlocks;
484
485   // First step, split the preheader and exit blocks, and add these blocks to
486   // the LoopBlocks list.
487   BasicBlock *OrigPreheader = L->getLoopPreheader();
488   LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
489
490   // We want the loop to come after the preheader, but before the exit blocks.
491   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
492
493   std::vector<BasicBlock*> ExitBlocks;
494   L->getExitBlocks(ExitBlocks);
495   std::sort(ExitBlocks.begin(), ExitBlocks.end());
496   ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
497                    ExitBlocks.end());
498   // Split all of the edges from inside the loop to their exit blocks.  This
499   // unswitching trivial: no phi nodes to update.
500   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
501     BasicBlock *ExitBlock = ExitBlocks[i];
502     std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
503
504     for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
505       assert(L->contains(Preds[j]) &&
506              "All preds of loop exit blocks must be the same loop!");
507       SplitEdge(Preds[j], ExitBlock);
508     }
509   }
510   
511   // The exit blocks may have been changed due to edge splitting, recompute.
512   ExitBlocks.clear();
513   L->getExitBlocks(ExitBlocks);
514   std::sort(ExitBlocks.begin(), ExitBlocks.end());
515   ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
516                    ExitBlocks.end());
517   
518   // Add exit blocks to the loop blocks.
519   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
520
521   // Next step, clone all of the basic blocks that make up the loop (including
522   // the loop preheader and exit blocks), keeping track of the mapping between
523   // the instructions and blocks.
524   std::vector<BasicBlock*> NewBlocks;
525   NewBlocks.reserve(LoopBlocks.size());
526   std::map<const Value*, Value*> ValueMap;
527   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
528     NewBlocks.push_back(CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F));
529     ValueMap[LoopBlocks[i]] = NewBlocks.back();  // Keep the BB mapping.
530   }
531
532   // Splice the newly inserted blocks into the function right before the
533   // original preheader.
534   F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
535                                 NewBlocks[0], F->end());
536
537   // Now we create the new Loop object for the versioned loop.
538   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
539   Loop *ParentLoop = L->getParentLoop();
540   if (ParentLoop) {
541     // Make sure to add the cloned preheader and exit blocks to the parent loop
542     // as well.
543     ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
544   }
545   
546   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
547     BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
548     if (ParentLoop)
549       ParentLoop->addBasicBlockToLoop(cast<BasicBlock>(NewExit), *LI);
550     
551     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
552            "Exit block should have been split to have one successor!");
553     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
554     
555     // If the successor of the exit block had PHI nodes, add an entry for
556     // NewExit.
557     PHINode *PN;
558     for (BasicBlock::iterator I = ExitSucc->begin();
559          (PN = dyn_cast<PHINode>(I)); ++I) {
560       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
561       std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
562       if (It != ValueMap.end()) V = It->second;
563       PN->addIncoming(V, NewExit);
564     }
565   }
566
567   // Rewrite the code to refer to itself.
568   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
569     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
570            E = NewBlocks[i]->end(); I != E; ++I)
571       RemapInstruction(I, ValueMap);
572   
573   // Rewrite the original preheader to select between versions of the loop.
574   assert(isa<BranchInst>(OrigPreheader->getTerminator()) &&
575          cast<BranchInst>(OrigPreheader->getTerminator())->isUnconditional() &&
576          OrigPreheader->getTerminator()->getSuccessor(0) == LoopBlocks[0] &&
577          "Preheader splitting did not work correctly!");
578
579   // Insert a conditional branch on LIC to the two preheaders.  The original
580   // code is the true version and the new code is the false version.
581   Value *BranchVal = LIC;
582   if (!isa<ConstantBool>(BranchVal)) {
583     BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp",
584                                             OrigPreheader->getTerminator());
585   } else if (Val != ConstantBool::True) {
586     // We want to enter the new loop when the condition is true.
587     BranchVal = BinaryOperator::createNot(BranchVal, "tmp",
588                                           OrigPreheader->getTerminator());
589   }
590   
591   // Remove the unconditional branch to LoopBlocks[0] and insert the new branch.
592   OrigPreheader->getInstList().pop_back();
593   new BranchInst(NewBlocks[0], LoopBlocks[0], BranchVal, OrigPreheader);
594
595   // Now we rewrite the original code to know that the condition is true and the
596   // new code to know that the condition is false.
597   RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
598   RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
599   Out1 = L;
600   Out2 = NewLoop;
601 }
602
603 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
604 // the value specified by Val in the specified loop, or we know it does NOT have
605 // that value.  Rewrite any uses of LIC or of properties correlated to it.
606 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
607                                                         Constant *Val,
608                                                         bool IsEqual) {
609   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
610   
611   // FIXME: Support correlated properties, like:
612   //  for (...)
613   //    if (li1 < li2)
614   //      ...
615   //    if (li1 > li2)
616   //      ...
617
618   // NotVal - If Val is a bool, this contains its inverse.
619   Constant *NotVal = 0;
620   if (ConstantBool *CB = dyn_cast<ConstantBool>(Val))
621     NotVal = ConstantBool::get(!CB->getValue());
622   
623   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
624   // selects, switches.
625   std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
626   
627   // Haha, this loop could be unswitched.  Get it? The unswitch pass could
628   // unswitch itself. Amazing.
629   for (unsigned i = 0, e = Users.size(); i != e; ++i)
630     if (Instruction *U = cast<Instruction>(Users[i]))
631       if (L->contains(U->getParent()))
632         if (IsEqual) {
633           U->replaceUsesOfWith(LIC, Val);
634         } else if (NotVal) {
635           U->replaceUsesOfWith(LIC, NotVal);
636         } else {
637           // If we know that LIC is not Val, use this info to simplify code.
638           if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
639             for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
640               if (SI->getCaseValue(i) == Val) {
641                 // Found a dead case value.  Don't remove PHI nodes in the 
642                 // successor if they become single-entry, those PHI nodes may
643                 // be in the Users list.
644                 SI->getSuccessor(i)->removePredecessor(SI->getParent(), true);
645                 SI->removeCase(i);
646                 break;
647               }
648             }
649           }
650
651           // TODO: We could simplify stuff like X == C.
652         }
653 }