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