Remove extra FIXME
[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/LoopInfo.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Analysis/Dominators.h"
39 #include "llvm/Transforms/Utils/Cloning.h"
40 #include "llvm/Transforms/Utils/Local.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include <algorithm>
48 #include <set>
49 using namespace llvm;
50
51 STATISTIC(NumBranches, "Number of branches unswitched");
52 STATISTIC(NumSwitches, "Number of switches unswitched");
53 STATISTIC(NumSelects , "Number of selects unswitched");
54 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
55 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
56
57 static cl::opt<unsigned>
58 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
59           cl::init(10), cl::Hidden);
60   
61 namespace {
62   class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
63     LoopInfo *LI;  // Loop information
64     LPPassManager *LPM;
65
66     // LoopProcessWorklist - Used to check if second loop needs processing
67     // after RewriteLoopBodyWithConditionConstant rewrites first loop.
68     std::vector<Loop*> LoopProcessWorklist;
69     SmallPtrSet<Value *,8> UnswitchedVals;
70     
71     bool OptimizeForSize;
72     bool redoLoop;
73
74     Loop *currentLoop;
75     DominanceFrontier *DF;
76     DominatorTree *DT;
77     BasicBlock *loopHeader;
78     BasicBlock *loopPreheader;
79     
80     /// LoopDF - Loop's dominance frontier. This set is a collection of 
81     /// loop exiting blocks' DF member blocks. However this does set does not
82     /// includes basic blocks that are inside loop.
83     SmallPtrSet<BasicBlock *, 8> LoopDF;
84
85     /// OrigLoopExitMap - This is used to map loop exiting block with 
86     /// corresponding loop exit block, before updating CFG.
87     DenseMap<BasicBlock *, BasicBlock *> OrigLoopExitMap;
88
89     // LoopBlocks contains all of the basic blocks of the loop, including the
90     // preheader of the loop, the body of the loop, and the exit blocks of the 
91     // loop, in that order.
92     std::vector<BasicBlock*> LoopBlocks;
93     // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
94     std::vector<BasicBlock*> NewBlocks;
95   public:
96     static char ID; // Pass ID, replacement for typeid
97     explicit LoopUnswitch(bool Os = false) : 
98       LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false), 
99       currentLoop(NULL), DF(NULL), DT(NULL), loopHeader(NULL),
100       loopPreheader(NULL) {}
101
102     bool runOnLoop(Loop *L, LPPassManager &LPM);
103     bool processCurrentLoop();
104
105     /// This transformation requires natural loop information & requires that
106     /// loop preheaders be inserted into the CFG...
107     ///
108     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109       AU.addRequiredID(LoopSimplifyID);
110       AU.addPreservedID(LoopSimplifyID);
111       AU.addRequired<LoopInfo>();
112       AU.addPreserved<LoopInfo>();
113       AU.addRequiredID(LCSSAID);
114       AU.addPreservedID(LCSSAID);
115       AU.addPreserved<DominatorTree>();
116       AU.addPreserved<DominanceFrontier>();
117     }
118
119   private:
120
121     /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
122     /// remove it.
123     void RemoveLoopFromWorklist(Loop *L) {
124       std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
125                                                  LoopProcessWorklist.end(), L);
126       if (I != LoopProcessWorklist.end())
127         LoopProcessWorklist.erase(I);
128     }
129
130     void initLoopData() {
131       loopHeader = currentLoop->getHeader();
132       loopPreheader = currentLoop->getLoopPreheader();
133     }
134
135     /// Split all of the edges from inside the loop to their exit blocks.
136     /// Update the appropriate Phi nodes as we do so.
137     void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks,
138                         SmallVector<BasicBlock *, 8> &MiddleBlocks);
139
140     /// If BB's dominance frontier  has a member that is not part of loop L then
141     /// remove it. Add NewDFMember in BB's dominance frontier.
142     void ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
143                                      BasicBlock *NewDFMember);
144       
145     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
146     unsigned getLoopUnswitchCost(Value *LIC);
147     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
148                                   BasicBlock *ExitBlock);
149     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
150
151     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
152                                               Constant *Val, bool isEqual);
153
154     void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
155                                         BasicBlock *TrueDest, 
156                                         BasicBlock *FalseDest,
157                                         Instruction *InsertPt);
158
159     void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
160     void RemoveBlockIfDead(BasicBlock *BB,
161                            std::vector<Instruction*> &Worklist, Loop *l);
162     void RemoveLoopFromHierarchy(Loop *L);
163     bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
164                                     BasicBlock **LoopExit = 0);
165
166   };
167 }
168 char LoopUnswitch::ID = 0;
169 static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
170
171 LoopPass *llvm::createLoopUnswitchPass(bool Os) { 
172   return new LoopUnswitch(Os); 
173 }
174
175 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
176 /// invariant in the loop, or has an invariant piece, return the invariant.
177 /// Otherwise, return null.
178 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
179   // Constants should be folded, not unswitched on!
180   if (isa<Constant>(Cond)) return false;
181
182   // TODO: Handle: br (VARIANT|INVARIANT).
183   // TODO: Hoist simple expressions out of loops.
184   if (L->isLoopInvariant(Cond)) return Cond;
185   
186   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
187     if (BO->getOpcode() == Instruction::And ||
188         BO->getOpcode() == Instruction::Or) {
189       // If either the left or right side is invariant, we can unswitch on this,
190       // which will cause the branch to go away in one loop and the condition to
191       // simplify in the other one.
192       if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
193         return LHS;
194       if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
195         return RHS;
196     }
197   
198   return 0;
199 }
200
201 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
202   LI = &getAnalysis<LoopInfo>();
203   LPM = &LPM_Ref;
204   DF = getAnalysisToUpdate<DominanceFrontier>();
205   DT = getAnalysisToUpdate<DominatorTree>();
206   currentLoop = L;
207   bool Changed = false;
208   do {
209     assert(currentLoop->isLCSSAForm());
210     redoLoop = false;
211     Changed |= processCurrentLoop();
212   } while(redoLoop);
213
214   return Changed;
215 }
216
217 /// processCurrentLoop - Do actual work and unswitch loop if possible 
218 /// and profitable.
219 bool LoopUnswitch::processCurrentLoop() {
220   bool Changed = false;
221
222   // Loop over all of the basic blocks in the loop.  If we find an interior
223   // block that is branching on a loop-invariant condition, we can unswitch this
224   // loop.
225   for (Loop::block_iterator I = currentLoop->block_begin(), 
226          E = currentLoop->block_end();
227        I != E; ++I) {
228     TerminatorInst *TI = (*I)->getTerminator();
229     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
230       // If this isn't branching on an invariant condition, we can't unswitch
231       // it.
232       if (BI->isConditional()) {
233         // See if this, or some part of it, is loop invariant.  If so, we can
234         // unswitch on it if we desire.
235         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), 
236                                                currentLoop, Changed);
237         if (LoopCond && UnswitchIfProfitable(LoopCond, 
238                                              ConstantInt::getTrue())) {
239           ++NumBranches;
240           return true;
241         }
242       }      
243     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
244       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), 
245                                              currentLoop, Changed);
246       if (LoopCond && SI->getNumCases() > 1) {
247         // Find a value to unswitch on:
248         // FIXME: this should chose the most expensive case!
249         Constant *UnswitchVal = SI->getCaseValue(1);
250         // Do not process same value again and again.
251         if (!UnswitchedVals.insert(UnswitchVal))
252           continue;
253
254         if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
255           ++NumSwitches;
256           return true;
257         }
258       }
259     }
260     
261     // Scan the instructions to check for unswitchable values.
262     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); 
263          BBI != E; ++BBI)
264       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
265         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), 
266                                                currentLoop, Changed);
267         if (LoopCond && UnswitchIfProfitable(LoopCond, 
268                                              ConstantInt::getTrue())) {
269           ++NumSelects;
270           return true;
271         }
272       }
273   }
274   return Changed;
275 }
276
277 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
278 ///   1. Exit the loop with no side effects.
279 ///   2. Branch to the latch block with no side-effects.
280 ///
281 /// If these conditions are true, we return true and set ExitBB to the block we
282 /// exit through.
283 ///
284 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
285                                          BasicBlock *&ExitBB,
286                                          std::set<BasicBlock*> &Visited) {
287   if (!Visited.insert(BB).second) {
288     // Already visited and Ok, end of recursion.
289     return true;
290   } else if (!L->contains(BB)) {
291     // Otherwise, this is a loop exit, this is fine so long as this is the
292     // first exit.
293     if (ExitBB != 0) return false;
294     ExitBB = BB;
295     return true;
296   }
297   
298   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
299   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
300     // Check to see if the successor is a trivial loop exit.
301     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
302       return false;
303   }
304
305   // Okay, everything after this looks good, check to make sure that this block
306   // doesn't include any side effects.
307   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
308     if (I->mayWriteToMemory())
309       return false;
310   
311   return true;
312 }
313
314 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
315 /// leads to an exit from the specified loop, and has no side-effects in the 
316 /// process.  If so, return the block that is exited to, otherwise return null.
317 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
318   std::set<BasicBlock*> Visited;
319   Visited.insert(L->getHeader());  // Branches to header are ok.
320   BasicBlock *ExitBB = 0;
321   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
322     return ExitBB;
323   return 0;
324 }
325
326 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
327 /// trivial: that is, that the condition controls whether or not the loop does
328 /// anything at all.  If this is a trivial condition, unswitching produces no
329 /// code duplications (equivalently, it produces a simpler loop and a new empty
330 /// loop, which gets deleted).
331 ///
332 /// If this is a trivial condition, return true, otherwise return false.  When
333 /// returning true, this sets Cond and Val to the condition that controls the
334 /// trivial condition: when Cond dynamically equals Val, the loop is known to
335 /// exit.  Finally, this sets LoopExit to the BB that the loop exits to when
336 /// Cond == Val.
337 ///
338 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
339                                        BasicBlock **LoopExit) {
340   BasicBlock *Header = currentLoop->getHeader();
341   TerminatorInst *HeaderTerm = Header->getTerminator();
342   
343   BasicBlock *LoopExitBB = 0;
344   if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
345     // If the header block doesn't end with a conditional branch on Cond, we
346     // can't handle it.
347     if (!BI->isConditional() || BI->getCondition() != Cond)
348       return false;
349   
350     // Check to see if a successor of the branch is guaranteed to go to the
351     // latch block or exit through a one exit block without having any 
352     // side-effects.  If so, determine the value of Cond that causes it to do
353     // this.
354     if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
355                                              BI->getSuccessor(0)))) {
356       if (Val) *Val = ConstantInt::getTrue();
357     } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
358                                                     BI->getSuccessor(1)))) {
359       if (Val) *Val = ConstantInt::getFalse();
360     }
361   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
362     // If this isn't a switch on Cond, we can't handle it.
363     if (SI->getCondition() != Cond) return false;
364     
365     // Check to see if a successor of the switch is guaranteed to go to the
366     // latch block or exit through a one exit block without having any 
367     // side-effects.  If so, determine the value of Cond that causes it to do
368     // this.  Note that we can't trivially unswitch on the default case.
369     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
370       if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
371                                                SI->getSuccessor(i)))) {
372         // Okay, we found a trivial case, remember the value that is trivial.
373         if (Val) *Val = SI->getCaseValue(i);
374         break;
375       }
376   }
377
378   // If we didn't find a single unique LoopExit block, or if the loop exit block
379   // contains phi nodes, this isn't trivial.
380   if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
381     return false;   // Can't handle this.
382   
383   if (LoopExit) *LoopExit = LoopExitBB;
384   
385   // We already know that nothing uses any scalar values defined inside of this
386   // loop.  As such, we just have to check to see if this loop will execute any
387   // side-effecting instructions (e.g. stores, calls, volatile loads) in the
388   // part of the loop that the code *would* execute.  We already checked the
389   // tail, check the header now.
390   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
391     if (I->mayWriteToMemory())
392       return false;
393   return true;
394 }
395
396 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
397 /// we choose to unswitch current loop on the specified value.
398 ///
399 unsigned LoopUnswitch::getLoopUnswitchCost(Value *LIC) {
400   // If the condition is trivial, always unswitch.  There is no code growth for
401   // this case.
402   if (IsTrivialUnswitchCondition(LIC))
403     return 0;
404   
405   // FIXME: This is really overly conservative.  However, more liberal 
406   // estimations have thus far resulted in excessive unswitching, which is bad
407   // both in compile time and in code size.  This should be replaced once
408   // someone figures out how a good estimation.
409   return currentLoop->getBlocks().size();
410   
411   unsigned Cost = 0;
412   // FIXME: this is brain dead.  It should take into consideration code
413   // shrinkage.
414   for (Loop::block_iterator I = currentLoop->block_begin(), 
415          E = currentLoop->block_end();
416        I != E; ++I) {
417     BasicBlock *BB = *I;
418     // Do not include empty blocks in the cost calculation.  This happen due to
419     // loop canonicalization and will be removed.
420     if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
421       continue;
422     
423     // Count basic blocks.
424     ++Cost;
425   }
426
427   return Cost;
428 }
429
430 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
431 /// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
432 /// unswitch the loop, reprocess the pieces, then return true.
433 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
434   // Check to see if it would be profitable to unswitch current loop.
435   unsigned Cost = getLoopUnswitchCost(LoopCond);
436
437   // Do not do non-trivial unswitch while optimizing for size.
438   if (Cost && OptimizeForSize)
439     return false;
440
441   if (Cost > Threshold) {
442     // FIXME: this should estimate growth by the amount of code shared by the
443     // resultant unswitched loops.
444     //
445     DOUT << "NOT unswitching loop %"
446          << currentLoop->getHeader()->getName() << ", cost too high: "
447          << currentLoop->getBlocks().size() << "\n";
448     return false;
449   }
450
451   initLoopData();
452
453   Constant *CondVal;
454   BasicBlock *ExitBlock;
455   if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
456     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
457   } else {
458     UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
459   }
460
461   // FIXME: Reconstruct dom info, because it is not preserved properly.
462   Function *F = loopHeader->getParent();
463   if (DT)
464     DT->runOnFunction(*F);
465   if (DF)
466     DF->runOnFunction(*F);
467   return true;
468 }
469
470 // RemapInstruction - Convert the instruction operands from referencing the
471 // current values into those specified by ValueMap.
472 //
473 static inline void RemapInstruction(Instruction *I,
474                                     DenseMap<const Value *, Value*> &ValueMap) {
475   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
476     Value *Op = I->getOperand(op);
477     DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
478     if (It != ValueMap.end()) Op = It->second;
479     I->setOperand(op, Op);
480   }
481 }
482
483 // CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator
484 // Info.
485 //
486 // If Orig block's immediate dominator is mapped in VM then use corresponding
487 // immediate dominator from the map. Otherwise Orig block's dominator is also
488 // NewBB's dominator.
489 //
490 // OrigPreheader is loop pre-header before this pass started
491 // updating CFG. NewPrehader is loops new pre-header. However, after CFG
492 // manipulation, loop L may not exist. So rely on input parameter NewPreheader.
493 static void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
494                          BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
495                          BasicBlock *OrigHeader,
496                          DominatorTree *DT, DominanceFrontier *DF,
497                          DenseMap<const Value*, Value*> &VM) {
498
499   // If NewBB alreay has found its place in domiantor tree then no need to do
500   // anything.
501   if (DT->getNode(NewBB))
502     return;
503
504   // If Orig does not have any immediate domiantor then its clone, NewBB, does 
505   // not need any immediate dominator.
506   DomTreeNode *OrigNode = DT->getNode(Orig);
507   if (!OrigNode)
508     return;
509   DomTreeNode *OrigIDomNode = OrigNode->getIDom();
510   if (!OrigIDomNode)
511     return;
512
513   BasicBlock *OrigIDom = NULL; 
514
515   // If Orig is original loop header then its immediate dominator is
516   // NewPreheader.
517   if (Orig == OrigHeader)
518     OrigIDom = NewPreheader;
519
520   // If Orig is new pre-header then its immediate dominator is
521   // original pre-header.
522   else if (Orig == NewPreheader)
523     OrigIDom = OrigPreheader;
524
525   // Otherwise ask DT to find Orig's immediate dominator.
526   else
527      OrigIDom = OrigIDomNode->getBlock();
528
529   // Initially use Orig's immediate dominator as NewBB's immediate dominator.
530   BasicBlock *NewIDom = OrigIDom;
531   DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
532   if (I != VM.end()) {
533     NewIDom = cast<BasicBlock>(I->second);
534     
535     // If NewIDom does not have corresponding dominatore tree node then
536     // get one.
537     if (!DT->getNode(NewIDom))
538       CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader, 
539                    OrigHeader, DT, DF, VM);
540   }
541   
542   DT->addNewBlock(NewBB, NewIDom);
543   
544   // Copy cloned dominance frontiner set
545   DominanceFrontier::DomSetType NewDFSet;
546   if (DF) {
547     DominanceFrontier::iterator DFI = DF->find(Orig);
548     if ( DFI != DF->end()) {
549       DominanceFrontier::DomSetType S = DFI->second;
550       for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
551            I != E; ++I) {
552         BasicBlock *BB = *I;
553         DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
554         if (IDM != VM.end())
555           NewDFSet.insert(cast<BasicBlock>(IDM->second));
556         else
557           NewDFSet.insert(BB);
558       }
559     }
560     DF->addBasicBlock(NewBB, NewDFSet);
561   }
562 }
563
564 /// CloneLoop - Recursively clone the specified loop and all of its children,
565 /// mapping the blocks with the specified map.
566 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
567                        LoopInfo *LI, LPPassManager *LPM) {
568   Loop *New = new Loop();
569
570   LPM->insertLoop(New, PL);
571
572   // Add all of the blocks in L to the new loop.
573   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
574        I != E; ++I)
575     if (LI->getLoopFor(*I) == L)
576       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
577
578   // Add all of the subloops to the new loop.
579   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
580     CloneLoop(*I, New, VM, LI, LPM);
581
582   return New;
583 }
584
585 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
586 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest.  Insert the
587 /// code immediately before InsertPt.
588 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
589                                                   BasicBlock *TrueDest,
590                                                   BasicBlock *FalseDest,
591                                                   Instruction *InsertPt) {
592   // Insert a conditional branch on LIC to the two preheaders.  The original
593   // code is the true version and the new code is the false version.
594   Value *BranchVal = LIC;
595   if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
596     BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
597   else if (Val != ConstantInt::getTrue())
598     // We want to enter the new loop when the condition is true.
599     std::swap(TrueDest, FalseDest);
600
601   // Insert the new branch.
602   BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
603 }
604
605
606 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
607 /// condition in it (a cond branch from its header block to its latch block,
608 /// where the path through the loop that doesn't execute its body has no 
609 /// side-effects), unswitch it.  This doesn't involve any code duplication, just
610 /// moving the conditional branch outside of the loop and updating loop info.
611 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, 
612                                             Constant *Val, 
613                                             BasicBlock *ExitBlock) {
614   DOUT << "loop-unswitch: Trivial-Unswitch loop %"
615        << loopHeader->getName() << " [" << L->getBlocks().size()
616        << " blocks] in Function " << L->getHeader()->getParent()->getName()
617        << " on cond: " << *Val << " == " << *Cond << "\n";
618   
619   // First step, split the preheader, so that we know that there is a safe place
620   // to insert the conditional branch.  We will change loopPreheader to have a
621   // conditional branch on Cond.
622   BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
623
624   // Now that we have a place to insert the conditional branch, create a place
625   // to branch to: this is the exit block out of the loop that we should
626   // short-circuit to.
627   
628   // Split this block now, so that the loop maintains its exit block, and so
629   // that the jump from the preheader can execute the contents of the exit block
630   // without actually branching to it (the exit block should be dominated by the
631   // loop header, not the preheader).
632   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
633   BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
634     
635   // Okay, now we have a position to branch from and a position to branch to, 
636   // insert the new conditional branch.
637   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, 
638                                  loopPreheader->getTerminator());
639   if (DT) {
640     DT->changeImmediateDominator(NewExit, loopPreheader);
641     DT->changeImmediateDominator(NewPH, loopPreheader);
642   }
643    
644   if (DF) {
645     // NewExit is now part of NewPH and Loop Header's dominance
646     // frontier.
647     DominanceFrontier::iterator  DFI = DF->find(NewPH);
648     if (DFI != DF->end())
649       DF->addToFrontier(DFI, NewExit);
650     DFI = DF->find(loopHeader);
651     DF->addToFrontier(DFI, NewExit);
652
653     // ExitBlock does not have successors then NewExit is part of
654     // its dominance frontier.
655     if (succ_begin(ExitBlock) == succ_end(ExitBlock)) {
656       DFI = DF->find(ExitBlock);
657       DF->addToFrontier(DFI, NewExit);
658     }
659   }
660   LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
661   loopPreheader->getTerminator()->eraseFromParent();
662
663   // We need to reprocess this loop, it could be unswitched again.
664   redoLoop = true;
665   
666   // Now that we know that the loop is never entered when this condition is a
667   // particular value, rewrite the loop with this info.  We know that this will
668   // at least eliminate the old branch.
669   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
670   ++NumTrivial;
671 }
672
673 /// ReplaceLoopExternalDFMember -
674 /// If BB's dominance frontier  has a member that is not part of loop L then 
675 /// remove it. Add NewDFMember in BB's dominance frontier.
676 void LoopUnswitch::ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
677                                                BasicBlock *NewDFMember) {
678   
679   DominanceFrontier::iterator DFI = DF->find(BB);
680   if (DFI == DF->end())
681     return;
682   
683   DominanceFrontier::DomSetType &DFSet = DFI->second;
684   for (DominanceFrontier::DomSetType::iterator DI = DFSet.begin(),
685          DE = DFSet.end(); DI != DE;) {
686     BasicBlock *B = *DI++;
687     if (L->contains(B))
688       continue;
689
690     DF->removeFromFrontier(DFI, B);
691     LoopDF.insert(B);
692   }
693
694   DF->addToFrontier(DFI, NewDFMember);
695 }
696
697 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
698 /// blocks.  Update the appropriate Phi nodes as we do so.
699 void LoopUnswitch::SplitExitEdges(Loop *L, 
700                                  const SmallVector<BasicBlock *, 8> &ExitBlocks,
701                                   SmallVector<BasicBlock *, 8> &MiddleBlocks) {
702
703   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
704     BasicBlock *ExitBlock = ExitBlocks[i];
705     std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
706
707     for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
708       BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
709       MiddleBlocks.push_back(MiddleBlock);
710       BasicBlock* StartBlock = Preds[j];
711       BasicBlock* EndBlock;
712       if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
713         EndBlock = MiddleBlock;
714         MiddleBlock = EndBlock->getSinglePredecessor();;
715       } else {
716         EndBlock = ExitBlock;
717       }
718       
719       OrigLoopExitMap[StartBlock] = EndBlock;
720
721       std::set<PHINode*> InsertedPHIs;
722       PHINode* OldLCSSA = 0;
723       for (BasicBlock::iterator I = EndBlock->begin();
724            (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
725         Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
726         PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
727                                             OldLCSSA->getName() + ".us-lcssa",
728                                             MiddleBlock->getTerminator());
729         NewLCSSA->addIncoming(OldValue, StartBlock);
730         OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
731                                    NewLCSSA);
732         InsertedPHIs.insert(NewLCSSA);
733       }
734
735       BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
736       for (BasicBlock::iterator I = MiddleBlock->begin();
737          (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
738          ++I) {
739         PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
740                                             OldLCSSA->getName() + ".us-lcssa",
741                                             InsertPt);
742         OldLCSSA->replaceAllUsesWith(NewLCSSA);
743         NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
744       }
745
746       if (DF && DT) {
747         // StartBlock -- > MiddleBlock -- > EndBlock
748         // StartBlock is loop exiting block. EndBlock will become merge point 
749         // of two loop exits after loop unswitch.
750         
751         // If StartBlock's DF member includes a block that is not loop member 
752         // then replace that DF member with EndBlock.
753
754         // If MiddleBlock's DF member includes a block that is not loop member
755         // tnen replace that DF member with EndBlock.
756
757         ReplaceLoopExternalDFMember(L, StartBlock, EndBlock);
758         ReplaceLoopExternalDFMember(L, MiddleBlock, EndBlock);
759       }
760     }    
761   }
762
763 }
764
765 /// addBBToDomFrontier - Helper function. Insert DFBB in Basic Block BB's
766 /// dominance frontier using iterator DFI.
767 static void addBBToDomFrontier(DominanceFrontier &DF,
768                                DominanceFrontier::iterator &DFI,
769                                BasicBlock *BB, BasicBlock *DFBB) {
770   if (DFI != DF.end()) {
771     DF.addToFrontier(DFI, DFBB);
772     return;
773   }
774
775   DominanceFrontier::DomSetType NSet;
776   NSet.insert(DFBB);
777   DF.addBasicBlock(BB, NSet);
778   DFI = DF.find(BB);
779 }
780
781 /// UnswitchNontrivialCondition - We determined that the loop is profitable 
782 /// to unswitch when LIC equal Val.  Split it into loop versions and test the 
783 /// condition outside of either loop.  Return the loops created as Out1/Out2.
784 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val, 
785                                                Loop *L) {
786   Function *F = loopHeader->getParent();
787   DOUT << "loop-unswitch: Unswitching loop %"
788        << loopHeader->getName() << " [" << L->getBlocks().size()
789        << " blocks] in Function " << F->getName()
790        << " when '" << *Val << "' == " << *LIC << "\n";
791
792   LoopBlocks.clear();
793   NewBlocks.clear();
794
795   // First step, split the preheader and exit blocks, and add these blocks to
796   // the LoopBlocks list.
797   BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
798   LoopBlocks.push_back(NewPreheader);
799
800   // We want the loop to come after the preheader, but before the exit blocks.
801   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
802
803   SmallVector<BasicBlock*, 8> ExitBlocks;
804   L->getUniqueExitBlocks(ExitBlocks);
805
806   // Split all of the edges from inside the loop to their exit blocks.  Update
807   // the appropriate Phi nodes as we do so.
808   SmallVector<BasicBlock *,8> MiddleBlocks;
809   SplitExitEdges(L, ExitBlocks, MiddleBlocks);
810
811   // The exit blocks may have been changed due to edge splitting, recompute.
812   ExitBlocks.clear();
813   L->getUniqueExitBlocks(ExitBlocks);
814
815   // Add exit blocks to the loop blocks.
816   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
817
818   // Next step, clone all of the basic blocks that make up the loop (including
819   // the loop preheader and exit blocks), keeping track of the mapping between
820   // the instructions and blocks.
821   NewBlocks.reserve(LoopBlocks.size());
822   DenseMap<const Value*, Value*> ValueMap;
823   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
824     BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
825     NewBlocks.push_back(New);
826     ValueMap[LoopBlocks[i]] = New;  // Keep the BB mapping.
827     LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
828   }
829
830   // OutSiders are basic block that are dominated by original header and
831   // at the same time they are not part of loop.
832   SmallPtrSet<BasicBlock *, 8> OutSiders;
833   if (DT) {
834     DomTreeNode *OrigHeaderNode = DT->getNode(loopHeader);
835     for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(), 
836           DE = OrigHeaderNode->end();  DI != DE; ++DI) {
837       BasicBlock *B = (*DI)->getBlock();
838
839       DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
840       if (VI == ValueMap.end()) 
841         OutSiders.insert(B);
842     }
843   }
844
845   // Splice the newly inserted blocks into the function right before the
846   // original preheader.
847   F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
848                                 NewBlocks[0], F->end());
849
850   // Now we create the new Loop object for the versioned loop.
851   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
852   Loop *ParentLoop = L->getParentLoop();
853   if (ParentLoop) {
854     // Make sure to add the cloned preheader and exit blocks to the parent loop
855     // as well.
856     ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
857   }
858   
859   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
860     BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
861     // The new exit block should be in the same loop as the old one.
862     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
863       ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
864     
865     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
866            "Exit block should have been split to have one successor!");
867     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
868     
869     // If the successor of the exit block had PHI nodes, add an entry for
870     // NewExit.
871     PHINode *PN;
872     for (BasicBlock::iterator I = ExitSucc->begin();
873          (PN = dyn_cast<PHINode>(I)); ++I) {
874       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
875       DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
876       if (It != ValueMap.end()) V = It->second;
877       PN->addIncoming(V, NewExit);
878     }
879   }
880
881   // Rewrite the code to refer to itself.
882   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
883     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
884            E = NewBlocks[i]->end(); I != E; ++I)
885       RemapInstruction(I, ValueMap);
886   
887   // Rewrite the original preheader to select between versions of the loop.
888   BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
889   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
890          "Preheader splitting did not work correctly!");
891
892   // Emit the new branch that selects between the two versions of this loop.
893   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
894   LPM->deleteSimpleAnalysisValue(OldBR, L);
895   OldBR->eraseFromParent();
896
897   // Update dominator info
898   if (DF && DT) {
899
900     SmallVector<BasicBlock *,4> ExitingBlocks;
901     L->getExitingBlocks(ExitingBlocks);
902
903     // Clone dominator info for all cloned basic block.
904     for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
905       BasicBlock *LBB = LoopBlocks[i];
906       BasicBlock *NBB = NewBlocks[i];
907       CloneDomInfo(NBB, LBB, NewPreheader, loopPreheader, 
908                    loopHeader, DT, DF, ValueMap);
909
910       //   If LBB's dominance frontier includes DFMember 
911       //      such that DFMember is also a member of LoopDF then
912       //         - Remove DFMember from LBB's dominance frontier
913       //         - Copy loop exiting blocks', that are dominated by BB,
914       //           dominance frontier member in BB's dominance frontier
915
916       DominanceFrontier::iterator LBBI = DF->find(LBB);
917       DominanceFrontier::iterator NBBI = DF->find(NBB);
918       if (LBBI == DF->end())
919         continue;
920
921       DominanceFrontier::DomSetType &LBSet = LBBI->second;
922       for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
923              LE = LBSet.end(); LI != LE; /* NULL */) {
924         BasicBlock *B = *LI++;
925         if (B == LBB && B == loopHeader)
926           continue;
927         bool removeB = false;
928         if (!LoopDF.count(B))
929           continue;
930         
931         // If LBB dominates loop exits then insert loop exit block's DF
932         // into B's DF.
933         for(SmallVector<BasicBlock *, 4>::iterator 
934               LExitI = ExitingBlocks.begin(),
935               LExitE = ExitingBlocks.end(); LExitI != LExitE; ++LExitI) {
936           BasicBlock *E = *LExitI;
937           
938           if (!DT->dominates(LBB,E))
939             continue;
940           
941           DenseMap<BasicBlock *, BasicBlock *>::iterator DFBI = 
942             OrigLoopExitMap.find(E);
943           if (DFBI == OrigLoopExitMap.end()) 
944             continue;
945           
946           BasicBlock *DFB = DFBI->second;
947           DF->addToFrontier(LBBI, DFB);
948           DF->addToFrontier(NBBI, DFB);
949           removeB = true;
950         }
951         
952         // If B's replacement is inserted in DF then now is the time to remove
953         // B.
954         if (removeB) {
955           DF->removeFromFrontier(LBBI, B);
956           if (L->contains(B))
957             DF->removeFromFrontier(NBBI, cast<BasicBlock>(ValueMap[B]));
958           else
959             DF->removeFromFrontier(NBBI, B);
960         }
961       }
962
963     }
964
965     // MiddleBlocks are dominated by original pre header. SplitEdge updated
966     // MiddleBlocks' dominance frontier appropriately.
967     for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
968       BasicBlock *MBB = MiddleBlocks[i];
969       if (!MBB->getSinglePredecessor())
970         DT->changeImmediateDominator(MBB, loopPreheader);
971     }
972
973     // All Outsiders are now dominated by original pre header.
974     for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
975            OE = OutSiders.end(); OI != OE; ++OI) {
976       BasicBlock *OB = *OI;
977       DT->changeImmediateDominator(OB, loopPreheader);
978     }
979
980     // New loop headers are dominated by original preheader
981     DT->changeImmediateDominator(NewBlocks[0], loopPreheader);
982     DT->changeImmediateDominator(LoopBlocks[0], loopPreheader);
983   }
984
985   LoopProcessWorklist.push_back(NewLoop);
986   redoLoop = true;
987
988   // Now we rewrite the original code to know that the condition is true and the
989   // new code to know that the condition is false.
990   RewriteLoopBodyWithConditionConstant(L      , LIC, Val, false);
991   
992   // It's possible that simplifying one loop could cause the other to be
993   // deleted.  If so, don't simplify it.
994   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
995     RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
996 }
997
998 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
999 /// specified.
1000 static void RemoveFromWorklist(Instruction *I, 
1001                                std::vector<Instruction*> &Worklist) {
1002   std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
1003                                                      Worklist.end(), I);
1004   while (WI != Worklist.end()) {
1005     unsigned Offset = WI-Worklist.begin();
1006     Worklist.erase(WI);
1007     WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
1008   }
1009 }
1010
1011 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
1012 /// program, replacing all uses with V and update the worklist.
1013 static void ReplaceUsesOfWith(Instruction *I, Value *V, 
1014                               std::vector<Instruction*> &Worklist,
1015                               Loop *L, LPPassManager *LPM) {
1016   DOUT << "Replace with '" << *V << "': " << *I;
1017
1018   // Add uses to the worklist, which may be dead now.
1019   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1020     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1021       Worklist.push_back(Use);
1022
1023   // Add users to the worklist which may be simplified now.
1024   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1025        UI != E; ++UI)
1026     Worklist.push_back(cast<Instruction>(*UI));
1027   LPM->deleteSimpleAnalysisValue(I, L);
1028   RemoveFromWorklist(I, Worklist);
1029   I->replaceAllUsesWith(V);
1030   I->eraseFromParent();
1031   ++NumSimplify;
1032 }
1033
1034 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
1035 /// information, and remove any dead successors it has.
1036 ///
1037 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
1038                                      std::vector<Instruction*> &Worklist,
1039                                      Loop *L) {
1040   if (pred_begin(BB) != pred_end(BB)) {
1041     // This block isn't dead, since an edge to BB was just removed, see if there
1042     // are any easy simplifications we can do now.
1043     if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1044       // If it has one pred, fold phi nodes in BB.
1045       while (isa<PHINode>(BB->begin()))
1046         ReplaceUsesOfWith(BB->begin(), 
1047                           cast<PHINode>(BB->begin())->getIncomingValue(0), 
1048                           Worklist, L, LPM);
1049       
1050       // If this is the header of a loop and the only pred is the latch, we now
1051       // have an unreachable loop.
1052       if (Loop *L = LI->getLoopFor(BB))
1053         if (loopHeader == BB && L->contains(Pred)) {
1054           // Remove the branch from the latch to the header block, this makes
1055           // the header dead, which will make the latch dead (because the header
1056           // dominates the latch).
1057           LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
1058           Pred->getTerminator()->eraseFromParent();
1059           new UnreachableInst(Pred);
1060           
1061           // The loop is now broken, remove it from LI.
1062           RemoveLoopFromHierarchy(L);
1063           
1064           // Reprocess the header, which now IS dead.
1065           RemoveBlockIfDead(BB, Worklist, L);
1066           return;
1067         }
1068       
1069       // If pred ends in a uncond branch, add uncond branch to worklist so that
1070       // the two blocks will get merged.
1071       if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
1072         if (BI->isUnconditional())
1073           Worklist.push_back(BI);
1074     }
1075     return;
1076   }
1077
1078   DOUT << "Nuking dead block: " << *BB;
1079   
1080   // Remove the instructions in the basic block from the worklist.
1081   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1082     RemoveFromWorklist(I, Worklist);
1083     
1084     // Anything that uses the instructions in this basic block should have their
1085     // uses replaced with undefs.
1086     if (!I->use_empty())
1087       I->replaceAllUsesWith(UndefValue::get(I->getType()));
1088   }
1089   
1090   // If this is the edge to the header block for a loop, remove the loop and
1091   // promote all subloops.
1092   if (Loop *BBLoop = LI->getLoopFor(BB)) {
1093     if (BBLoop->getLoopLatch() == BB)
1094       RemoveLoopFromHierarchy(BBLoop);
1095   }
1096
1097   // Remove the block from the loop info, which removes it from any loops it
1098   // was in.
1099   LI->removeBlock(BB);
1100   
1101   
1102   // Remove phi node entries in successors for this block.
1103   TerminatorInst *TI = BB->getTerminator();
1104   std::vector<BasicBlock*> Succs;
1105   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1106     Succs.push_back(TI->getSuccessor(i));
1107     TI->getSuccessor(i)->removePredecessor(BB);
1108   }
1109   
1110   // Unique the successors, remove anything with multiple uses.
1111   std::sort(Succs.begin(), Succs.end());
1112   Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
1113   
1114   // Remove the basic block, including all of the instructions contained in it.
1115   LPM->deleteSimpleAnalysisValue(BB, L);  
1116   BB->eraseFromParent();
1117   // Remove successor blocks here that are not dead, so that we know we only
1118   // have dead blocks in this list.  Nondead blocks have a way of becoming dead,
1119   // then getting removed before we revisit them, which is badness.
1120   //
1121   for (unsigned i = 0; i != Succs.size(); ++i)
1122     if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
1123       // One exception is loop headers.  If this block was the preheader for a
1124       // loop, then we DO want to visit the loop so the loop gets deleted.
1125       // We know that if the successor is a loop header, that this loop had to
1126       // be the preheader: the case where this was the latch block was handled
1127       // above and headers can only have two predecessors.
1128       if (!LI->isLoopHeader(Succs[i])) {
1129         Succs.erase(Succs.begin()+i);
1130         --i;
1131       }
1132     }
1133   
1134   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
1135     RemoveBlockIfDead(Succs[i], Worklist, L);
1136 }
1137
1138 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
1139 /// become unwrapped, either because the backedge was deleted, or because the
1140 /// edge into the header was removed.  If the edge into the header from the
1141 /// latch block was removed, the loop is unwrapped but subloops are still alive,
1142 /// so they just reparent loops.  If the loops are actually dead, they will be
1143 /// removed later.
1144 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
1145   LPM->deleteLoopFromQueue(L);
1146   RemoveLoopFromWorklist(L);
1147 }
1148
1149
1150
1151 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1152 // the value specified by Val in the specified loop, or we know it does NOT have
1153 // that value.  Rewrite any uses of LIC or of properties correlated to it.
1154 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1155                                                         Constant *Val,
1156                                                         bool IsEqual) {
1157   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1158   
1159   // FIXME: Support correlated properties, like:
1160   //  for (...)
1161   //    if (li1 < li2)
1162   //      ...
1163   //    if (li1 > li2)
1164   //      ...
1165   
1166   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
1167   // selects, switches.
1168   std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
1169   std::vector<Instruction*> Worklist;
1170
1171   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1172   // in the loop with the appropriate one directly.
1173   if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
1174     Value *Replacement;
1175     if (IsEqual)
1176       Replacement = Val;
1177     else
1178       Replacement = ConstantInt::get(Type::Int1Ty, 
1179                                      !cast<ConstantInt>(Val)->getZExtValue());
1180     
1181     for (unsigned i = 0, e = Users.size(); i != e; ++i)
1182       if (Instruction *U = cast<Instruction>(Users[i])) {
1183         if (!L->contains(U->getParent()))
1184           continue;
1185         U->replaceUsesOfWith(LIC, Replacement);
1186         Worklist.push_back(U);
1187       }
1188   } else {
1189     // Otherwise, we don't know the precise value of LIC, but we do know that it
1190     // is certainly NOT "Val".  As such, simplify any uses in the loop that we
1191     // can.  This case occurs when we unswitch switch statements.
1192     for (unsigned i = 0, e = Users.size(); i != e; ++i)
1193       if (Instruction *U = cast<Instruction>(Users[i])) {
1194         if (!L->contains(U->getParent()))
1195           continue;
1196
1197         Worklist.push_back(U);
1198
1199         // If we know that LIC is not Val, use this info to simplify code.
1200         if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1201           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1202             if (SI->getCaseValue(i) == Val) {
1203               // Found a dead case value.  Don't remove PHI nodes in the 
1204               // successor if they become single-entry, those PHI nodes may
1205               // be in the Users list.
1206               
1207               // FIXME: This is a hack.  We need to keep the successor around
1208               // and hooked up so as to preserve the loop structure, because
1209               // trying to update it is complicated.  So instead we preserve the
1210               // loop structure and put the block on an dead code path.
1211               
1212               BasicBlock* Old = SI->getParent();
1213               BasicBlock* Split = SplitBlock(Old, SI, this);
1214               
1215               Instruction* OldTerm = Old->getTerminator();
1216               BranchInst::Create(Split, SI->getSuccessor(i),
1217                                  ConstantInt::getTrue(), OldTerm);
1218
1219               LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
1220               Old->getTerminator()->eraseFromParent();
1221               
1222               PHINode *PN;
1223               for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
1224                    (PN = dyn_cast<PHINode>(II)); ++II) {
1225                 Value *InVal = PN->removeIncomingValue(Split, false);
1226                 PN->addIncoming(InVal, Old);
1227               }
1228
1229               SI->removeCase(i);
1230               break;
1231             }
1232           }
1233         }
1234         
1235         // TODO: We could do other simplifications, for example, turning 
1236         // LIC == Val -> false.
1237       }
1238   }
1239   
1240   SimplifyCode(Worklist, L);
1241 }
1242
1243 /// SimplifyCode - Okay, now that we have simplified some instructions in the 
1244 /// loop, walk over it and constant prop, dce, and fold control flow where
1245 /// possible.  Note that this is effectively a very simple loop-structure-aware
1246 /// optimizer.  During processing of this loop, L could very well be deleted, so
1247 /// it must not be used.
1248 ///
1249 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1250 /// pass.
1251 ///
1252 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1253   while (!Worklist.empty()) {
1254     Instruction *I = Worklist.back();
1255     Worklist.pop_back();
1256     
1257     // Simple constant folding.
1258     if (Constant *C = ConstantFoldInstruction(I)) {
1259       ReplaceUsesOfWith(I, C, Worklist, L, LPM);
1260       continue;
1261     }
1262     
1263     // Simple DCE.
1264     if (isInstructionTriviallyDead(I)) {
1265       DOUT << "Remove dead instruction '" << *I;
1266       
1267       // Add uses to the worklist, which may be dead now.
1268       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1269         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1270           Worklist.push_back(Use);
1271       LPM->deleteSimpleAnalysisValue(I, L);
1272       RemoveFromWorklist(I, Worklist);
1273       I->eraseFromParent();
1274       ++NumSimplify;
1275       continue;
1276     }
1277     
1278     // Special case hacks that appear commonly in unswitched code.
1279     switch (I->getOpcode()) {
1280     case Instruction::Select:
1281       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1282         ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1283                           LPM);
1284         continue;
1285       }
1286       break;
1287     case Instruction::And:
1288       if (isa<ConstantInt>(I->getOperand(0)) && 
1289           I->getOperand(0)->getType() == Type::Int1Ty)   // constant -> RHS
1290         cast<BinaryOperator>(I)->swapOperands();
1291       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1))) 
1292         if (CB->getType() == Type::Int1Ty) {
1293           if (CB->isOne())      // X & 1 -> X
1294             ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1295           else                  // X & 0 -> 0
1296             ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1297           continue;
1298         }
1299       break;
1300     case Instruction::Or:
1301       if (isa<ConstantInt>(I->getOperand(0)) &&
1302           I->getOperand(0)->getType() == Type::Int1Ty)   // constant -> RHS
1303         cast<BinaryOperator>(I)->swapOperands();
1304       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1305         if (CB->getType() == Type::Int1Ty) {
1306           if (CB->isOne())   // X | 1 -> 1
1307             ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1308           else                  // X | 0 -> X
1309             ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1310           continue;
1311         }
1312       break;
1313     case Instruction::Br: {
1314       BranchInst *BI = cast<BranchInst>(I);
1315       if (BI->isUnconditional()) {
1316         // If BI's parent is the only pred of the successor, fold the two blocks
1317         // together.
1318         BasicBlock *Pred = BI->getParent();
1319         BasicBlock *Succ = BI->getSuccessor(0);
1320         BasicBlock *SinglePred = Succ->getSinglePredecessor();
1321         if (!SinglePred) continue;  // Nothing to do.
1322         assert(SinglePred == Pred && "CFG broken");
1323
1324         DOUT << "Merging blocks: " << Pred->getName() << " <- " 
1325              << Succ->getName() << "\n";
1326         
1327         // Resolve any single entry PHI nodes in Succ.
1328         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1329           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1330         
1331         // Move all of the successor contents from Succ to Pred.
1332         Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1333                                    Succ->end());
1334         LPM->deleteSimpleAnalysisValue(BI, L);
1335         BI->eraseFromParent();
1336         RemoveFromWorklist(BI, Worklist);
1337         
1338         // If Succ has any successors with PHI nodes, update them to have
1339         // entries coming from Pred instead of Succ.
1340         Succ->replaceAllUsesWith(Pred);
1341         
1342         // Remove Succ from the loop tree.
1343         LI->removeBlock(Succ);
1344         LPM->deleteSimpleAnalysisValue(Succ, L);
1345         Succ->eraseFromParent();
1346         ++NumSimplify;
1347       } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1348         // Conditional branch.  Turn it into an unconditional branch, then
1349         // remove dead blocks.
1350         break;  // FIXME: Enable.
1351
1352         DOUT << "Folded branch: " << *BI;
1353         BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1354         BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1355         DeadSucc->removePredecessor(BI->getParent(), true);
1356         Worklist.push_back(BranchInst::Create(LiveSucc, BI));
1357         LPM->deleteSimpleAnalysisValue(BI, L);
1358         BI->eraseFromParent();
1359         RemoveFromWorklist(BI, Worklist);
1360         ++NumSimplify;
1361
1362         RemoveBlockIfDead(DeadSucc, Worklist, L);
1363       }
1364       break;
1365     }
1366     }
1367   }
1368 }