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