Revert "r214897 - Remove dead zero store to calloc initialized memory"
[oota-llvm.git] / lib / Transforms / Scalar / JumpThreading.cpp
1 //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
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 file implements the Jump Threading pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/CFG.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/LazyValueInfo.h"
25 #include "llvm/Analysis/Loads.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLibraryInfo.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Transforms/Utils/SSAUpdater.h"
39 using namespace llvm;
40
41 #define DEBUG_TYPE "jump-threading"
42
43 STATISTIC(NumThreads, "Number of jumps threaded");
44 STATISTIC(NumFolds,   "Number of terminators folded");
45 STATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
46
47 static cl::opt<unsigned>
48 Threshold("jump-threading-threshold",
49           cl::desc("Max block size to duplicate for jump threading"),
50           cl::init(6), cl::Hidden);
51
52 namespace {
53   // These are at global scope so static functions can use them too.
54   typedef SmallVectorImpl<std::pair<Constant*, BasicBlock*> > PredValueInfo;
55   typedef SmallVector<std::pair<Constant*, BasicBlock*>, 8> PredValueInfoTy;
56
57   // This is used to keep track of what kind of constant we're currently hoping
58   // to find.
59   enum ConstantPreference {
60     WantInteger,
61     WantBlockAddress
62   };
63
64   /// This pass performs 'jump threading', which looks at blocks that have
65   /// multiple predecessors and multiple successors.  If one or more of the
66   /// predecessors of the block can be proven to always jump to one of the
67   /// successors, we forward the edge from the predecessor to the successor by
68   /// duplicating the contents of this block.
69   ///
70   /// An example of when this can occur is code like this:
71   ///
72   ///   if () { ...
73   ///     X = 4;
74   ///   }
75   ///   if (X < 3) {
76   ///
77   /// In this case, the unconditional branch at the end of the first if can be
78   /// revectored to the false side of the second if.
79   ///
80   class JumpThreading : public FunctionPass {
81     const DataLayout *DL;
82     TargetLibraryInfo *TLI;
83     LazyValueInfo *LVI;
84 #ifdef NDEBUG
85     SmallPtrSet<BasicBlock*, 16> LoopHeaders;
86 #else
87     SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
88 #endif
89     DenseSet<std::pair<Value*, BasicBlock*> > RecursionSet;
90
91     // RAII helper for updating the recursion stack.
92     struct RecursionSetRemover {
93       DenseSet<std::pair<Value*, BasicBlock*> > &TheSet;
94       std::pair<Value*, BasicBlock*> ThePair;
95
96       RecursionSetRemover(DenseSet<std::pair<Value*, BasicBlock*> > &S,
97                           std::pair<Value*, BasicBlock*> P)
98         : TheSet(S), ThePair(P) { }
99
100       ~RecursionSetRemover() {
101         TheSet.erase(ThePair);
102       }
103     };
104   public:
105     static char ID; // Pass identification
106     JumpThreading() : FunctionPass(ID) {
107       initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
108     }
109
110     bool runOnFunction(Function &F) override;
111
112     void getAnalysisUsage(AnalysisUsage &AU) const override {
113       AU.addRequired<LazyValueInfo>();
114       AU.addPreserved<LazyValueInfo>();
115       AU.addRequired<TargetLibraryInfo>();
116     }
117
118     void FindLoopHeaders(Function &F);
119     bool ProcessBlock(BasicBlock *BB);
120     bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
121                     BasicBlock *SuccBB);
122     bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
123                                   const SmallVectorImpl<BasicBlock *> &PredBBs);
124
125     bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
126                                          PredValueInfo &Result,
127                                          ConstantPreference Preference);
128     bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
129                                 ConstantPreference Preference);
130
131     bool ProcessBranchOnPHI(PHINode *PN);
132     bool ProcessBranchOnXOR(BinaryOperator *BO);
133
134     bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
135     bool TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB);
136   };
137 }
138
139 char JumpThreading::ID = 0;
140 INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
141                 "Jump Threading", false, false)
142 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
143 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
144 INITIALIZE_PASS_END(JumpThreading, "jump-threading",
145                 "Jump Threading", false, false)
146
147 // Public interface to the Jump Threading pass
148 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
149
150 /// runOnFunction - Top level algorithm.
151 ///
152 bool JumpThreading::runOnFunction(Function &F) {
153   if (skipOptnoneFunction(F))
154     return false;
155
156   DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
157   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
158   DL = DLP ? &DLP->getDataLayout() : nullptr;
159   TLI = &getAnalysis<TargetLibraryInfo>();
160   LVI = &getAnalysis<LazyValueInfo>();
161
162   // Remove unreachable blocks from function as they may result in infinite
163   // loop. We do threading if we found something profitable. Jump threading a
164   // branch can create other opportunities. If these opportunities form a cycle
165   // i.e. if any jump treading is undoing previous threading in the path, then
166   // we will loop forever. We take care of this issue by not jump threading for
167   // back edges. This works for normal cases but not for unreachable blocks as
168   // they may have cycle with no back edge.
169   removeUnreachableBlocks(F);
170
171   FindLoopHeaders(F);
172
173   bool Changed, EverChanged = false;
174   do {
175     Changed = false;
176     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
177       BasicBlock *BB = I;
178       // Thread all of the branches we can over this block.
179       while (ProcessBlock(BB))
180         Changed = true;
181
182       ++I;
183
184       // If the block is trivially dead, zap it.  This eliminates the successor
185       // edges which simplifies the CFG.
186       if (pred_begin(BB) == pred_end(BB) &&
187           BB != &BB->getParent()->getEntryBlock()) {
188         DEBUG(dbgs() << "  JT: Deleting dead block '" << BB->getName()
189               << "' with terminator: " << *BB->getTerminator() << '\n');
190         LoopHeaders.erase(BB);
191         LVI->eraseBlock(BB);
192         DeleteDeadBlock(BB);
193         Changed = true;
194         continue;
195       }
196
197       BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
198
199       // Can't thread an unconditional jump, but if the block is "almost
200       // empty", we can replace uses of it with uses of the successor and make
201       // this dead.
202       if (BI && BI->isUnconditional() &&
203           BB != &BB->getParent()->getEntryBlock() &&
204           // If the terminator is the only non-phi instruction, try to nuke it.
205           BB->getFirstNonPHIOrDbg()->isTerminator()) {
206         // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
207         // block, we have to make sure it isn't in the LoopHeaders set.  We
208         // reinsert afterward if needed.
209         bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
210         BasicBlock *Succ = BI->getSuccessor(0);
211
212         // FIXME: It is always conservatively correct to drop the info
213         // for a block even if it doesn't get erased.  This isn't totally
214         // awesome, but it allows us to use AssertingVH to prevent nasty
215         // dangling pointer issues within LazyValueInfo.
216         LVI->eraseBlock(BB);
217         if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
218           Changed = true;
219           // If we deleted BB and BB was the header of a loop, then the
220           // successor is now the header of the loop.
221           BB = Succ;
222         }
223
224         if (ErasedFromLoopHeaders)
225           LoopHeaders.insert(BB);
226       }
227     }
228     EverChanged |= Changed;
229   } while (Changed);
230
231   LoopHeaders.clear();
232   return EverChanged;
233 }
234
235 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
236 /// thread across it. Stop scanning the block when passing the threshold.
237 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB,
238                                              unsigned Threshold) {
239   /// Ignore PHI nodes, these will be flattened when duplication happens.
240   BasicBlock::const_iterator I = BB->getFirstNonPHI();
241
242   // FIXME: THREADING will delete values that are just used to compute the
243   // branch, so they shouldn't count against the duplication cost.
244
245   // Sum up the cost of each instruction until we get to the terminator.  Don't
246   // include the terminator because the copy won't include it.
247   unsigned Size = 0;
248   for (; !isa<TerminatorInst>(I); ++I) {
249
250     // Stop scanning the block if we've reached the threshold.
251     if (Size > Threshold)
252       return Size;
253
254     // Debugger intrinsics don't incur code size.
255     if (isa<DbgInfoIntrinsic>(I)) continue;
256
257     // If this is a pointer->pointer bitcast, it is free.
258     if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
259       continue;
260
261     // All other instructions count for at least one unit.
262     ++Size;
263
264     // Calls are more expensive.  If they are non-intrinsic calls, we model them
265     // as having cost of 4.  If they are a non-vector intrinsic, we model them
266     // as having cost of 2 total, and if they are a vector intrinsic, we model
267     // them as having cost 1.
268     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
269       if (CI->cannotDuplicate())
270         // Blocks with NoDuplicate are modelled as having infinite cost, so they
271         // are never duplicated.
272         return ~0U;
273       else if (!isa<IntrinsicInst>(CI))
274         Size += 3;
275       else if (!CI->getType()->isVectorTy())
276         Size += 1;
277     }
278   }
279
280   // Threading through a switch statement is particularly profitable.  If this
281   // block ends in a switch, decrease its cost to make it more likely to happen.
282   if (isa<SwitchInst>(I))
283     Size = Size > 6 ? Size-6 : 0;
284
285   // The same holds for indirect branches, but slightly more so.
286   if (isa<IndirectBrInst>(I))
287     Size = Size > 8 ? Size-8 : 0;
288
289   return Size;
290 }
291
292 /// FindLoopHeaders - We do not want jump threading to turn proper loop
293 /// structures into irreducible loops.  Doing this breaks up the loop nesting
294 /// hierarchy and pessimizes later transformations.  To prevent this from
295 /// happening, we first have to find the loop headers.  Here we approximate this
296 /// by finding targets of backedges in the CFG.
297 ///
298 /// Note that there definitely are cases when we want to allow threading of
299 /// edges across a loop header.  For example, threading a jump from outside the
300 /// loop (the preheader) to an exit block of the loop is definitely profitable.
301 /// It is also almost always profitable to thread backedges from within the loop
302 /// to exit blocks, and is often profitable to thread backedges to other blocks
303 /// within the loop (forming a nested loop).  This simple analysis is not rich
304 /// enough to track all of these properties and keep it up-to-date as the CFG
305 /// mutates, so we don't allow any of these transformations.
306 ///
307 void JumpThreading::FindLoopHeaders(Function &F) {
308   SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
309   FindFunctionBackedges(F, Edges);
310
311   for (unsigned i = 0, e = Edges.size(); i != e; ++i)
312     LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
313 }
314
315 /// getKnownConstant - Helper method to determine if we can thread over a
316 /// terminator with the given value as its condition, and if so what value to
317 /// use for that. What kind of value this is depends on whether we want an
318 /// integer or a block address, but an undef is always accepted.
319 /// Returns null if Val is null or not an appropriate constant.
320 static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
321   if (!Val)
322     return nullptr;
323
324   // Undef is "known" enough.
325   if (UndefValue *U = dyn_cast<UndefValue>(Val))
326     return U;
327
328   if (Preference == WantBlockAddress)
329     return dyn_cast<BlockAddress>(Val->stripPointerCasts());
330
331   return dyn_cast<ConstantInt>(Val);
332 }
333
334 /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
335 /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
336 /// in any of our predecessors.  If so, return the known list of value and pred
337 /// BB in the result vector.
338 ///
339 /// This returns true if there were any known values.
340 ///
341 bool JumpThreading::
342 ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB, PredValueInfo &Result,
343                                 ConstantPreference Preference) {
344   // This method walks up use-def chains recursively.  Because of this, we could
345   // get into an infinite loop going around loops in the use-def chain.  To
346   // prevent this, keep track of what (value, block) pairs we've already visited
347   // and terminate the search if we loop back to them
348   if (!RecursionSet.insert(std::make_pair(V, BB)).second)
349     return false;
350
351   // An RAII help to remove this pair from the recursion set once the recursion
352   // stack pops back out again.
353   RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
354
355   // If V is a constant, then it is known in all predecessors.
356   if (Constant *KC = getKnownConstant(V, Preference)) {
357     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
358       Result.push_back(std::make_pair(KC, *PI));
359
360     return true;
361   }
362
363   // If V is a non-instruction value, or an instruction in a different block,
364   // then it can't be derived from a PHI.
365   Instruction *I = dyn_cast<Instruction>(V);
366   if (!I || I->getParent() != BB) {
367
368     // Okay, if this is a live-in value, see if it has a known value at the end
369     // of any of our predecessors.
370     //
371     // FIXME: This should be an edge property, not a block end property.
372     /// TODO: Per PR2563, we could infer value range information about a
373     /// predecessor based on its terminator.
374     //
375     // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
376     // "I" is a non-local compare-with-a-constant instruction.  This would be
377     // able to handle value inequalities better, for example if the compare is
378     // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
379     // Perhaps getConstantOnEdge should be smart enough to do this?
380
381     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
382       BasicBlock *P = *PI;
383       // If the value is known by LazyValueInfo to be a constant in a
384       // predecessor, use that information to try to thread this block.
385       Constant *PredCst = LVI->getConstantOnEdge(V, P, BB);
386       if (Constant *KC = getKnownConstant(PredCst, Preference))
387         Result.push_back(std::make_pair(KC, P));
388     }
389
390     return !Result.empty();
391   }
392
393   /// If I is a PHI node, then we know the incoming values for any constants.
394   if (PHINode *PN = dyn_cast<PHINode>(I)) {
395     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
396       Value *InVal = PN->getIncomingValue(i);
397       if (Constant *KC = getKnownConstant(InVal, Preference)) {
398         Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
399       } else {
400         Constant *CI = LVI->getConstantOnEdge(InVal,
401                                               PN->getIncomingBlock(i), BB);
402         if (Constant *KC = getKnownConstant(CI, Preference))
403           Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
404       }
405     }
406
407     return !Result.empty();
408   }
409
410   PredValueInfoTy LHSVals, RHSVals;
411
412   // Handle some boolean conditions.
413   if (I->getType()->getPrimitiveSizeInBits() == 1) {
414     assert(Preference == WantInteger && "One-bit non-integer type?");
415     // X | true -> true
416     // X & false -> false
417     if (I->getOpcode() == Instruction::Or ||
418         I->getOpcode() == Instruction::And) {
419       ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
420                                       WantInteger);
421       ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals,
422                                       WantInteger);
423
424       if (LHSVals.empty() && RHSVals.empty())
425         return false;
426
427       ConstantInt *InterestingVal;
428       if (I->getOpcode() == Instruction::Or)
429         InterestingVal = ConstantInt::getTrue(I->getContext());
430       else
431         InterestingVal = ConstantInt::getFalse(I->getContext());
432
433       SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
434
435       // Scan for the sentinel.  If we find an undef, force it to the
436       // interesting value: x|undef -> true and x&undef -> false.
437       for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
438         if (LHSVals[i].first == InterestingVal ||
439             isa<UndefValue>(LHSVals[i].first)) {
440           Result.push_back(LHSVals[i]);
441           Result.back().first = InterestingVal;
442           LHSKnownBBs.insert(LHSVals[i].second);
443         }
444       for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
445         if (RHSVals[i].first == InterestingVal ||
446             isa<UndefValue>(RHSVals[i].first)) {
447           // If we already inferred a value for this block on the LHS, don't
448           // re-add it.
449           if (!LHSKnownBBs.count(RHSVals[i].second)) {
450             Result.push_back(RHSVals[i]);
451             Result.back().first = InterestingVal;
452           }
453         }
454
455       return !Result.empty();
456     }
457
458     // Handle the NOT form of XOR.
459     if (I->getOpcode() == Instruction::Xor &&
460         isa<ConstantInt>(I->getOperand(1)) &&
461         cast<ConstantInt>(I->getOperand(1))->isOne()) {
462       ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result,
463                                       WantInteger);
464       if (Result.empty())
465         return false;
466
467       // Invert the known values.
468       for (unsigned i = 0, e = Result.size(); i != e; ++i)
469         Result[i].first = ConstantExpr::getNot(Result[i].first);
470
471       return true;
472     }
473
474   // Try to simplify some other binary operator values.
475   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
476     assert(Preference != WantBlockAddress
477             && "A binary operator creating a block address?");
478     if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
479       PredValueInfoTy LHSVals;
480       ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals,
481                                       WantInteger);
482
483       // Try to use constant folding to simplify the binary operator.
484       for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
485         Constant *V = LHSVals[i].first;
486         Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
487
488         if (Constant *KC = getKnownConstant(Folded, WantInteger))
489           Result.push_back(std::make_pair(KC, LHSVals[i].second));
490       }
491     }
492
493     return !Result.empty();
494   }
495
496   // Handle compare with phi operand, where the PHI is defined in this block.
497   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
498     assert(Preference == WantInteger && "Compares only produce integers");
499     PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
500     if (PN && PN->getParent() == BB) {
501       // We can do this simplification if any comparisons fold to true or false.
502       // See if any do.
503       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
504         BasicBlock *PredBB = PN->getIncomingBlock(i);
505         Value *LHS = PN->getIncomingValue(i);
506         Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
507
508         Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, DL);
509         if (!Res) {
510           if (!isa<Constant>(RHS))
511             continue;
512
513           LazyValueInfo::Tristate
514             ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
515                                            cast<Constant>(RHS), PredBB, BB);
516           if (ResT == LazyValueInfo::Unknown)
517             continue;
518           Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
519         }
520
521         if (Constant *KC = getKnownConstant(Res, WantInteger))
522           Result.push_back(std::make_pair(KC, PredBB));
523       }
524
525       return !Result.empty();
526     }
527
528
529     // If comparing a live-in value against a constant, see if we know the
530     // live-in value on any predecessors.
531     if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
532       if (!isa<Instruction>(Cmp->getOperand(0)) ||
533           cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
534         Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
535
536         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
537           BasicBlock *P = *PI;
538           // If the value is known by LazyValueInfo to be a constant in a
539           // predecessor, use that information to try to thread this block.
540           LazyValueInfo::Tristate Res =
541             LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
542                                     RHSCst, P, BB);
543           if (Res == LazyValueInfo::Unknown)
544             continue;
545
546           Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
547           Result.push_back(std::make_pair(ResC, P));
548         }
549
550         return !Result.empty();
551       }
552
553       // Try to find a constant value for the LHS of a comparison,
554       // and evaluate it statically if we can.
555       if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
556         PredValueInfoTy LHSVals;
557         ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
558                                         WantInteger);
559
560         for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
561           Constant *V = LHSVals[i].first;
562           Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
563                                                       V, CmpConst);
564           if (Constant *KC = getKnownConstant(Folded, WantInteger))
565             Result.push_back(std::make_pair(KC, LHSVals[i].second));
566         }
567
568         return !Result.empty();
569       }
570     }
571   }
572
573   if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
574     // Handle select instructions where at least one operand is a known constant
575     // and we can figure out the condition value for any predecessor block.
576     Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
577     Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
578     PredValueInfoTy Conds;
579     if ((TrueVal || FalseVal) &&
580         ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds,
581                                         WantInteger)) {
582       for (unsigned i = 0, e = Conds.size(); i != e; ++i) {
583         Constant *Cond = Conds[i].first;
584
585         // Figure out what value to use for the condition.
586         bool KnownCond;
587         if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
588           // A known boolean.
589           KnownCond = CI->isOne();
590         } else {
591           assert(isa<UndefValue>(Cond) && "Unexpected condition value");
592           // Either operand will do, so be sure to pick the one that's a known
593           // constant.
594           // FIXME: Do this more cleverly if both values are known constants?
595           KnownCond = (TrueVal != nullptr);
596         }
597
598         // See if the select has a known constant value for this predecessor.
599         if (Constant *Val = KnownCond ? TrueVal : FalseVal)
600           Result.push_back(std::make_pair(Val, Conds[i].second));
601       }
602
603       return !Result.empty();
604     }
605   }
606
607   // If all else fails, see if LVI can figure out a constant value for us.
608   Constant *CI = LVI->getConstant(V, BB);
609   if (Constant *KC = getKnownConstant(CI, Preference)) {
610     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
611       Result.push_back(std::make_pair(KC, *PI));
612   }
613
614   return !Result.empty();
615 }
616
617
618
619 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
620 /// in an undefined jump, decide which block is best to revector to.
621 ///
622 /// Since we can pick an arbitrary destination, we pick the successor with the
623 /// fewest predecessors.  This should reduce the in-degree of the others.
624 ///
625 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
626   TerminatorInst *BBTerm = BB->getTerminator();
627   unsigned MinSucc = 0;
628   BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
629   // Compute the successor with the minimum number of predecessors.
630   unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
631   for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
632     TestBB = BBTerm->getSuccessor(i);
633     unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
634     if (NumPreds < MinNumPreds) {
635       MinSucc = i;
636       MinNumPreds = NumPreds;
637     }
638   }
639
640   return MinSucc;
641 }
642
643 static bool hasAddressTakenAndUsed(BasicBlock *BB) {
644   if (!BB->hasAddressTaken()) return false;
645
646   // If the block has its address taken, it may be a tree of dead constants
647   // hanging off of it.  These shouldn't keep the block alive.
648   BlockAddress *BA = BlockAddress::get(BB);
649   BA->removeDeadConstantUsers();
650   return !BA->use_empty();
651 }
652
653 /// ProcessBlock - If there are any predecessors whose control can be threaded
654 /// through to a successor, transform them now.
655 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
656   // If the block is trivially dead, just return and let the caller nuke it.
657   // This simplifies other transformations.
658   if (pred_begin(BB) == pred_end(BB) &&
659       BB != &BB->getParent()->getEntryBlock())
660     return false;
661
662   // If this block has a single predecessor, and if that pred has a single
663   // successor, merge the blocks.  This encourages recursive jump threading
664   // because now the condition in this block can be threaded through
665   // predecessors of our predecessor block.
666   if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
667     if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
668         SinglePred != BB && !hasAddressTakenAndUsed(BB)) {
669       // If SinglePred was a loop header, BB becomes one.
670       if (LoopHeaders.erase(SinglePred))
671         LoopHeaders.insert(BB);
672
673       LVI->eraseBlock(SinglePred);
674       MergeBasicBlockIntoOnlyPred(BB);
675
676       return true;
677     }
678   }
679
680   // What kind of constant we're looking for.
681   ConstantPreference Preference = WantInteger;
682
683   // Look to see if the terminator is a conditional branch, switch or indirect
684   // branch, if not we can't thread it.
685   Value *Condition;
686   Instruction *Terminator = BB->getTerminator();
687   if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
688     // Can't thread an unconditional jump.
689     if (BI->isUnconditional()) return false;
690     Condition = BI->getCondition();
691   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
692     Condition = SI->getCondition();
693   } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
694     // Can't thread indirect branch with no successors.
695     if (IB->getNumSuccessors() == 0) return false;
696     Condition = IB->getAddress()->stripPointerCasts();
697     Preference = WantBlockAddress;
698   } else {
699     return false; // Must be an invoke.
700   }
701
702   // Run constant folding to see if we can reduce the condition to a simple
703   // constant.
704   if (Instruction *I = dyn_cast<Instruction>(Condition)) {
705     Value *SimpleVal = ConstantFoldInstruction(I, DL, TLI);
706     if (SimpleVal) {
707       I->replaceAllUsesWith(SimpleVal);
708       I->eraseFromParent();
709       Condition = SimpleVal;
710     }
711   }
712
713   // If the terminator is branching on an undef, we can pick any of the
714   // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
715   if (isa<UndefValue>(Condition)) {
716     unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
717
718     // Fold the branch/switch.
719     TerminatorInst *BBTerm = BB->getTerminator();
720     for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
721       if (i == BestSucc) continue;
722       BBTerm->getSuccessor(i)->removePredecessor(BB, true);
723     }
724
725     DEBUG(dbgs() << "  In block '" << BB->getName()
726           << "' folding undef terminator: " << *BBTerm << '\n');
727     BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
728     BBTerm->eraseFromParent();
729     return true;
730   }
731
732   // If the terminator of this block is branching on a constant, simplify the
733   // terminator to an unconditional branch.  This can occur due to threading in
734   // other blocks.
735   if (getKnownConstant(Condition, Preference)) {
736     DEBUG(dbgs() << "  In block '" << BB->getName()
737           << "' folding terminator: " << *BB->getTerminator() << '\n');
738     ++NumFolds;
739     ConstantFoldTerminator(BB, true);
740     return true;
741   }
742
743   Instruction *CondInst = dyn_cast<Instruction>(Condition);
744
745   // All the rest of our checks depend on the condition being an instruction.
746   if (!CondInst) {
747     // FIXME: Unify this with code below.
748     if (ProcessThreadableEdges(Condition, BB, Preference))
749       return true;
750     return false;
751   }
752
753
754   if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
755     // For a comparison where the LHS is outside this block, it's possible
756     // that we've branched on it before.  Used LVI to see if we can simplify
757     // the branch based on that.
758     BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
759     Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
760     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
761     if (CondBr && CondConst && CondBr->isConditional() && PI != PE &&
762         (!isa<Instruction>(CondCmp->getOperand(0)) ||
763          cast<Instruction>(CondCmp->getOperand(0))->getParent() != BB)) {
764       // For predecessor edge, determine if the comparison is true or false
765       // on that edge.  If they're all true or all false, we can simplify the
766       // branch.
767       // FIXME: We could handle mixed true/false by duplicating code.
768       LazyValueInfo::Tristate Baseline =
769         LVI->getPredicateOnEdge(CondCmp->getPredicate(), CondCmp->getOperand(0),
770                                 CondConst, *PI, BB);
771       if (Baseline != LazyValueInfo::Unknown) {
772         // Check that all remaining incoming values match the first one.
773         while (++PI != PE) {
774           LazyValueInfo::Tristate Ret =
775             LVI->getPredicateOnEdge(CondCmp->getPredicate(),
776                                     CondCmp->getOperand(0), CondConst, *PI, BB);
777           if (Ret != Baseline) break;
778         }
779
780         // If we terminated early, then one of the values didn't match.
781         if (PI == PE) {
782           unsigned ToRemove = Baseline == LazyValueInfo::True ? 1 : 0;
783           unsigned ToKeep = Baseline == LazyValueInfo::True ? 0 : 1;
784           CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
785           BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
786           CondBr->eraseFromParent();
787           return true;
788         }
789       }
790
791     }
792
793     if (CondBr && CondConst && TryToUnfoldSelect(CondCmp, BB))
794       return true;
795   }
796
797   // Check for some cases that are worth simplifying.  Right now we want to look
798   // for loads that are used by a switch or by the condition for the branch.  If
799   // we see one, check to see if it's partially redundant.  If so, insert a PHI
800   // which can then be used to thread the values.
801   //
802   Value *SimplifyValue = CondInst;
803   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
804     if (isa<Constant>(CondCmp->getOperand(1)))
805       SimplifyValue = CondCmp->getOperand(0);
806
807   // TODO: There are other places where load PRE would be profitable, such as
808   // more complex comparisons.
809   if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
810     if (SimplifyPartiallyRedundantLoad(LI))
811       return true;
812
813
814   // Handle a variety of cases where we are branching on something derived from
815   // a PHI node in the current block.  If we can prove that any predecessors
816   // compute a predictable value based on a PHI node, thread those predecessors.
817   //
818   if (ProcessThreadableEdges(CondInst, BB, Preference))
819     return true;
820
821   // If this is an otherwise-unfoldable branch on a phi node in the current
822   // block, see if we can simplify.
823   if (PHINode *PN = dyn_cast<PHINode>(CondInst))
824     if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
825       return ProcessBranchOnPHI(PN);
826
827
828   // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
829   if (CondInst->getOpcode() == Instruction::Xor &&
830       CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
831     return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
832
833
834   // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
835   // "(X == 4)", thread through this block.
836
837   return false;
838 }
839
840 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
841 /// load instruction, eliminate it by replacing it with a PHI node.  This is an
842 /// important optimization that encourages jump threading, and needs to be run
843 /// interlaced with other jump threading tasks.
844 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
845   // Don't hack volatile/atomic loads.
846   if (!LI->isSimple()) return false;
847
848   // If the load is defined in a block with exactly one predecessor, it can't be
849   // partially redundant.
850   BasicBlock *LoadBB = LI->getParent();
851   if (LoadBB->getSinglePredecessor())
852     return false;
853
854   // If the load is defined in a landing pad, it can't be partially redundant,
855   // because the edges between the invoke and the landing pad cannot have other
856   // instructions between them.
857   if (LoadBB->isLandingPad())
858     return false;
859
860   Value *LoadedPtr = LI->getOperand(0);
861
862   // If the loaded operand is defined in the LoadBB, it can't be available.
863   // TODO: Could do simple PHI translation, that would be fun :)
864   if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
865     if (PtrOp->getParent() == LoadBB)
866       return false;
867
868   // Scan a few instructions up from the load, to see if it is obviously live at
869   // the entry to its block.
870   BasicBlock::iterator BBIt = LI;
871
872   if (Value *AvailableVal =
873         FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
874     // If the value if the load is locally available within the block, just use
875     // it.  This frequently occurs for reg2mem'd allocas.
876     //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
877
878     // If the returned value is the load itself, replace with an undef. This can
879     // only happen in dead loops.
880     if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
881     LI->replaceAllUsesWith(AvailableVal);
882     LI->eraseFromParent();
883     return true;
884   }
885
886   // Otherwise, if we scanned the whole block and got to the top of the block,
887   // we know the block is locally transparent to the load.  If not, something
888   // might clobber its value.
889   if (BBIt != LoadBB->begin())
890     return false;
891
892   // If all of the loads and stores that feed the value have the same AA tags,
893   // then we can propagate them onto any newly inserted loads.
894   AAMDNodes AATags;
895   LI->getAAMetadata(AATags);
896
897   SmallPtrSet<BasicBlock*, 8> PredsScanned;
898   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
899   AvailablePredsTy AvailablePreds;
900   BasicBlock *OneUnavailablePred = nullptr;
901
902   // If we got here, the loaded value is transparent through to the start of the
903   // block.  Check to see if it is available in any of the predecessor blocks.
904   for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
905        PI != PE; ++PI) {
906     BasicBlock *PredBB = *PI;
907
908     // If we already scanned this predecessor, skip it.
909     if (!PredsScanned.insert(PredBB))
910       continue;
911
912     // Scan the predecessor to see if the value is available in the pred.
913     BBIt = PredBB->end();
914     AAMDNodes ThisAATags;
915     Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6,
916                                                     nullptr, &ThisAATags);
917     if (!PredAvailable) {
918       OneUnavailablePred = PredBB;
919       continue;
920     }
921
922     // If AA tags disagree or are not present, forget about them.
923     if (AATags != ThisAATags) AATags = AAMDNodes();
924
925     // If so, this load is partially redundant.  Remember this info so that we
926     // can create a PHI node.
927     AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
928   }
929
930   // If the loaded value isn't available in any predecessor, it isn't partially
931   // redundant.
932   if (AvailablePreds.empty()) return false;
933
934   // Okay, the loaded value is available in at least one (and maybe all!)
935   // predecessors.  If the value is unavailable in more than one unique
936   // predecessor, we want to insert a merge block for those common predecessors.
937   // This ensures that we only have to insert one reload, thus not increasing
938   // code size.
939   BasicBlock *UnavailablePred = nullptr;
940
941   // If there is exactly one predecessor where the value is unavailable, the
942   // already computed 'OneUnavailablePred' block is it.  If it ends in an
943   // unconditional branch, we know that it isn't a critical edge.
944   if (PredsScanned.size() == AvailablePreds.size()+1 &&
945       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
946     UnavailablePred = OneUnavailablePred;
947   } else if (PredsScanned.size() != AvailablePreds.size()) {
948     // Otherwise, we had multiple unavailable predecessors or we had a critical
949     // edge from the one.
950     SmallVector<BasicBlock*, 8> PredsToSplit;
951     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
952
953     for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
954       AvailablePredSet.insert(AvailablePreds[i].first);
955
956     // Add all the unavailable predecessors to the PredsToSplit list.
957     for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
958          PI != PE; ++PI) {
959       BasicBlock *P = *PI;
960       // If the predecessor is an indirect goto, we can't split the edge.
961       if (isa<IndirectBrInst>(P->getTerminator()))
962         return false;
963
964       if (!AvailablePredSet.count(P))
965         PredsToSplit.push_back(P);
966     }
967
968     // Split them out to their own block.
969     UnavailablePred =
970       SplitBlockPredecessors(LoadBB, PredsToSplit, "thread-pre-split", this);
971   }
972
973   // If the value isn't available in all predecessors, then there will be
974   // exactly one where it isn't available.  Insert a load on that edge and add
975   // it to the AvailablePreds list.
976   if (UnavailablePred) {
977     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
978            "Can't handle critical edge here!");
979     LoadInst *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
980                                  LI->getAlignment(),
981                                  UnavailablePred->getTerminator());
982     NewVal->setDebugLoc(LI->getDebugLoc());
983     if (AATags)
984       NewVal->setAAMetadata(AATags);
985
986     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
987   }
988
989   // Now we know that each predecessor of this block has a value in
990   // AvailablePreds, sort them for efficient access as we're walking the preds.
991   array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
992
993   // Create a PHI node at the start of the block for the PRE'd load value.
994   pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
995   PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
996                                 LoadBB->begin());
997   PN->takeName(LI);
998   PN->setDebugLoc(LI->getDebugLoc());
999
1000   // Insert new entries into the PHI for each predecessor.  A single block may
1001   // have multiple entries here.
1002   for (pred_iterator PI = PB; PI != PE; ++PI) {
1003     BasicBlock *P = *PI;
1004     AvailablePredsTy::iterator I =
1005       std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
1006                        std::make_pair(P, (Value*)nullptr));
1007
1008     assert(I != AvailablePreds.end() && I->first == P &&
1009            "Didn't find entry for predecessor!");
1010
1011     PN->addIncoming(I->second, I->first);
1012   }
1013
1014   //cerr << "PRE: " << *LI << *PN << "\n";
1015
1016   LI->replaceAllUsesWith(PN);
1017   LI->eraseFromParent();
1018
1019   return true;
1020 }
1021
1022 /// FindMostPopularDest - The specified list contains multiple possible
1023 /// threadable destinations.  Pick the one that occurs the most frequently in
1024 /// the list.
1025 static BasicBlock *
1026 FindMostPopularDest(BasicBlock *BB,
1027                     const SmallVectorImpl<std::pair<BasicBlock*,
1028                                   BasicBlock*> > &PredToDestList) {
1029   assert(!PredToDestList.empty());
1030
1031   // Determine popularity.  If there are multiple possible destinations, we
1032   // explicitly choose to ignore 'undef' destinations.  We prefer to thread
1033   // blocks with known and real destinations to threading undef.  We'll handle
1034   // them later if interesting.
1035   DenseMap<BasicBlock*, unsigned> DestPopularity;
1036   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
1037     if (PredToDestList[i].second)
1038       DestPopularity[PredToDestList[i].second]++;
1039
1040   // Find the most popular dest.
1041   DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
1042   BasicBlock *MostPopularDest = DPI->first;
1043   unsigned Popularity = DPI->second;
1044   SmallVector<BasicBlock*, 4> SamePopularity;
1045
1046   for (++DPI; DPI != DestPopularity.end(); ++DPI) {
1047     // If the popularity of this entry isn't higher than the popularity we've
1048     // seen so far, ignore it.
1049     if (DPI->second < Popularity)
1050       ; // ignore.
1051     else if (DPI->second == Popularity) {
1052       // If it is the same as what we've seen so far, keep track of it.
1053       SamePopularity.push_back(DPI->first);
1054     } else {
1055       // If it is more popular, remember it.
1056       SamePopularity.clear();
1057       MostPopularDest = DPI->first;
1058       Popularity = DPI->second;
1059     }
1060   }
1061
1062   // Okay, now we know the most popular destination.  If there is more than one
1063   // destination, we need to determine one.  This is arbitrary, but we need
1064   // to make a deterministic decision.  Pick the first one that appears in the
1065   // successor list.
1066   if (!SamePopularity.empty()) {
1067     SamePopularity.push_back(MostPopularDest);
1068     TerminatorInst *TI = BB->getTerminator();
1069     for (unsigned i = 0; ; ++i) {
1070       assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
1071
1072       if (std::find(SamePopularity.begin(), SamePopularity.end(),
1073                     TI->getSuccessor(i)) == SamePopularity.end())
1074         continue;
1075
1076       MostPopularDest = TI->getSuccessor(i);
1077       break;
1078     }
1079   }
1080
1081   // Okay, we have finally picked the most popular destination.
1082   return MostPopularDest;
1083 }
1084
1085 bool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
1086                                            ConstantPreference Preference) {
1087   // If threading this would thread across a loop header, don't even try to
1088   // thread the edge.
1089   if (LoopHeaders.count(BB))
1090     return false;
1091
1092   PredValueInfoTy PredValues;
1093   if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference))
1094     return false;
1095
1096   assert(!PredValues.empty() &&
1097          "ComputeValueKnownInPredecessors returned true with no values");
1098
1099   DEBUG(dbgs() << "IN BB: " << *BB;
1100         for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
1101           dbgs() << "  BB '" << BB->getName() << "': FOUND condition = "
1102             << *PredValues[i].first
1103             << " for pred '" << PredValues[i].second->getName() << "'.\n";
1104         });
1105
1106   // Decide what we want to thread through.  Convert our list of known values to
1107   // a list of known destinations for each pred.  This also discards duplicate
1108   // predecessors and keeps track of the undefined inputs (which are represented
1109   // as a null dest in the PredToDestList).
1110   SmallPtrSet<BasicBlock*, 16> SeenPreds;
1111   SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1112
1113   BasicBlock *OnlyDest = nullptr;
1114   BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1115
1116   for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
1117     BasicBlock *Pred = PredValues[i].second;
1118     if (!SeenPreds.insert(Pred))
1119       continue;  // Duplicate predecessor entry.
1120
1121     // If the predecessor ends with an indirect goto, we can't change its
1122     // destination.
1123     if (isa<IndirectBrInst>(Pred->getTerminator()))
1124       continue;
1125
1126     Constant *Val = PredValues[i].first;
1127
1128     BasicBlock *DestBB;
1129     if (isa<UndefValue>(Val))
1130       DestBB = nullptr;
1131     else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
1132       DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
1133     else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1134       DestBB = SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccessor();
1135     } else {
1136       assert(isa<IndirectBrInst>(BB->getTerminator())
1137               && "Unexpected terminator");
1138       DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1139     }
1140
1141     // If we have exactly one destination, remember it for efficiency below.
1142     if (PredToDestList.empty())
1143       OnlyDest = DestBB;
1144     else if (OnlyDest != DestBB)
1145       OnlyDest = MultipleDestSentinel;
1146
1147     PredToDestList.push_back(std::make_pair(Pred, DestBB));
1148   }
1149
1150   // If all edges were unthreadable, we fail.
1151   if (PredToDestList.empty())
1152     return false;
1153
1154   // Determine which is the most common successor.  If we have many inputs and
1155   // this block is a switch, we want to start by threading the batch that goes
1156   // to the most popular destination first.  If we only know about one
1157   // threadable destination (the common case) we can avoid this.
1158   BasicBlock *MostPopularDest = OnlyDest;
1159
1160   if (MostPopularDest == MultipleDestSentinel)
1161     MostPopularDest = FindMostPopularDest(BB, PredToDestList);
1162
1163   // Now that we know what the most popular destination is, factor all
1164   // predecessors that will jump to it into a single predecessor.
1165   SmallVector<BasicBlock*, 16> PredsToFactor;
1166   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
1167     if (PredToDestList[i].second == MostPopularDest) {
1168       BasicBlock *Pred = PredToDestList[i].first;
1169
1170       // This predecessor may be a switch or something else that has multiple
1171       // edges to the block.  Factor each of these edges by listing them
1172       // according to # occurrences in PredsToFactor.
1173       TerminatorInst *PredTI = Pred->getTerminator();
1174       for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
1175         if (PredTI->getSuccessor(i) == BB)
1176           PredsToFactor.push_back(Pred);
1177     }
1178
1179   // If the threadable edges are branching on an undefined value, we get to pick
1180   // the destination that these predecessors should get to.
1181   if (!MostPopularDest)
1182     MostPopularDest = BB->getTerminator()->
1183                             getSuccessor(GetBestDestForJumpOnUndef(BB));
1184
1185   // Ok, try to thread it!
1186   return ThreadEdge(BB, PredsToFactor, MostPopularDest);
1187 }
1188
1189 /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
1190 /// a PHI node in the current block.  See if there are any simplifications we
1191 /// can do based on inputs to the phi node.
1192 ///
1193 bool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
1194   BasicBlock *BB = PN->getParent();
1195
1196   // TODO: We could make use of this to do it once for blocks with common PHI
1197   // values.
1198   SmallVector<BasicBlock*, 1> PredBBs;
1199   PredBBs.resize(1);
1200
1201   // If any of the predecessor blocks end in an unconditional branch, we can
1202   // *duplicate* the conditional branch into that block in order to further
1203   // encourage jump threading and to eliminate cases where we have branch on a
1204   // phi of an icmp (branch on icmp is much better).
1205   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1206     BasicBlock *PredBB = PN->getIncomingBlock(i);
1207     if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1208       if (PredBr->isUnconditional()) {
1209         PredBBs[0] = PredBB;
1210         // Try to duplicate BB into PredBB.
1211         if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1212           return true;
1213       }
1214   }
1215
1216   return false;
1217 }
1218
1219 /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
1220 /// a xor instruction in the current block.  See if there are any
1221 /// simplifications we can do based on inputs to the xor.
1222 ///
1223 bool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
1224   BasicBlock *BB = BO->getParent();
1225
1226   // If either the LHS or RHS of the xor is a constant, don't do this
1227   // optimization.
1228   if (isa<ConstantInt>(BO->getOperand(0)) ||
1229       isa<ConstantInt>(BO->getOperand(1)))
1230     return false;
1231
1232   // If the first instruction in BB isn't a phi, we won't be able to infer
1233   // anything special about any particular predecessor.
1234   if (!isa<PHINode>(BB->front()))
1235     return false;
1236
1237   // If we have a xor as the branch input to this block, and we know that the
1238   // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1239   // the condition into the predecessor and fix that value to true, saving some
1240   // logical ops on that path and encouraging other paths to simplify.
1241   //
1242   // This copies something like this:
1243   //
1244   //  BB:
1245   //    %X = phi i1 [1],  [%X']
1246   //    %Y = icmp eq i32 %A, %B
1247   //    %Z = xor i1 %X, %Y
1248   //    br i1 %Z, ...
1249   //
1250   // Into:
1251   //  BB':
1252   //    %Y = icmp ne i32 %A, %B
1253   //    br i1 %Z, ...
1254
1255   PredValueInfoTy XorOpValues;
1256   bool isLHS = true;
1257   if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
1258                                        WantInteger)) {
1259     assert(XorOpValues.empty());
1260     if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
1261                                          WantInteger))
1262       return false;
1263     isLHS = false;
1264   }
1265
1266   assert(!XorOpValues.empty() &&
1267          "ComputeValueKnownInPredecessors returned true with no values");
1268
1269   // Scan the information to see which is most popular: true or false.  The
1270   // predecessors can be of the set true, false, or undef.
1271   unsigned NumTrue = 0, NumFalse = 0;
1272   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1273     if (isa<UndefValue>(XorOpValues[i].first))
1274       // Ignore undefs for the count.
1275       continue;
1276     if (cast<ConstantInt>(XorOpValues[i].first)->isZero())
1277       ++NumFalse;
1278     else
1279       ++NumTrue;
1280   }
1281
1282   // Determine which value to split on, true, false, or undef if neither.
1283   ConstantInt *SplitVal = nullptr;
1284   if (NumTrue > NumFalse)
1285     SplitVal = ConstantInt::getTrue(BB->getContext());
1286   else if (NumTrue != 0 || NumFalse != 0)
1287     SplitVal = ConstantInt::getFalse(BB->getContext());
1288
1289   // Collect all of the blocks that this can be folded into so that we can
1290   // factor this once and clone it once.
1291   SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1292   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1293     if (XorOpValues[i].first != SplitVal &&
1294         !isa<UndefValue>(XorOpValues[i].first))
1295       continue;
1296
1297     BlocksToFoldInto.push_back(XorOpValues[i].second);
1298   }
1299
1300   // If we inferred a value for all of the predecessors, then duplication won't
1301   // help us.  However, we can just replace the LHS or RHS with the constant.
1302   if (BlocksToFoldInto.size() ==
1303       cast<PHINode>(BB->front()).getNumIncomingValues()) {
1304     if (!SplitVal) {
1305       // If all preds provide undef, just nuke the xor, because it is undef too.
1306       BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1307       BO->eraseFromParent();
1308     } else if (SplitVal->isZero()) {
1309       // If all preds provide 0, replace the xor with the other input.
1310       BO->replaceAllUsesWith(BO->getOperand(isLHS));
1311       BO->eraseFromParent();
1312     } else {
1313       // If all preds provide 1, set the computed value to 1.
1314       BO->setOperand(!isLHS, SplitVal);
1315     }
1316
1317     return true;
1318   }
1319
1320   // Try to duplicate BB into PredBB.
1321   return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1322 }
1323
1324
1325 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1326 /// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
1327 /// NewPred using the entries from OldPred (suitably mapped).
1328 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1329                                             BasicBlock *OldPred,
1330                                             BasicBlock *NewPred,
1331                                      DenseMap<Instruction*, Value*> &ValueMap) {
1332   for (BasicBlock::iterator PNI = PHIBB->begin();
1333        PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1334     // Ok, we have a PHI node.  Figure out what the incoming value was for the
1335     // DestBlock.
1336     Value *IV = PN->getIncomingValueForBlock(OldPred);
1337
1338     // Remap the value if necessary.
1339     if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1340       DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1341       if (I != ValueMap.end())
1342         IV = I->second;
1343     }
1344
1345     PN->addIncoming(IV, NewPred);
1346   }
1347 }
1348
1349 /// ThreadEdge - We have decided that it is safe and profitable to factor the
1350 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
1351 /// across BB.  Transform the IR to reflect this change.
1352 bool JumpThreading::ThreadEdge(BasicBlock *BB,
1353                                const SmallVectorImpl<BasicBlock*> &PredBBs,
1354                                BasicBlock *SuccBB) {
1355   // If threading to the same block as we come from, we would infinite loop.
1356   if (SuccBB == BB) {
1357     DEBUG(dbgs() << "  Not threading across BB '" << BB->getName()
1358           << "' - would thread to self!\n");
1359     return false;
1360   }
1361
1362   // If threading this would thread across a loop header, don't thread the edge.
1363   // See the comments above FindLoopHeaders for justifications and caveats.
1364   if (LoopHeaders.count(BB)) {
1365     DEBUG(dbgs() << "  Not threading across loop header BB '" << BB->getName()
1366           << "' to dest BB '" << SuccBB->getName()
1367           << "' - it might create an irreducible loop!\n");
1368     return false;
1369   }
1370
1371   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB, Threshold);
1372   if (JumpThreadCost > Threshold) {
1373     DEBUG(dbgs() << "  Not threading BB '" << BB->getName()
1374           << "' - Cost is too high: " << JumpThreadCost << "\n");
1375     return false;
1376   }
1377
1378   // And finally, do it!  Start by factoring the predecessors is needed.
1379   BasicBlock *PredBB;
1380   if (PredBBs.size() == 1)
1381     PredBB = PredBBs[0];
1382   else {
1383     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
1384           << " common predecessors.\n");
1385     PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
1386   }
1387
1388   // And finally, do it!
1389   DEBUG(dbgs() << "  Threading edge from '" << PredBB->getName() << "' to '"
1390         << SuccBB->getName() << "' with cost: " << JumpThreadCost
1391         << ", across block:\n    "
1392         << *BB << "\n");
1393
1394   LVI->threadEdge(PredBB, BB, SuccBB);
1395
1396   // We are going to have to map operands from the original BB block to the new
1397   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
1398   // account for entry from PredBB.
1399   DenseMap<Instruction*, Value*> ValueMapping;
1400
1401   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
1402                                          BB->getName()+".thread",
1403                                          BB->getParent(), BB);
1404   NewBB->moveAfter(PredBB);
1405
1406   BasicBlock::iterator BI = BB->begin();
1407   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1408     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1409
1410   // Clone the non-phi instructions of BB into NewBB, keeping track of the
1411   // mapping and using it to remap operands in the cloned instructions.
1412   for (; !isa<TerminatorInst>(BI); ++BI) {
1413     Instruction *New = BI->clone();
1414     New->setName(BI->getName());
1415     NewBB->getInstList().push_back(New);
1416     ValueMapping[BI] = New;
1417
1418     // Remap operands to patch up intra-block references.
1419     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1420       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1421         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1422         if (I != ValueMapping.end())
1423           New->setOperand(i, I->second);
1424       }
1425   }
1426
1427   // We didn't copy the terminator from BB over to NewBB, because there is now
1428   // an unconditional jump to SuccBB.  Insert the unconditional jump.
1429   BranchInst *NewBI =BranchInst::Create(SuccBB, NewBB);
1430   NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
1431
1432   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1433   // PHI nodes for NewBB now.
1434   AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
1435
1436   // If there were values defined in BB that are used outside the block, then we
1437   // now have to update all uses of the value to use either the original value,
1438   // the cloned value, or some PHI derived value.  This can require arbitrary
1439   // PHI insertion, of which we are prepared to do, clean these up now.
1440   SSAUpdater SSAUpdate;
1441   SmallVector<Use*, 16> UsesToRename;
1442   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1443     // Scan all uses of this instruction to see if it is used outside of its
1444     // block, and if so, record them in UsesToRename.
1445     for (Use &U : I->uses()) {
1446       Instruction *User = cast<Instruction>(U.getUser());
1447       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1448         if (UserPN->getIncomingBlock(U) == BB)
1449           continue;
1450       } else if (User->getParent() == BB)
1451         continue;
1452
1453       UsesToRename.push_back(&U);
1454     }
1455
1456     // If there are no uses outside the block, we're done with this instruction.
1457     if (UsesToRename.empty())
1458       continue;
1459
1460     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
1461
1462     // We found a use of I outside of BB.  Rename all uses of I that are outside
1463     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1464     // with the two values we know.
1465     SSAUpdate.Initialize(I->getType(), I->getName());
1466     SSAUpdate.AddAvailableValue(BB, I);
1467     SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1468
1469     while (!UsesToRename.empty())
1470       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1471     DEBUG(dbgs() << "\n");
1472   }
1473
1474
1475   // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
1476   // NewBB instead of BB.  This eliminates predecessors from BB, which requires
1477   // us to simplify any PHI nodes in BB.
1478   TerminatorInst *PredTerm = PredBB->getTerminator();
1479   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1480     if (PredTerm->getSuccessor(i) == BB) {
1481       BB->removePredecessor(PredBB, true);
1482       PredTerm->setSuccessor(i, NewBB);
1483     }
1484
1485   // At this point, the IR is fully up to date and consistent.  Do a quick scan
1486   // over the new instructions and zap any that are constants or dead.  This
1487   // frequently happens because of phi translation.
1488   SimplifyInstructionsInBlock(NewBB, DL, TLI);
1489
1490   // Threaded an edge!
1491   ++NumThreads;
1492   return true;
1493 }
1494
1495 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1496 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1497 /// If we can duplicate the contents of BB up into PredBB do so now, this
1498 /// improves the odds that the branch will be on an analyzable instruction like
1499 /// a compare.
1500 bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1501                                  const SmallVectorImpl<BasicBlock *> &PredBBs) {
1502   assert(!PredBBs.empty() && "Can't handle an empty set");
1503
1504   // If BB is a loop header, then duplicating this block outside the loop would
1505   // cause us to transform this into an irreducible loop, don't do this.
1506   // See the comments above FindLoopHeaders for justifications and caveats.
1507   if (LoopHeaders.count(BB)) {
1508     DEBUG(dbgs() << "  Not duplicating loop header '" << BB->getName()
1509           << "' into predecessor block '" << PredBBs[0]->getName()
1510           << "' - it might create an irreducible loop!\n");
1511     return false;
1512   }
1513
1514   unsigned DuplicationCost = getJumpThreadDuplicationCost(BB, Threshold);
1515   if (DuplicationCost > Threshold) {
1516     DEBUG(dbgs() << "  Not duplicating BB '" << BB->getName()
1517           << "' - Cost is too high: " << DuplicationCost << "\n");
1518     return false;
1519   }
1520
1521   // And finally, do it!  Start by factoring the predecessors is needed.
1522   BasicBlock *PredBB;
1523   if (PredBBs.size() == 1)
1524     PredBB = PredBBs[0];
1525   else {
1526     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
1527           << " common predecessors.\n");
1528     PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
1529   }
1530
1531   // Okay, we decided to do this!  Clone all the instructions in BB onto the end
1532   // of PredBB.
1533   DEBUG(dbgs() << "  Duplicating block '" << BB->getName() << "' into end of '"
1534         << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
1535         << DuplicationCost << " block is:" << *BB << "\n");
1536
1537   // Unless PredBB ends with an unconditional branch, split the edge so that we
1538   // can just clone the bits from BB into the end of the new PredBB.
1539   BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
1540
1541   if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
1542     PredBB = SplitEdge(PredBB, BB, this);
1543     OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1544   }
1545
1546   // We are going to have to map operands from the original BB block into the
1547   // PredBB block.  Evaluate PHI nodes in BB.
1548   DenseMap<Instruction*, Value*> ValueMapping;
1549
1550   BasicBlock::iterator BI = BB->begin();
1551   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1552     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1553
1554   // Clone the non-phi instructions of BB into PredBB, keeping track of the
1555   // mapping and using it to remap operands in the cloned instructions.
1556   for (; BI != BB->end(); ++BI) {
1557     Instruction *New = BI->clone();
1558
1559     // Remap operands to patch up intra-block references.
1560     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1561       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1562         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1563         if (I != ValueMapping.end())
1564           New->setOperand(i, I->second);
1565       }
1566
1567     // If this instruction can be simplified after the operands are updated,
1568     // just use the simplified value instead.  This frequently happens due to
1569     // phi translation.
1570     if (Value *IV = SimplifyInstruction(New, DL)) {
1571       delete New;
1572       ValueMapping[BI] = IV;
1573     } else {
1574       // Otherwise, insert the new instruction into the block.
1575       New->setName(BI->getName());
1576       PredBB->getInstList().insert(OldPredBranch, New);
1577       ValueMapping[BI] = New;
1578     }
1579   }
1580
1581   // Check to see if the targets of the branch had PHI nodes. If so, we need to
1582   // add entries to the PHI nodes for branch from PredBB now.
1583   BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1584   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1585                                   ValueMapping);
1586   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1587                                   ValueMapping);
1588
1589   // If there were values defined in BB that are used outside the block, then we
1590   // now have to update all uses of the value to use either the original value,
1591   // the cloned value, or some PHI derived value.  This can require arbitrary
1592   // PHI insertion, of which we are prepared to do, clean these up now.
1593   SSAUpdater SSAUpdate;
1594   SmallVector<Use*, 16> UsesToRename;
1595   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1596     // Scan all uses of this instruction to see if it is used outside of its
1597     // block, and if so, record them in UsesToRename.
1598     for (Use &U : I->uses()) {
1599       Instruction *User = cast<Instruction>(U.getUser());
1600       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1601         if (UserPN->getIncomingBlock(U) == BB)
1602           continue;
1603       } else if (User->getParent() == BB)
1604         continue;
1605
1606       UsesToRename.push_back(&U);
1607     }
1608
1609     // If there are no uses outside the block, we're done with this instruction.
1610     if (UsesToRename.empty())
1611       continue;
1612
1613     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
1614
1615     // We found a use of I outside of BB.  Rename all uses of I that are outside
1616     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1617     // with the two values we know.
1618     SSAUpdate.Initialize(I->getType(), I->getName());
1619     SSAUpdate.AddAvailableValue(BB, I);
1620     SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1621
1622     while (!UsesToRename.empty())
1623       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1624     DEBUG(dbgs() << "\n");
1625   }
1626
1627   // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1628   // that we nuked.
1629   BB->removePredecessor(PredBB, true);
1630
1631   // Remove the unconditional branch at the end of the PredBB block.
1632   OldPredBranch->eraseFromParent();
1633
1634   ++NumDupes;
1635   return true;
1636 }
1637
1638 /// TryToUnfoldSelect - Look for blocks of the form
1639 /// bb1:
1640 ///   %a = select
1641 ///   br bb
1642 ///
1643 /// bb2:
1644 ///   %p = phi [%a, %bb] ...
1645 ///   %c = icmp %p
1646 ///   br i1 %c
1647 ///
1648 /// And expand the select into a branch structure if one of its arms allows %c
1649 /// to be folded. This later enables threading from bb1 over bb2.
1650 bool JumpThreading::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
1651   BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
1652   PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
1653   Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
1654
1655   if (!CondBr || !CondBr->isConditional() || !CondLHS ||
1656       CondLHS->getParent() != BB)
1657     return false;
1658
1659   for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
1660     BasicBlock *Pred = CondLHS->getIncomingBlock(I);
1661     SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
1662
1663     // Look if one of the incoming values is a select in the corresponding
1664     // predecessor.
1665     if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
1666       continue;
1667
1668     BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
1669     if (!PredTerm || !PredTerm->isUnconditional())
1670       continue;
1671
1672     // Now check if one of the select values would allow us to constant fold the
1673     // terminator in BB. We don't do the transform if both sides fold, those
1674     // cases will be threaded in any case.
1675     LazyValueInfo::Tristate LHSFolds =
1676         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
1677                                 CondRHS, Pred, BB);
1678     LazyValueInfo::Tristate RHSFolds =
1679         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
1680                                 CondRHS, Pred, BB);
1681     if ((LHSFolds != LazyValueInfo::Unknown ||
1682          RHSFolds != LazyValueInfo::Unknown) &&
1683         LHSFolds != RHSFolds) {
1684       // Expand the select.
1685       //
1686       // Pred --
1687       //  |    v
1688       //  |  NewBB
1689       //  |    |
1690       //  |-----
1691       //  v
1692       // BB
1693       BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
1694                                              BB->getParent(), BB);
1695       // Move the unconditional branch to NewBB.
1696       PredTerm->removeFromParent();
1697       NewBB->getInstList().insert(NewBB->end(), PredTerm);
1698       // Create a conditional branch and update PHI nodes.
1699       BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
1700       CondLHS->setIncomingValue(I, SI->getFalseValue());
1701       CondLHS->addIncoming(SI->getTrueValue(), NewBB);
1702       // The select is now dead.
1703       SI->eraseFromParent();
1704
1705       // Update any other PHI nodes in BB.
1706       for (BasicBlock::iterator BI = BB->begin();
1707            PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
1708         if (Phi != CondLHS)
1709           Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
1710       return true;
1711     }
1712   }
1713   return false;
1714 }