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