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