a217e8644a834f55ac2018b55afa226f7e34e024
[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 is distributed under the University of Illinois Open Source
6 // 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/DerivedTypes.h"
33 #include "llvm/Function.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Analysis/ConstantFolding.h"
36 #include "llvm/Analysis/InlineCost.h"
37 #include "llvm/Analysis/InstructionSimplify.h"
38 #include "llvm/Analysis/LoopInfo.h"
39 #include "llvm/Analysis/LoopPass.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Transforms/Utils/Cloning.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/STLExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <algorithm>
51 #include <set>
52 using namespace llvm;
53
54 STATISTIC(NumBranches, "Number of branches unswitched");
55 STATISTIC(NumSwitches, "Number of switches unswitched");
56 STATISTIC(NumSelects , "Number of selects unswitched");
57 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
58 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
59
60 // The specific value of 50 here was chosen based only on intuition and a
61 // few specific examples.
62 static cl::opt<unsigned>
63 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
64           cl::init(50), cl::Hidden);
65   
66 namespace {
67   class LoopUnswitch : public LoopPass {
68     LoopInfo *LI;  // Loop information
69     LPPassManager *LPM;
70
71     // LoopProcessWorklist - Used to check if second loop needs processing
72     // after RewriteLoopBodyWithConditionConstant rewrites first loop.
73     std::vector<Loop*> LoopProcessWorklist;
74     SmallPtrSet<Value *,8> UnswitchedVals;
75     
76     bool OptimizeForSize;
77     bool redoLoop;
78
79     Loop *currentLoop;
80     DominatorTree *DT;
81     BasicBlock *loopHeader;
82     BasicBlock *loopPreheader;
83     
84     // LoopBlocks contains all of the basic blocks of the loop, including the
85     // preheader of the loop, the body of the loop, and the exit blocks of the 
86     // loop, in that order.
87     std::vector<BasicBlock*> LoopBlocks;
88     // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
89     std::vector<BasicBlock*> NewBlocks;
90
91   public:
92     static char ID; // Pass ID, replacement for typeid
93     explicit LoopUnswitch(bool Os = false) : 
94       LoopPass(ID), OptimizeForSize(Os), redoLoop(false), 
95       currentLoop(NULL), DT(NULL), loopHeader(NULL),
96       loopPreheader(NULL) {
97         initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
98       }
99
100     bool runOnLoop(Loop *L, LPPassManager &LPM);
101     bool processCurrentLoop();
102
103     /// This transformation requires natural loop information & requires that
104     /// loop preheaders be inserted into the CFG.
105     ///
106     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
107       AU.addRequiredID(LoopSimplifyID);
108       AU.addPreservedID(LoopSimplifyID);
109       AU.addRequired<LoopInfo>();
110       AU.addPreserved<LoopInfo>();
111       AU.addRequiredID(LCSSAID);
112       AU.addPreservedID(LCSSAID);
113       AU.addPreserved<DominatorTree>();
114     }
115
116   private:
117
118     virtual void releaseMemory() {
119       UnswitchedVals.clear();
120     }
121
122     /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
123     /// remove it.
124     void RemoveLoopFromWorklist(Loop *L) {
125       std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
126                                                  LoopProcessWorklist.end(), L);
127       if (I != LoopProcessWorklist.end())
128         LoopProcessWorklist.erase(I);
129     }
130
131     void initLoopData() {
132       loopHeader = currentLoop->getHeader();
133       loopPreheader = currentLoop->getLoopPreheader();
134     }
135
136     /// Split all of the edges from inside the loop to their exit blocks.
137     /// Update the appropriate Phi nodes as we do so.
138     void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks);
139
140     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
141     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
142                                   BasicBlock *ExitBlock);
143     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
144
145     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
146                                               Constant *Val, bool isEqual);
147
148     void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
149                                         BasicBlock *TrueDest, 
150                                         BasicBlock *FalseDest,
151                                         Instruction *InsertPt);
152
153     void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
154     void RemoveBlockIfDead(BasicBlock *BB,
155                            std::vector<Instruction*> &Worklist, Loop *l);
156     void RemoveLoopFromHierarchy(Loop *L);
157     bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
158                                     BasicBlock **LoopExit = 0);
159
160   };
161 }
162 char LoopUnswitch::ID = 0;
163 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
164                       false, false)
165 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
166 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
167 INITIALIZE_PASS_DEPENDENCY(LCSSA)
168 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
169 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
170                       false, false)
171
172 Pass *llvm::createLoopUnswitchPass(bool Os) { 
173   return new LoopUnswitch(Os); 
174 }
175
176 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
177 /// invariant in the loop, or has an invariant piece, return the invariant.
178 /// Otherwise, return null.
179 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
180   // We can never unswitch on vector conditions.
181   if (Cond->getType()->isVectorTy())
182     return 0;
183
184   // Constants should be folded, not unswitched on!
185   if (isa<Constant>(Cond)) return 0;
186
187   // TODO: Handle: br (VARIANT|INVARIANT).
188
189   // Hoist simple values out.
190   if (L->makeLoopInvariant(Cond, Changed))
191     return Cond;
192
193   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
194     if (BO->getOpcode() == Instruction::And ||
195         BO->getOpcode() == Instruction::Or) {
196       // If either the left or right side is invariant, we can unswitch on this,
197       // which will cause the branch to go away in one loop and the condition to
198       // simplify in the other one.
199       if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
200         return LHS;
201       if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
202         return RHS;
203     }
204   
205   return 0;
206 }
207
208 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
209   LI = &getAnalysis<LoopInfo>();
210   LPM = &LPM_Ref;
211   DT = getAnalysisIfAvailable<DominatorTree>();
212   currentLoop = L;
213   Function *F = currentLoop->getHeader()->getParent();
214   bool Changed = false;
215   do {
216     assert(currentLoop->isLCSSAForm(*DT));
217     redoLoop = false;
218     Changed |= processCurrentLoop();
219   } while(redoLoop);
220
221   if (Changed) {
222     // FIXME: Reconstruct dom info, because it is not preserved properly.
223     if (DT)
224       DT->runOnFunction(*F);
225   }
226   return Changed;
227 }
228
229 /// processCurrentLoop - Do actual work and unswitch loop if possible 
230 /// and profitable.
231 bool LoopUnswitch::processCurrentLoop() {
232   bool Changed = false;
233   LLVMContext &Context = currentLoop->getHeader()->getContext();
234
235   // Loop over all of the basic blocks in the loop.  If we find an interior
236   // block that is branching on a loop-invariant condition, we can unswitch this
237   // loop.
238   for (Loop::block_iterator I = currentLoop->block_begin(), 
239          E = currentLoop->block_end(); I != E; ++I) {
240     TerminatorInst *TI = (*I)->getTerminator();
241     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
242       // If this isn't branching on an invariant condition, we can't unswitch
243       // it.
244       if (BI->isConditional()) {
245         // See if this, or some part of it, is loop invariant.  If so, we can
246         // unswitch on it if we desire.
247         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), 
248                                                currentLoop, Changed);
249         if (LoopCond && UnswitchIfProfitable(LoopCond, 
250                                              ConstantInt::getTrue(Context))) {
251           ++NumBranches;
252           return true;
253         }
254       }      
255     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
256       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), 
257                                              currentLoop, Changed);
258       if (LoopCond && SI->getNumCases() > 1) {
259         // Find a value to unswitch on:
260         // FIXME: this should chose the most expensive case!
261         Constant *UnswitchVal = SI->getCaseValue(1);
262         // Do not process same value again and again.
263         if (!UnswitchedVals.insert(UnswitchVal))
264           continue;
265
266         if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
267           ++NumSwitches;
268           return true;
269         }
270       }
271     }
272     
273     // Scan the instructions to check for unswitchable values.
274     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); 
275          BBI != E; ++BBI)
276       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
277         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), 
278                                                currentLoop, Changed);
279         if (LoopCond && UnswitchIfProfitable(LoopCond, 
280                                              ConstantInt::getTrue(Context))) {
281           ++NumSelects;
282           return true;
283         }
284       }
285   }
286   return Changed;
287 }
288
289 /// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
290 /// loop with no side effects (including infinite loops).
291 ///
292 /// If true, we return true and set ExitBB to the block we
293 /// exit through.
294 ///
295 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
296                                          BasicBlock *&ExitBB,
297                                          std::set<BasicBlock*> &Visited) {
298   if (!Visited.insert(BB).second) {
299     // Already visited. Without more analysis, this could indicate an infinte loop.
300     return false;
301   } else if (!L->contains(BB)) {
302     // Otherwise, this is a loop exit, this is fine so long as this is the
303     // first exit.
304     if (ExitBB != 0) return false;
305     ExitBB = BB;
306     return true;
307   }
308   
309   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
310   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
311     // Check to see if the successor is a trivial loop exit.
312     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
313       return false;
314   }
315
316   // Okay, everything after this looks good, check to make sure that this block
317   // doesn't include any side effects.
318   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
319     if (I->mayHaveSideEffects())
320       return false;
321   
322   return true;
323 }
324
325 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
326 /// leads to an exit from the specified loop, and has no side-effects in the 
327 /// process.  If so, return the block that is exited to, otherwise return null.
328 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
329   std::set<BasicBlock*> Visited;
330   Visited.insert(L->getHeader());  // Branches to header make infinite loops.
331   BasicBlock *ExitBB = 0;
332   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
333     return ExitBB;
334   return 0;
335 }
336
337 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
338 /// trivial: that is, that the condition controls whether or not the loop does
339 /// anything at all.  If this is a trivial condition, unswitching produces no
340 /// code duplications (equivalently, it produces a simpler loop and a new empty
341 /// loop, which gets deleted).
342 ///
343 /// If this is a trivial condition, return true, otherwise return false.  When
344 /// returning true, this sets Cond and Val to the condition that controls the
345 /// trivial condition: when Cond dynamically equals Val, the loop is known to
346 /// exit.  Finally, this sets LoopExit to the BB that the loop exits to when
347 /// Cond == Val.
348 ///
349 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
350                                        BasicBlock **LoopExit) {
351   BasicBlock *Header = currentLoop->getHeader();
352   TerminatorInst *HeaderTerm = Header->getTerminator();
353   LLVMContext &Context = Header->getContext();
354   
355   BasicBlock *LoopExitBB = 0;
356   if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
357     // If the header block doesn't end with a conditional branch on Cond, we
358     // can't handle it.
359     if (!BI->isConditional() || BI->getCondition() != Cond)
360       return false;
361   
362     // Check to see if a successor of the branch is guaranteed to 
363     // exit through a unique exit block without having any 
364     // side-effects.  If so, determine the value of Cond that causes it to do
365     // this.
366     if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
367                                              BI->getSuccessor(0)))) {
368       if (Val) *Val = ConstantInt::getTrue(Context);
369     } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
370                                                     BI->getSuccessor(1)))) {
371       if (Val) *Val = ConstantInt::getFalse(Context);
372     }
373   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
374     // If this isn't a switch on Cond, we can't handle it.
375     if (SI->getCondition() != Cond) return false;
376     
377     // Check to see if a successor of the switch is guaranteed to go to the
378     // latch block or exit through a one exit block without having any 
379     // side-effects.  If so, determine the value of Cond that causes it to do
380     // this.  Note that we can't trivially unswitch on the default case.
381     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
382       if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
383                                                SI->getSuccessor(i)))) {
384         // Okay, we found a trivial case, remember the value that is trivial.
385         if (Val) *Val = SI->getCaseValue(i);
386         break;
387       }
388   }
389
390   // If we didn't find a single unique LoopExit block, or if the loop exit block
391   // contains phi nodes, this isn't trivial.
392   if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
393     return false;   // Can't handle this.
394   
395   if (LoopExit) *LoopExit = LoopExitBB;
396   
397   // We already know that nothing uses any scalar values defined inside of this
398   // loop.  As such, we just have to check to see if this loop will execute any
399   // side-effecting instructions (e.g. stores, calls, volatile loads) in the
400   // part of the loop that the code *would* execute.  We already checked the
401   // tail, check the header now.
402   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
403     if (I->mayHaveSideEffects())
404       return false;
405   return true;
406 }
407
408 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
409 /// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
410 /// unswitch the loop, reprocess the pieces, then return true.
411 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
412
413   initLoopData();
414
415   // If LoopSimplify was unable to form a preheader, don't do any unswitching.
416   if (!loopPreheader)
417     return false;
418
419   Function *F = loopHeader->getParent();
420
421   Constant *CondVal = 0;
422   BasicBlock *ExitBlock = 0;
423   if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
424     // If the condition is trivial, always unswitch. There is no code growth
425     // for this case.
426     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
427     return true;
428   }
429
430   // Check to see if it would be profitable to unswitch current loop.
431
432   // Do not do non-trivial unswitch while optimizing for size.
433   if (OptimizeForSize || F->hasFnAttr(Attribute::OptimizeForSize))
434     return false;
435
436   // FIXME: This is overly conservative because it does not take into
437   // consideration code simplification opportunities and code that can
438   // be shared by the resultant unswitched loops.
439   CodeMetrics Metrics;
440   for (Loop::block_iterator I = currentLoop->block_begin(), 
441          E = currentLoop->block_end();
442        I != E; ++I)
443     Metrics.analyzeBasicBlock(*I);
444
445   // Limit the number of instructions to avoid causing significant code
446   // expansion, and the number of basic blocks, to avoid loops with
447   // large numbers of branches which cause loop unswitching to go crazy.
448   // This is a very ad-hoc heuristic.
449   if (Metrics.NumInsts > Threshold ||
450       Metrics.NumBlocks * 5 > Threshold ||
451       Metrics.containsIndirectBr || Metrics.isRecursive) {
452     DEBUG(dbgs() << "NOT unswitching loop %"
453           << currentLoop->getHeader()->getName() << ", cost too high: "
454           << currentLoop->getBlocks().size() << "\n");
455     return false;
456   }
457
458   UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
459   return true;
460 }
461
462 // RemapInstruction - Convert the instruction operands from referencing the
463 // current values into those specified by VMap.
464 //
465 static inline void RemapInstruction(Instruction *I,
466                                     ValueToValueMapTy &VMap) {
467   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
468     Value *Op = I->getOperand(op);
469     ValueToValueMapTy::iterator It = VMap.find(Op);
470     if (It != VMap.end()) Op = It->second;
471     I->setOperand(op, Op);
472   }
473 }
474
475 /// CloneLoop - Recursively clone the specified loop and all of its children,
476 /// mapping the blocks with the specified map.
477 static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
478                        LoopInfo *LI, LPPassManager *LPM) {
479   Loop *New = new Loop();
480   LPM->insertLoop(New, PL);
481
482   // Add all of the blocks in L to the new loop.
483   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
484        I != E; ++I)
485     if (LI->getLoopFor(*I) == L)
486       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
487
488   // Add all of the subloops to the new loop.
489   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
490     CloneLoop(*I, New, VM, LI, LPM);
491
492   return New;
493 }
494
495 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
496 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest.  Insert the
497 /// code immediately before InsertPt.
498 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
499                                                   BasicBlock *TrueDest,
500                                                   BasicBlock *FalseDest,
501                                                   Instruction *InsertPt) {
502   // Insert a conditional branch on LIC to the two preheaders.  The original
503   // code is the true version and the new code is the false version.
504   Value *BranchVal = LIC;
505   if (!isa<ConstantInt>(Val) ||
506       Val->getType() != Type::getInt1Ty(LIC->getContext()))
507     BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val, "tmp");
508   else if (Val != ConstantInt::getTrue(Val->getContext()))
509     // We want to enter the new loop when the condition is true.
510     std::swap(TrueDest, FalseDest);
511
512   // Insert the new branch.
513   BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
514
515   // If either edge is critical, split it. This helps preserve LoopSimplify
516   // form for enclosing loops.
517   SplitCriticalEdge(BI, 0, this);
518   SplitCriticalEdge(BI, 1, this);
519 }
520
521 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
522 /// condition in it (a cond branch from its header block to its latch block,
523 /// where the path through the loop that doesn't execute its body has no 
524 /// side-effects), unswitch it.  This doesn't involve any code duplication, just
525 /// moving the conditional branch outside of the loop and updating loop info.
526 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, 
527                                             Constant *Val, 
528                                             BasicBlock *ExitBlock) {
529   DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
530         << loopHeader->getName() << " [" << L->getBlocks().size()
531         << " blocks] in Function " << L->getHeader()->getParent()->getName()
532         << " on cond: " << *Val << " == " << *Cond << "\n");
533   
534   // First step, split the preheader, so that we know that there is a safe place
535   // to insert the conditional branch.  We will change loopPreheader to have a
536   // conditional branch on Cond.
537   BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
538
539   // Now that we have a place to insert the conditional branch, create a place
540   // to branch to: this is the exit block out of the loop that we should
541   // short-circuit to.
542   
543   // Split this block now, so that the loop maintains its exit block, and so
544   // that the jump from the preheader can execute the contents of the exit block
545   // without actually branching to it (the exit block should be dominated by the
546   // loop header, not the preheader).
547   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
548   BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
549     
550   // Okay, now we have a position to branch from and a position to branch to, 
551   // insert the new conditional branch.
552   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, 
553                                  loopPreheader->getTerminator());
554   LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
555   loopPreheader->getTerminator()->eraseFromParent();
556
557   // We need to reprocess this loop, it could be unswitched again.
558   redoLoop = true;
559   
560   // Now that we know that the loop is never entered when this condition is a
561   // particular value, rewrite the loop with this info.  We know that this will
562   // at least eliminate the old branch.
563   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
564   ++NumTrivial;
565 }
566
567 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
568 /// blocks.  Update the appropriate Phi nodes as we do so.
569 void LoopUnswitch::SplitExitEdges(Loop *L, 
570                                 const SmallVector<BasicBlock *, 8> &ExitBlocks){
571
572   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
573     BasicBlock *ExitBlock = ExitBlocks[i];
574     SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
575                                        pred_end(ExitBlock));
576     SplitBlockPredecessors(ExitBlock, Preds.data(), Preds.size(),
577                            ".us-lcssa", this);
578   }
579 }
580
581 /// UnswitchNontrivialCondition - We determined that the loop is profitable 
582 /// to unswitch when LIC equal Val.  Split it into loop versions and test the 
583 /// condition outside of either loop.  Return the loops created as Out1/Out2.
584 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val, 
585                                                Loop *L) {
586   Function *F = loopHeader->getParent();
587   DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
588         << loopHeader->getName() << " [" << L->getBlocks().size()
589         << " blocks] in Function " << F->getName()
590         << " when '" << *Val << "' == " << *LIC << "\n");
591
592   LoopBlocks.clear();
593   NewBlocks.clear();
594
595   // First step, split the preheader and exit blocks, and add these blocks to
596   // the LoopBlocks list.
597   BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
598   LoopBlocks.push_back(NewPreheader);
599
600   // We want the loop to come after the preheader, but before the exit blocks.
601   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
602
603   SmallVector<BasicBlock*, 8> ExitBlocks;
604   L->getUniqueExitBlocks(ExitBlocks);
605
606   // Split all of the edges from inside the loop to their exit blocks.  Update
607   // the appropriate Phi nodes as we do so.
608   SplitExitEdges(L, ExitBlocks);
609
610   // The exit blocks may have been changed due to edge splitting, recompute.
611   ExitBlocks.clear();
612   L->getUniqueExitBlocks(ExitBlocks);
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   NewBlocks.reserve(LoopBlocks.size());
621   ValueToValueMapTy VMap;
622   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
623     BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
624     NewBlocks.push_back(NewBB);
625     VMap[LoopBlocks[i]] = NewBB;  // Keep the BB mapping.
626     LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
627   }
628
629   // Splice the newly inserted blocks into the function right before the
630   // original preheader.
631   F->getBasicBlockList().splice(NewPreheader, 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(), VMap, LI, LPM);
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->getBase());
641   }
642   
643   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
644     BasicBlock *NewExit = cast<BasicBlock>(VMap[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->getBase());
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(); isa<PHINode>(I); ++I) {
657       PN = cast<PHINode>(I);
658       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
659       ValueToValueMapTy::iterator It = VMap.find(V);
660       if (It != VMap.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, VMap);
670   
671   // Rewrite the original preheader to select between versions of the loop.
672   BranchInst *OldBR = cast<BranchInst>(loopPreheader->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   LPM->deleteSimpleAnalysisValue(OldBR, L);
679   OldBR->eraseFromParent();
680
681   LoopProcessWorklist.push_back(NewLoop);
682   redoLoop = true;
683
684   // Keep a WeakVH holding onto LIC.  If the first call to RewriteLoopBody
685   // deletes the instruction (for example by simplifying a PHI that feeds into
686   // the condition that we're unswitching on), we don't rewrite the second
687   // iteration.
688   WeakVH LICHandle(LIC);
689   
690   // Now we rewrite the original code to know that the condition is true and the
691   // new code to know that the condition is false.
692   RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
693
694   // It's possible that simplifying one loop could cause the other to be
695   // changed to another value or a constant.  If its a constant, don't simplify
696   // it.
697   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
698       LICHandle && !isa<Constant>(LICHandle))
699     RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
700 }
701
702 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
703 /// specified.
704 static void RemoveFromWorklist(Instruction *I, 
705                                std::vector<Instruction*> &Worklist) {
706   std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
707                                                      Worklist.end(), I);
708   while (WI != Worklist.end()) {
709     unsigned Offset = WI-Worklist.begin();
710     Worklist.erase(WI);
711     WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
712   }
713 }
714
715 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
716 /// program, replacing all uses with V and update the worklist.
717 static void ReplaceUsesOfWith(Instruction *I, Value *V, 
718                               std::vector<Instruction*> &Worklist,
719                               Loop *L, LPPassManager *LPM) {
720   DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
721
722   // Add uses to the worklist, which may be dead now.
723   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
724     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
725       Worklist.push_back(Use);
726
727   // Add users to the worklist which may be simplified now.
728   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
729        UI != E; ++UI)
730     Worklist.push_back(cast<Instruction>(*UI));
731   LPM->deleteSimpleAnalysisValue(I, L);
732   RemoveFromWorklist(I, Worklist);
733   I->replaceAllUsesWith(V);
734   I->eraseFromParent();
735   ++NumSimplify;
736 }
737
738 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
739 /// information, and remove any dead successors it has.
740 ///
741 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
742                                      std::vector<Instruction*> &Worklist,
743                                      Loop *L) {
744   if (pred_begin(BB) != pred_end(BB)) {
745     // This block isn't dead, since an edge to BB was just removed, see if there
746     // are any easy simplifications we can do now.
747     if (BasicBlock *Pred = BB->getSinglePredecessor()) {
748       // If it has one pred, fold phi nodes in BB.
749       while (isa<PHINode>(BB->begin()))
750         ReplaceUsesOfWith(BB->begin(), 
751                           cast<PHINode>(BB->begin())->getIncomingValue(0), 
752                           Worklist, L, LPM);
753       
754       // If this is the header of a loop and the only pred is the latch, we now
755       // have an unreachable loop.
756       if (Loop *L = LI->getLoopFor(BB))
757         if (loopHeader == BB && L->contains(Pred)) {
758           // Remove the branch from the latch to the header block, this makes
759           // the header dead, which will make the latch dead (because the header
760           // dominates the latch).
761           LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
762           Pred->getTerminator()->eraseFromParent();
763           new UnreachableInst(BB->getContext(), Pred);
764           
765           // The loop is now broken, remove it from LI.
766           RemoveLoopFromHierarchy(L);
767           
768           // Reprocess the header, which now IS dead.
769           RemoveBlockIfDead(BB, Worklist, L);
770           return;
771         }
772       
773       // If pred ends in a uncond branch, add uncond branch to worklist so that
774       // the two blocks will get merged.
775       if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
776         if (BI->isUnconditional())
777           Worklist.push_back(BI);
778     }
779     return;
780   }
781
782   DEBUG(dbgs() << "Nuking dead block: " << *BB);
783   
784   // Remove the instructions in the basic block from the worklist.
785   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
786     RemoveFromWorklist(I, Worklist);
787     
788     // Anything that uses the instructions in this basic block should have their
789     // uses replaced with undefs.
790     // If I is not void type then replaceAllUsesWith undef.
791     // This allows ValueHandlers and custom metadata to adjust itself.
792     if (!I->getType()->isVoidTy())
793       I->replaceAllUsesWith(UndefValue::get(I->getType()));
794   }
795   
796   // If this is the edge to the header block for a loop, remove the loop and
797   // promote all subloops.
798   if (Loop *BBLoop = LI->getLoopFor(BB)) {
799     if (BBLoop->getLoopLatch() == BB)
800       RemoveLoopFromHierarchy(BBLoop);
801   }
802
803   // Remove the block from the loop info, which removes it from any loops it
804   // was in.
805   LI->removeBlock(BB);
806   
807   
808   // Remove phi node entries in successors for this block.
809   TerminatorInst *TI = BB->getTerminator();
810   SmallVector<BasicBlock*, 4> Succs;
811   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
812     Succs.push_back(TI->getSuccessor(i));
813     TI->getSuccessor(i)->removePredecessor(BB);
814   }
815   
816   // Unique the successors, remove anything with multiple uses.
817   array_pod_sort(Succs.begin(), Succs.end());
818   Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
819   
820   // Remove the basic block, including all of the instructions contained in it.
821   LPM->deleteSimpleAnalysisValue(BB, L);  
822   BB->eraseFromParent();
823   // Remove successor blocks here that are not dead, so that we know we only
824   // have dead blocks in this list.  Nondead blocks have a way of becoming dead,
825   // then getting removed before we revisit them, which is badness.
826   //
827   for (unsigned i = 0; i != Succs.size(); ++i)
828     if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
829       // One exception is loop headers.  If this block was the preheader for a
830       // loop, then we DO want to visit the loop so the loop gets deleted.
831       // We know that if the successor is a loop header, that this loop had to
832       // be the preheader: the case where this was the latch block was handled
833       // above and headers can only have two predecessors.
834       if (!LI->isLoopHeader(Succs[i])) {
835         Succs.erase(Succs.begin()+i);
836         --i;
837       }
838     }
839   
840   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
841     RemoveBlockIfDead(Succs[i], Worklist, L);
842 }
843
844 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
845 /// become unwrapped, either because the backedge was deleted, or because the
846 /// edge into the header was removed.  If the edge into the header from the
847 /// latch block was removed, the loop is unwrapped but subloops are still alive,
848 /// so they just reparent loops.  If the loops are actually dead, they will be
849 /// removed later.
850 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
851   LPM->deleteLoopFromQueue(L);
852   RemoveLoopFromWorklist(L);
853 }
854
855 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
856 // the value specified by Val in the specified loop, or we know it does NOT have
857 // that value.  Rewrite any uses of LIC or of properties correlated to it.
858 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
859                                                         Constant *Val,
860                                                         bool IsEqual) {
861   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
862   
863   // FIXME: Support correlated properties, like:
864   //  for (...)
865   //    if (li1 < li2)
866   //      ...
867   //    if (li1 > li2)
868   //      ...
869   
870   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
871   // selects, switches.
872   std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
873   std::vector<Instruction*> Worklist;
874   LLVMContext &Context = Val->getContext();
875
876
877   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
878   // in the loop with the appropriate one directly.
879   if (IsEqual || (isa<ConstantInt>(Val) &&
880       Val->getType()->isIntegerTy(1))) {
881     Value *Replacement;
882     if (IsEqual)
883       Replacement = Val;
884     else
885       Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()), 
886                                      !cast<ConstantInt>(Val)->getZExtValue());
887     
888     for (unsigned i = 0, e = Users.size(); i != e; ++i)
889       if (Instruction *U = cast<Instruction>(Users[i])) {
890         if (!L->contains(U))
891           continue;
892         U->replaceUsesOfWith(LIC, Replacement);
893         Worklist.push_back(U);
894       }
895     SimplifyCode(Worklist, L);
896     return;
897   }
898   
899   // Otherwise, we don't know the precise value of LIC, but we do know that it
900   // is certainly NOT "Val".  As such, simplify any uses in the loop that we
901   // can.  This case occurs when we unswitch switch statements.
902   for (unsigned i = 0, e = Users.size(); i != e; ++i) {
903     Instruction *U = cast<Instruction>(Users[i]);
904     if (!L->contains(U))
905       continue;
906
907     Worklist.push_back(U);
908
909     // TODO: We could do other simplifications, for example, turning 
910     // 'icmp eq LIC, Val' -> false.
911
912     // If we know that LIC is not Val, use this info to simplify code.
913     SwitchInst *SI = dyn_cast<SwitchInst>(U);
914     if (SI == 0 || !isa<ConstantInt>(Val)) continue;
915     
916     unsigned DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
917     if (DeadCase == 0) continue;  // Default case is live for multiple values.
918     
919     // Found a dead case value.  Don't remove PHI nodes in the 
920     // successor if they become single-entry, those PHI nodes may
921     // be in the Users list.
922         
923     // FIXME: This is a hack.  We need to keep the successor around
924     // and hooked up so as to preserve the loop structure, because
925     // trying to update it is complicated.  So instead we preserve the
926     // loop structure and put the block on a dead code path.
927     BasicBlock *Switch = SI->getParent();
928     SplitEdge(Switch, SI->getSuccessor(DeadCase), this);
929     // Compute the successors instead of relying on the return value
930     // of SplitEdge, since it may have split the switch successor
931     // after PHI nodes.
932     BasicBlock *NewSISucc = SI->getSuccessor(DeadCase);
933     BasicBlock *OldSISucc = *succ_begin(NewSISucc);
934     // Create an "unreachable" destination.
935     BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
936                                            Switch->getParent(),
937                                            OldSISucc);
938     new UnreachableInst(Context, Abort);
939     // Force the new case destination to branch to the "unreachable"
940     // block while maintaining a (dead) CFG edge to the old block.
941     NewSISucc->getTerminator()->eraseFromParent();
942     BranchInst::Create(Abort, OldSISucc,
943                        ConstantInt::getTrue(Context), NewSISucc);
944     // Release the PHI operands for this edge.
945     for (BasicBlock::iterator II = NewSISucc->begin();
946          PHINode *PN = dyn_cast<PHINode>(II); ++II)
947       PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
948                            UndefValue::get(PN->getType()));
949     // Tell the domtree about the new block. We don't fully update the
950     // domtree here -- instead we force it to do a full recomputation
951     // after the pass is complete -- but we do need to inform it of
952     // new blocks.
953     if (DT)
954       DT->addNewBlock(Abort, NewSISucc);
955   }
956   
957   SimplifyCode(Worklist, L);
958 }
959
960 /// SimplifyCode - Okay, now that we have simplified some instructions in the
961 /// loop, walk over it and constant prop, dce, and fold control flow where
962 /// possible.  Note that this is effectively a very simple loop-structure-aware
963 /// optimizer.  During processing of this loop, L could very well be deleted, so
964 /// it must not be used.
965 ///
966 /// FIXME: When the loop optimizer is more mature, separate this out to a new
967 /// pass.
968 ///
969 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
970   while (!Worklist.empty()) {
971     Instruction *I = Worklist.back();
972     Worklist.pop_back();
973     
974     // Simple constant folding.
975     if (Constant *C = ConstantFoldInstruction(I)) {
976       ReplaceUsesOfWith(I, C, Worklist, L, LPM);
977       continue;
978     }
979     
980     // Simple DCE.
981     if (isInstructionTriviallyDead(I)) {
982       DEBUG(dbgs() << "Remove dead instruction '" << *I);
983       
984       // Add uses to the worklist, which may be dead now.
985       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
986         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
987           Worklist.push_back(Use);
988       LPM->deleteSimpleAnalysisValue(I, L);
989       RemoveFromWorklist(I, Worklist);
990       I->eraseFromParent();
991       ++NumSimplify;
992       continue;
993     }
994     
995     // See if instruction simplification can hack this up.  This is common for
996     // things like "select false, X, Y" after unswitching made the condition be
997     // 'false'.
998     if (Value *V = SimplifyInstruction(I)) {
999       ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1000       continue;
1001     }
1002     
1003     // Special case hacks that appear commonly in unswitched code.
1004     if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1005       if (BI->isUnconditional()) {
1006         // If BI's parent is the only pred of the successor, fold the two blocks
1007         // together.
1008         BasicBlock *Pred = BI->getParent();
1009         BasicBlock *Succ = BI->getSuccessor(0);
1010         BasicBlock *SinglePred = Succ->getSinglePredecessor();
1011         if (!SinglePred) continue;  // Nothing to do.
1012         assert(SinglePred == Pred && "CFG broken");
1013
1014         DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- " 
1015               << Succ->getName() << "\n");
1016         
1017         // Resolve any single entry PHI nodes in Succ.
1018         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1019           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1020         
1021         // Move all of the successor contents from Succ to Pred.
1022         Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1023                                    Succ->end());
1024         LPM->deleteSimpleAnalysisValue(BI, L);
1025         BI->eraseFromParent();
1026         RemoveFromWorklist(BI, Worklist);
1027         
1028         // If Succ has any successors with PHI nodes, update them to have
1029         // entries coming from Pred instead of Succ.
1030         Succ->replaceAllUsesWith(Pred);
1031         
1032         // Remove Succ from the loop tree.
1033         LI->removeBlock(Succ);
1034         LPM->deleteSimpleAnalysisValue(Succ, L);
1035         Succ->eraseFromParent();
1036         ++NumSimplify;
1037         continue;
1038       }
1039       
1040       if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1041         // Conditional branch.  Turn it into an unconditional branch, then
1042         // remove dead blocks.
1043         continue;  // FIXME: Enable.
1044
1045         DEBUG(dbgs() << "Folded branch: " << *BI);
1046         BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1047         BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1048         DeadSucc->removePredecessor(BI->getParent(), true);
1049         Worklist.push_back(BranchInst::Create(LiveSucc, BI));
1050         LPM->deleteSimpleAnalysisValue(BI, L);
1051         BI->eraseFromParent();
1052         RemoveFromWorklist(BI, Worklist);
1053         ++NumSimplify;
1054
1055         RemoveBlockIfDead(DeadSucc, Worklist, L);
1056       }
1057       continue;
1058     }
1059   }
1060 }