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