Fix a bug where we'd call SplitBlockPredecessors with a pred in the
[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 #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/ConstantFolding.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "llvm/Transforms/Utils/SSAUpdater.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
33
34 STATISTIC(NumThreads, "Number of jumps threaded");
35 STATISTIC(NumFolds,   "Number of terminators folded");
36 STATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
37
38 static cl::opt<unsigned>
39 Threshold("jump-threading-threshold", 
40           cl::desc("Max block size to duplicate for jump threading"),
41           cl::init(6), cl::Hidden);
42
43 namespace {
44   /// This pass performs 'jump threading', which looks at blocks that have
45   /// multiple predecessors and multiple successors.  If one or more of the
46   /// predecessors of the block can be proven to always jump to one of the
47   /// successors, we forward the edge from the predecessor to the successor by
48   /// duplicating the contents of this block.
49   ///
50   /// An example of when this can occur is code like this:
51   ///
52   ///   if () { ...
53   ///     X = 4;
54   ///   }
55   ///   if (X < 3) {
56   ///
57   /// In this case, the unconditional branch at the end of the first if can be
58   /// revectored to the false side of the second if.
59   ///
60   class JumpThreading : public FunctionPass {
61     TargetData *TD;
62 #ifdef NDEBUG
63     SmallPtrSet<BasicBlock*, 16> LoopHeaders;
64 #else
65     SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
66 #endif
67   public:
68     static char ID; // Pass identification
69     JumpThreading() : FunctionPass(&ID) {}
70
71     bool runOnFunction(Function &F);
72     void FindLoopHeaders(Function &F);
73     
74     bool ProcessBlock(BasicBlock *BB);
75     bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
76     bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
77                                           BasicBlock *PredBB);
78     
79     typedef SmallVectorImpl<std::pair<ConstantInt*,
80                                       BasicBlock*> > PredValueInfo;
81     
82     bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
83                                          PredValueInfo &Result);
84     bool ProcessThreadableEdges(Instruction *CondInst, BasicBlock *BB);
85     
86     
87     bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
88     bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
89
90     bool ProcessJumpOnPHI(PHINode *PN);
91     
92     bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
93   };
94 }
95
96 char JumpThreading::ID = 0;
97 static RegisterPass<JumpThreading>
98 X("jump-threading", "Jump Threading");
99
100 // Public interface to the Jump Threading pass
101 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
102
103 /// runOnFunction - Top level algorithm.
104 ///
105 bool JumpThreading::runOnFunction(Function &F) {
106   DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
107   TD = getAnalysisIfAvailable<TargetData>();
108   
109   FindLoopHeaders(F);
110   
111   bool AnotherIteration = true, EverChanged = false;
112   while (AnotherIteration) {
113     AnotherIteration = false;
114     bool Changed = false;
115     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
116       BasicBlock *BB = I;
117       while (ProcessBlock(BB))
118         Changed = true;
119       
120       ++I;
121       
122       // If the block is trivially dead, zap it.  This eliminates the successor
123       // edges which simplifies the CFG.
124       if (pred_begin(BB) == pred_end(BB) &&
125           BB != &BB->getParent()->getEntryBlock()) {
126         DEBUG(errs() << "  JT: Deleting dead block '" << BB->getName()
127               << "' with terminator: " << *BB->getTerminator() << '\n');
128         LoopHeaders.erase(BB);
129         DeleteDeadBlock(BB);
130         Changed = true;
131       }
132     }
133     AnotherIteration = Changed;
134     EverChanged |= Changed;
135   }
136   
137   LoopHeaders.clear();
138   return EverChanged;
139 }
140
141 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
142 /// thread across it.
143 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
144   /// Ignore PHI nodes, these will be flattened when duplication happens.
145   BasicBlock::const_iterator I = BB->getFirstNonPHI();
146   
147   // Sum up the cost of each instruction until we get to the terminator.  Don't
148   // include the terminator because the copy won't include it.
149   unsigned Size = 0;
150   for (; !isa<TerminatorInst>(I); ++I) {
151     // Debugger intrinsics don't incur code size.
152     if (isa<DbgInfoIntrinsic>(I)) continue;
153     
154     // If this is a pointer->pointer bitcast, it is free.
155     if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
156       continue;
157     
158     // All other instructions count for at least one unit.
159     ++Size;
160     
161     // Calls are more expensive.  If they are non-intrinsic calls, we model them
162     // as having cost of 4.  If they are a non-vector intrinsic, we model them
163     // as having cost of 2 total, and if they are a vector intrinsic, we model
164     // them as having cost 1.
165     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
166       if (!isa<IntrinsicInst>(CI))
167         Size += 3;
168       else if (!isa<VectorType>(CI->getType()))
169         Size += 1;
170     }
171   }
172   
173   // Threading through a switch statement is particularly profitable.  If this
174   // block ends in a switch, decrease its cost to make it more likely to happen.
175   if (isa<SwitchInst>(I))
176     Size = Size > 6 ? Size-6 : 0;
177   
178   return Size;
179 }
180
181
182
183 /// FindLoopHeaders - We do not want jump threading to turn proper loop
184 /// structures into irreducible loops.  Doing this breaks up the loop nesting
185 /// hierarchy and pessimizes later transformations.  To prevent this from
186 /// happening, we first have to find the loop headers.  Here we approximate this
187 /// by finding targets of backedges in the CFG.
188 ///
189 /// Note that there definitely are cases when we want to allow threading of
190 /// edges across a loop header.  For example, threading a jump from outside the
191 /// loop (the preheader) to an exit block of the loop is definitely profitable.
192 /// It is also almost always profitable to thread backedges from within the loop
193 /// to exit blocks, and is often profitable to thread backedges to other blocks
194 /// within the loop (forming a nested loop).  This simple analysis is not rich
195 /// enough to track all of these properties and keep it up-to-date as the CFG
196 /// mutates, so we don't allow any of these transformations.
197 ///
198 void JumpThreading::FindLoopHeaders(Function &F) {
199   SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
200   FindFunctionBackedges(F, Edges);
201   
202   for (unsigned i = 0, e = Edges.size(); i != e; ++i)
203     LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
204 }
205
206 /// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
207 /// hand sides of the compare instruction, try to determine the result. If the
208 /// result can not be determined, a null pointer is returned.
209 static Constant *GetResultOfComparison(CmpInst::Predicate pred,
210                                        Value *LHS, Value *RHS) {
211   if (Constant *CLHS = dyn_cast<Constant>(LHS))
212     if (Constant *CRHS = dyn_cast<Constant>(RHS))
213       return ConstantExpr::getCompare(pred, CLHS, CRHS);
214   
215   if (LHS == RHS)
216     if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType()))
217       if (ICmpInst::isTrueWhenEqual(pred))
218         return ConstantInt::getTrue(LHS->getContext());
219       else
220         return ConstantInt::getFalse(LHS->getContext());
221   return 0;
222 }
223
224
225 /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
226 /// if we can infer that the value is a known ConstantInt in any of our
227 /// predecessors.  If so, return the known the list of value and pred BB in the
228 /// result vector.  If a value is known to be undef, it is returned as null.
229 ///
230 /// The BB basic block is known to start with a PHI node.
231 ///
232 /// This returns true if there were any known values.
233 ///
234 ///
235 /// TODO: Per PR2563, we could infer value range information about a predecessor
236 /// based on its terminator.
237 bool JumpThreading::
238 ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
239   PHINode *TheFirstPHI = cast<PHINode>(BB->begin());
240   
241   // If V is a constantint, then it is known in all predecessors.
242   if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
243     ConstantInt *CI = dyn_cast<ConstantInt>(V);
244     Result.resize(TheFirstPHI->getNumIncomingValues());
245     for (unsigned i = 0, e = Result.size(); i != e; ++i)
246       Result[i] = std::make_pair(CI, TheFirstPHI->getIncomingBlock(i));
247     return true;
248   }
249   
250   // If V is a non-instruction value, or an instruction in a different block,
251   // then it can't be derived from a PHI.
252   Instruction *I = dyn_cast<Instruction>(V);
253   if (I == 0 || I->getParent() != BB)
254     return false;
255   
256   /// If I is a PHI node, then we know the incoming values for any constants.
257   if (PHINode *PN = dyn_cast<PHINode>(I)) {
258     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
259       Value *InVal = PN->getIncomingValue(i);
260       if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
261         ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
262         Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
263       }
264     }
265     return !Result.empty();
266   }
267   
268   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
269
270   // Handle some boolean conditions.
271   if (I->getType()->getPrimitiveSizeInBits() == 1) { 
272     // X | true -> true
273     // X & false -> false
274     if (I->getOpcode() == Instruction::Or ||
275         I->getOpcode() == Instruction::And) {
276       ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
277       ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
278       
279       if (LHSVals.empty() && RHSVals.empty())
280         return false;
281       
282       ConstantInt *InterestingVal;
283       if (I->getOpcode() == Instruction::Or)
284         InterestingVal = ConstantInt::getTrue(I->getContext());
285       else
286         InterestingVal = ConstantInt::getFalse(I->getContext());
287       
288       // Scan for the sentinel.
289       for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
290         if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0)
291           Result.push_back(LHSVals[i]);
292       for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
293         if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0)
294           Result.push_back(RHSVals[i]);
295       return !Result.empty();
296     }
297     
298     // TODO: Should handle the NOT form of XOR.
299     
300   }
301   
302   // Handle compare with phi operand, where the PHI is defined in this block.
303   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
304     PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
305     if (PN && PN->getParent() == BB) {
306       // We can do this simplification if any comparisons fold to true or false.
307       // See if any do.
308       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
309         BasicBlock *PredBB = PN->getIncomingBlock(i);
310         Value *LHS = PN->getIncomingValue(i);
311         Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
312         
313         Constant *Res = GetResultOfComparison(Cmp->getPredicate(), LHS, RHS);
314         if (Res == 0) continue;
315         
316         if (isa<UndefValue>(Res))
317           Result.push_back(std::make_pair((ConstantInt*)0, PredBB));
318         else if (ConstantInt *CI = dyn_cast<ConstantInt>(Res))
319           Result.push_back(std::make_pair(CI, PredBB));
320       }
321       
322       return !Result.empty();
323     }
324     
325     // TODO: We could also recurse to see if we can determine constants another
326     // way.
327   }
328   return false;
329 }
330
331
332
333 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
334 /// in an undefined jump, decide which block is best to revector to.
335 ///
336 /// Since we can pick an arbitrary destination, we pick the successor with the
337 /// fewest predecessors.  This should reduce the in-degree of the others.
338 ///
339 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
340   TerminatorInst *BBTerm = BB->getTerminator();
341   unsigned MinSucc = 0;
342   BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
343   // Compute the successor with the minimum number of predecessors.
344   unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
345   for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
346     TestBB = BBTerm->getSuccessor(i);
347     unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
348     if (NumPreds < MinNumPreds)
349       MinSucc = i;
350   }
351   
352   return MinSucc;
353 }
354
355 /// ProcessBlock - If there are any predecessors whose control can be threaded
356 /// through to a successor, transform them now.
357 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
358   // If this block has a single predecessor, and if that pred has a single
359   // successor, merge the blocks.  This encourages recursive jump threading
360   // because now the condition in this block can be threaded through
361   // predecessors of our predecessor block.
362   if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
363     if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
364         SinglePred != BB) {
365       // If SinglePred was a loop header, BB becomes one.
366       if (LoopHeaders.erase(SinglePred))
367         LoopHeaders.insert(BB);
368       
369       // Remember if SinglePred was the entry block of the function.  If so, we
370       // will need to move BB back to the entry position.
371       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
372       MergeBasicBlockIntoOnlyPred(BB);
373       
374       if (isEntry && BB != &BB->getParent()->getEntryBlock())
375         BB->moveBefore(&BB->getParent()->getEntryBlock());
376       return true;
377     }
378   }
379
380   // Look to see if the terminator is a branch of switch, if not we can't thread
381   // it.
382   Value *Condition;
383   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
384     // Can't thread an unconditional jump.
385     if (BI->isUnconditional()) return false;
386     Condition = BI->getCondition();
387   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
388     Condition = SI->getCondition();
389   else
390     return false; // Must be an invoke.
391   
392   // If the terminator of this block is branching on a constant, simplify the
393   // terminator to an unconditional branch.  This can occur due to threading in
394   // other blocks.
395   if (isa<ConstantInt>(Condition)) {
396     DEBUG(errs() << "  In block '" << BB->getName()
397           << "' folding terminator: " << *BB->getTerminator() << '\n');
398     ++NumFolds;
399     ConstantFoldTerminator(BB);
400     return true;
401   }
402   
403   // If the terminator is branching on an undef, we can pick any of the
404   // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
405   if (isa<UndefValue>(Condition)) {
406     unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
407     
408     // Fold the branch/switch.
409     TerminatorInst *BBTerm = BB->getTerminator();
410     for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
411       if (i == BestSucc) continue;
412       BBTerm->getSuccessor(i)->removePredecessor(BB);
413     }
414     
415     DEBUG(errs() << "  In block '" << BB->getName()
416           << "' folding undef terminator: " << *BBTerm << '\n');
417     BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
418     BBTerm->eraseFromParent();
419     return true;
420   }
421   
422   Instruction *CondInst = dyn_cast<Instruction>(Condition);
423
424   // If the condition is an instruction defined in another block, see if a
425   // predecessor has the same condition:
426   //     br COND, BBX, BBY
427   //  BBX:
428   //     br COND, BBZ, BBW
429   if (!Condition->hasOneUse() && // Multiple uses.
430       (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
431     pred_iterator PI = pred_begin(BB), E = pred_end(BB);
432     if (isa<BranchInst>(BB->getTerminator())) {
433       for (; PI != E; ++PI)
434         if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
435           if (PBI->isConditional() && PBI->getCondition() == Condition &&
436               ProcessBranchOnDuplicateCond(*PI, BB))
437             return true;
438     } else {
439       assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
440       for (; PI != E; ++PI)
441         if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
442           if (PSI->getCondition() == Condition &&
443               ProcessSwitchOnDuplicateCond(*PI, BB))
444             return true;
445     }
446   }
447
448   // All the rest of our checks depend on the condition being an instruction.
449   if (CondInst == 0)
450     return false;
451   
452   // See if this is a phi node in the current block.
453   if (PHINode *PN = dyn_cast<PHINode>(CondInst))
454     if (PN->getParent() == BB)
455       return ProcessJumpOnPHI(PN);
456   
457   if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
458     if (!isa<PHINode>(CondCmp->getOperand(0)) ||
459         cast<PHINode>(CondCmp->getOperand(0))->getParent() != BB) {
460       // If we have a comparison, loop over the predecessors to see if there is
461       // a condition with a lexically identical value.
462       pred_iterator PI = pred_begin(BB), E = pred_end(BB);
463       for (; PI != E; ++PI)
464         if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
465           if (PBI->isConditional() && *PI != BB) {
466             if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
467               if (CI->getOperand(0) == CondCmp->getOperand(0) &&
468                   CI->getOperand(1) == CondCmp->getOperand(1) &&
469                   CI->getPredicate() == CondCmp->getPredicate()) {
470                 // TODO: Could handle things like (x != 4) --> (x == 17)
471                 if (ProcessBranchOnDuplicateCond(*PI, BB))
472                   return true;
473               }
474             }
475           }
476     }
477   }
478
479   // Check for some cases that are worth simplifying.  Right now we want to look
480   // for loads that are used by a switch or by the condition for the branch.  If
481   // we see one, check to see if it's partially redundant.  If so, insert a PHI
482   // which can then be used to thread the values.
483   //
484   // This is particularly important because reg2mem inserts loads and stores all
485   // over the place, and this blocks jump threading if we don't zap them.
486   Value *SimplifyValue = CondInst;
487   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
488     if (isa<Constant>(CondCmp->getOperand(1)))
489       SimplifyValue = CondCmp->getOperand(0);
490   
491   if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
492     if (SimplifyPartiallyRedundantLoad(LI))
493       return true;
494   
495   
496   // Handle a variety of cases where we are branching on something derived from
497   // a PHI node in the current block.  If we can prove that any predecessors
498   // compute a predictable value based on a PHI node, thread those predecessors.
499   //
500   // We only bother doing this if the current block has a PHI node and if the
501   // conditional instruction lives in the current block.  If either condition
502   // fail, this won't be a computable value anyway.
503   if (CondInst->getParent() == BB && isa<PHINode>(BB->front()))
504     if (ProcessThreadableEdges(CondInst, BB))
505       return true;
506   
507   
508   // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
509   // "(X == 4)" thread through this block.
510   
511   return false;
512 }
513
514 /// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
515 /// block that jump on exactly the same condition.  This means that we almost
516 /// always know the direction of the edge in the DESTBB:
517 ///  PREDBB:
518 ///     br COND, DESTBB, BBY
519 ///  DESTBB:
520 ///     br COND, BBZ, BBW
521 ///
522 /// If DESTBB has multiple predecessors, we can't just constant fold the branch
523 /// in DESTBB, we have to thread over it.
524 bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
525                                                  BasicBlock *BB) {
526   BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
527   
528   // If both successors of PredBB go to DESTBB, we don't know anything.  We can
529   // fold the branch to an unconditional one, which allows other recursive
530   // simplifications.
531   bool BranchDir;
532   if (PredBI->getSuccessor(1) != BB)
533     BranchDir = true;
534   else if (PredBI->getSuccessor(0) != BB)
535     BranchDir = false;
536   else {
537     DEBUG(errs() << "  In block '" << PredBB->getName()
538           << "' folding terminator: " << *PredBB->getTerminator() << '\n');
539     ++NumFolds;
540     ConstantFoldTerminator(PredBB);
541     return true;
542   }
543    
544   BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
545
546   // If the dest block has one predecessor, just fix the branch condition to a
547   // constant and fold it.
548   if (BB->getSinglePredecessor()) {
549     DEBUG(errs() << "  In block '" << BB->getName()
550           << "' folding condition to '" << BranchDir << "': "
551           << *BB->getTerminator() << '\n');
552     ++NumFolds;
553     Value *OldCond = DestBI->getCondition();
554     DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
555                                           BranchDir));
556     ConstantFoldTerminator(BB);
557     RecursivelyDeleteTriviallyDeadInstructions(OldCond);
558     return true;
559   }
560  
561   
562   // Next, figure out which successor we are threading to.
563   BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
564   
565   // Ok, try to thread it!
566   return ThreadEdge(BB, PredBB, SuccBB);
567 }
568
569 /// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
570 /// block that switch on exactly the same condition.  This means that we almost
571 /// always know the direction of the edge in the DESTBB:
572 ///  PREDBB:
573 ///     switch COND [... DESTBB, BBY ... ]
574 ///  DESTBB:
575 ///     switch COND [... BBZ, BBW ]
576 ///
577 /// Optimizing switches like this is very important, because simplifycfg builds
578 /// switches out of repeated 'if' conditions.
579 bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
580                                                  BasicBlock *DestBB) {
581   // Can't thread edge to self.
582   if (PredBB == DestBB)
583     return false;
584   
585   SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
586   SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
587
588   // There are a variety of optimizations that we can potentially do on these
589   // blocks: we order them from most to least preferable.
590   
591   // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
592   // directly to their destination.  This does not introduce *any* code size
593   // growth.  Skip debug info first.
594   BasicBlock::iterator BBI = DestBB->begin();
595   while (isa<DbgInfoIntrinsic>(BBI))
596     BBI++;
597   
598   // FIXME: Thread if it just contains a PHI.
599   if (isa<SwitchInst>(BBI)) {
600     bool MadeChange = false;
601     // Ignore the default edge for now.
602     for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
603       ConstantInt *DestVal = DestSI->getCaseValue(i);
604       BasicBlock *DestSucc = DestSI->getSuccessor(i);
605       
606       // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'.  See if
607       // PredSI has an explicit case for it.  If so, forward.  If it is covered
608       // by the default case, we can't update PredSI.
609       unsigned PredCase = PredSI->findCaseValue(DestVal);
610       if (PredCase == 0) continue;
611       
612       // If PredSI doesn't go to DestBB on this value, then it won't reach the
613       // case on this condition.
614       if (PredSI->getSuccessor(PredCase) != DestBB &&
615           DestSI->getSuccessor(i) != DestBB)
616         continue;
617
618       // Otherwise, we're safe to make the change.  Make sure that the edge from
619       // DestSI to DestSucc is not critical and has no PHI nodes.
620       DEBUG(errs() << "FORWARDING EDGE " << *DestVal << "   FROM: " << *PredSI);
621       DEBUG(errs() << "THROUGH: " << *DestSI);
622
623       // If the destination has PHI nodes, just split the edge for updating
624       // simplicity.
625       if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
626         SplitCriticalEdge(DestSI, i, this);
627         DestSucc = DestSI->getSuccessor(i);
628       }
629       FoldSingleEntryPHINodes(DestSucc);
630       PredSI->setSuccessor(PredCase, DestSucc);
631       MadeChange = true;
632     }
633     
634     if (MadeChange)
635       return true;
636   }
637   
638   return false;
639 }
640
641
642 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
643 /// load instruction, eliminate it by replacing it with a PHI node.  This is an
644 /// important optimization that encourages jump threading, and needs to be run
645 /// interlaced with other jump threading tasks.
646 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
647   // Don't hack volatile loads.
648   if (LI->isVolatile()) return false;
649   
650   // If the load is defined in a block with exactly one predecessor, it can't be
651   // partially redundant.
652   BasicBlock *LoadBB = LI->getParent();
653   if (LoadBB->getSinglePredecessor())
654     return false;
655   
656   Value *LoadedPtr = LI->getOperand(0);
657
658   // If the loaded operand is defined in the LoadBB, it can't be available.
659   // FIXME: Could do PHI translation, that would be fun :)
660   if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
661     if (PtrOp->getParent() == LoadBB)
662       return false;
663   
664   // Scan a few instructions up from the load, to see if it is obviously live at
665   // the entry to its block.
666   BasicBlock::iterator BBIt = LI;
667
668   if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB, 
669                                                      BBIt, 6)) {
670     // If the value if the load is locally available within the block, just use
671     // it.  This frequently occurs for reg2mem'd allocas.
672     //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
673     
674     // If the returned value is the load itself, replace with an undef. This can
675     // only happen in dead loops.
676     if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
677     LI->replaceAllUsesWith(AvailableVal);
678     LI->eraseFromParent();
679     return true;
680   }
681
682   // Otherwise, if we scanned the whole block and got to the top of the block,
683   // we know the block is locally transparent to the load.  If not, something
684   // might clobber its value.
685   if (BBIt != LoadBB->begin())
686     return false;
687   
688   
689   SmallPtrSet<BasicBlock*, 8> PredsScanned;
690   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
691   AvailablePredsTy AvailablePreds;
692   BasicBlock *OneUnavailablePred = 0;
693   
694   // If we got here, the loaded value is transparent through to the start of the
695   // block.  Check to see if it is available in any of the predecessor blocks.
696   for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
697        PI != PE; ++PI) {
698     BasicBlock *PredBB = *PI;
699
700     // If we already scanned this predecessor, skip it.
701     if (!PredsScanned.insert(PredBB))
702       continue;
703
704     // Scan the predecessor to see if the value is available in the pred.
705     BBIt = PredBB->end();
706     Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
707     if (!PredAvailable) {
708       OneUnavailablePred = PredBB;
709       continue;
710     }
711     
712     // If so, this load is partially redundant.  Remember this info so that we
713     // can create a PHI node.
714     AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
715   }
716   
717   // If the loaded value isn't available in any predecessor, it isn't partially
718   // redundant.
719   if (AvailablePreds.empty()) return false;
720   
721   // Okay, the loaded value is available in at least one (and maybe all!)
722   // predecessors.  If the value is unavailable in more than one unique
723   // predecessor, we want to insert a merge block for those common predecessors.
724   // This ensures that we only have to insert one reload, thus not increasing
725   // code size.
726   BasicBlock *UnavailablePred = 0;
727   
728   // If there is exactly one predecessor where the value is unavailable, the
729   // already computed 'OneUnavailablePred' block is it.  If it ends in an
730   // unconditional branch, we know that it isn't a critical edge.
731   if (PredsScanned.size() == AvailablePreds.size()+1 &&
732       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
733     UnavailablePred = OneUnavailablePred;
734   } else if (PredsScanned.size() != AvailablePreds.size()) {
735     // Otherwise, we had multiple unavailable predecessors or we had a critical
736     // edge from the one.
737     SmallVector<BasicBlock*, 8> PredsToSplit;
738     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
739
740     for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
741       AvailablePredSet.insert(AvailablePreds[i].first);
742
743     // Add all the unavailable predecessors to the PredsToSplit list.
744     for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
745          PI != PE; ++PI)
746       if (!AvailablePredSet.count(*PI))
747         PredsToSplit.push_back(*PI);
748     
749     // Split them out to their own block.
750     UnavailablePred =
751       SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
752                              "thread-split", this);
753   }
754   
755   // If the value isn't available in all predecessors, then there will be
756   // exactly one where it isn't available.  Insert a load on that edge and add
757   // it to the AvailablePreds list.
758   if (UnavailablePred) {
759     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
760            "Can't handle critical edge here!");
761     Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
762                                  UnavailablePred->getTerminator());
763     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
764   }
765   
766   // Now we know that each predecessor of this block has a value in
767   // AvailablePreds, sort them for efficient access as we're walking the preds.
768   array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
769   
770   // Create a PHI node at the start of the block for the PRE'd load value.
771   PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
772   PN->takeName(LI);
773   
774   // Insert new entries into the PHI for each predecessor.  A single block may
775   // have multiple entries here.
776   for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
777        ++PI) {
778     AvailablePredsTy::iterator I = 
779       std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
780                        std::make_pair(*PI, (Value*)0));
781     
782     assert(I != AvailablePreds.end() && I->first == *PI &&
783            "Didn't find entry for predecessor!");
784     
785     PN->addIncoming(I->second, I->first);
786   }
787   
788   //cerr << "PRE: " << *LI << *PN << "\n";
789   
790   LI->replaceAllUsesWith(PN);
791   LI->eraseFromParent();
792   
793   return true;
794 }
795
796 /// FindMostPopularDest - The specified list contains multiple possible
797 /// threadable destinations.  Pick the one that occurs the most frequently in
798 /// the list.
799 static BasicBlock *
800 FindMostPopularDest(BasicBlock *BB,
801                     const SmallVectorImpl<std::pair<BasicBlock*,
802                                   BasicBlock*> > &PredToDestList) {
803   assert(!PredToDestList.empty());
804   
805   // Determine popularity.  If there are multiple possible destinations, we
806   // explicitly choose to ignore 'undef' destinations.  We prefer to thread
807   // blocks with known and real destinations to threading undef.  We'll handle
808   // them later if interesting.
809   DenseMap<BasicBlock*, unsigned> DestPopularity;
810   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
811     if (PredToDestList[i].second)
812       DestPopularity[PredToDestList[i].second]++;
813   
814   // Find the most popular dest.
815   DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
816   BasicBlock *MostPopularDest = DPI->first;
817   unsigned Popularity = DPI->second;
818   SmallVector<BasicBlock*, 4> SamePopularity;
819   
820   for (++DPI; DPI != DestPopularity.end(); ++DPI) {
821     // If the popularity of this entry isn't higher than the popularity we've
822     // seen so far, ignore it.
823     if (DPI->second < Popularity)
824       ; // ignore.
825     else if (DPI->second == Popularity) {
826       // If it is the same as what we've seen so far, keep track of it.
827       SamePopularity.push_back(DPI->first);
828     } else {
829       // If it is more popular, remember it.
830       SamePopularity.clear();
831       MostPopularDest = DPI->first;
832       Popularity = DPI->second;
833     }      
834   }
835   
836   // Okay, now we know the most popular destination.  If there is more than
837   // destination, we need to determine one.  This is arbitrary, but we need
838   // to make a deterministic decision.  Pick the first one that appears in the
839   // successor list.
840   if (!SamePopularity.empty()) {
841     SamePopularity.push_back(MostPopularDest);
842     TerminatorInst *TI = BB->getTerminator();
843     for (unsigned i = 0; ; ++i) {
844       assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
845       
846       if (std::find(SamePopularity.begin(), SamePopularity.end(),
847                     TI->getSuccessor(i)) == SamePopularity.end())
848         continue;
849       
850       MostPopularDest = TI->getSuccessor(i);
851       break;
852     }
853   }
854   
855   // Okay, we have finally picked the most popular destination.
856   return MostPopularDest;
857 }
858
859 bool JumpThreading::ProcessThreadableEdges(Instruction *CondInst,
860                                            BasicBlock *BB) {
861   // If threading this would thread across a loop header, don't even try to
862   // thread the edge.
863   if (LoopHeaders.count(BB))
864     return false;
865   
866   
867   
868   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
869   if (!ComputeValueKnownInPredecessors(CondInst, BB, PredValues))
870     return false;
871   assert(!PredValues.empty() &&
872          "ComputeValueKnownInPredecessors returned true with no values");
873
874   DEBUG(errs() << "IN BB: " << *BB;
875         for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
876           errs() << "  BB '" << BB->getName() << "': FOUND condition = ";
877           if (PredValues[i].first)
878             errs() << *PredValues[i].first;
879           else
880             errs() << "UNDEF";
881           errs() << " for pred '" << PredValues[i].second->getName()
882           << "'.\n";
883         });
884   
885   // Decide what we want to thread through.  Convert our list of known values to
886   // a list of known destinations for each pred.  This also discards duplicate
887   // predecessors and keeps track of the undefined inputs (which are represented
888   // as a null dest in the PredToDestList.
889   SmallPtrSet<BasicBlock*, 16> SeenPreds;
890   SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
891   
892   BasicBlock *OnlyDest = 0;
893   BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
894   
895   for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
896     BasicBlock *Pred = PredValues[i].second;
897     if (!SeenPreds.insert(Pred))
898       continue;  // Duplicate predecessor entry.
899     
900     // If the predecessor ends with an indirect goto, we can't change its
901     // destination.
902     if (isa<IndirectBrInst>(Pred->getTerminator()))
903       continue;
904     
905     ConstantInt *Val = PredValues[i].first;
906     
907     BasicBlock *DestBB;
908     if (Val == 0)      // Undef.
909       DestBB = 0;
910     else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
911       DestBB = BI->getSuccessor(Val->isZero());
912     else {
913       SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
914       DestBB = SI->getSuccessor(SI->findCaseValue(Val));
915     }
916
917     // If we have exactly one destination, remember it for efficiency below.
918     if (i == 0)
919       OnlyDest = DestBB;
920     else if (OnlyDest != DestBB)
921       OnlyDest = MultipleDestSentinel;
922     
923     PredToDestList.push_back(std::make_pair(Pred, DestBB));
924   }
925   
926   // If all edges were unthreadable, we fail.
927   if (PredToDestList.empty())
928     return false;
929   
930   // Determine which is the most common successor.  If we have many inputs and
931   // this block is a switch, we want to start by threading the batch that goes
932   // to the most popular destination first.  If we only know about one
933   // threadable destination (the common case) we can avoid this.
934   BasicBlock *MostPopularDest = OnlyDest;
935   
936   if (MostPopularDest == MultipleDestSentinel)
937     MostPopularDest = FindMostPopularDest(BB, PredToDestList);
938   
939   // Now that we know what the most popular destination is, factor all
940   // predecessors that will jump to it into a single predecessor.
941   SmallVector<BasicBlock*, 16> PredsToFactor;
942   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
943     if (PredToDestList[i].second == MostPopularDest) {
944       BasicBlock *Pred = PredToDestList[i].first;
945       
946       // This predecessor may be a switch or something else that has multiple
947       // edges to the block.  Factor each of these edges by listing them
948       // according to # occurrences in PredsToFactor.
949       TerminatorInst *PredTI = Pred->getTerminator();
950       for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
951         if (PredTI->getSuccessor(i) == BB)
952           PredsToFactor.push_back(Pred);
953     }
954
955   BasicBlock *PredToThread;
956   if (PredsToFactor.size() == 1)
957     PredToThread = PredsToFactor[0];
958   else {
959     DEBUG(errs() << "  Factoring out " << PredsToFactor.size()
960                  << " common predecessors.\n");
961     PredToThread = SplitBlockPredecessors(BB, &PredsToFactor[0],
962                                           PredsToFactor.size(),
963                                           ".thr_comm", this);
964   }
965   
966   // If the threadable edges are branching on an undefined value, we get to pick
967   // the destination that these predecessors should get to.
968   if (MostPopularDest == 0)
969     MostPopularDest = BB->getTerminator()->
970                             getSuccessor(GetBestDestForJumpOnUndef(BB));
971         
972   // Ok, try to thread it!
973   return ThreadEdge(BB, PredToThread, MostPopularDest);
974 }
975
976 /// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
977 /// the current block.  See if there are any simplifications we can do based on
978 /// inputs to the phi node.
979 /// 
980 bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
981   BasicBlock *BB = PN->getParent();
982   
983   // If any of the predecessor blocks end in an unconditional branch, we can
984   // *duplicate* the jump into that block in order to further encourage jump
985   // threading and to eliminate cases where we have branch on a phi of an icmp
986   // (branch on icmp is much better).
987
988   // We don't want to do this tranformation for switches, because we don't
989   // really want to duplicate a switch.
990   if (isa<SwitchInst>(BB->getTerminator()))
991     return false;
992   
993   // Look for unconditional branch predecessors.
994   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
995     BasicBlock *PredBB = PN->getIncomingBlock(i);
996     if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
997       if (PredBr->isUnconditional() &&
998           // Try to duplicate BB into PredBB.
999           DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
1000         return true;
1001   }
1002
1003   return false;
1004 }
1005
1006
1007 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1008 /// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
1009 /// NewPred using the entries from OldPred (suitably mapped).
1010 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1011                                             BasicBlock *OldPred,
1012                                             BasicBlock *NewPred,
1013                                      DenseMap<Instruction*, Value*> &ValueMap) {
1014   for (BasicBlock::iterator PNI = PHIBB->begin();
1015        PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1016     // Ok, we have a PHI node.  Figure out what the incoming value was for the
1017     // DestBlock.
1018     Value *IV = PN->getIncomingValueForBlock(OldPred);
1019     
1020     // Remap the value if necessary.
1021     if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1022       DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1023       if (I != ValueMap.end())
1024         IV = I->second;
1025     }
1026     
1027     PN->addIncoming(IV, NewPred);
1028   }
1029 }
1030
1031 /// ThreadEdge - We have decided that it is safe and profitable to thread an
1032 /// edge from PredBB to SuccBB across BB.  Transform the IR to reflect this
1033 /// change.
1034 bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, 
1035                                BasicBlock *SuccBB) {
1036   // If threading to the same block as we come from, we would infinite loop.
1037   if (SuccBB == BB) {
1038     DEBUG(errs() << "  Not threading across BB '" << BB->getName()
1039           << "' - would thread to self!\n");
1040     return false;
1041   }
1042   
1043   // If threading this would thread across a loop header, don't thread the edge.
1044   // See the comments above FindLoopHeaders for justifications and caveats.
1045   if (LoopHeaders.count(BB)) {
1046     DEBUG(errs() << "  Not threading from '" << PredBB->getName()
1047           << "' across loop header BB '" << BB->getName()
1048           << "' to dest BB '" << SuccBB->getName()
1049           << "' - it might create an irreducible loop!\n");
1050     return false;
1051   }
1052
1053   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
1054   if (JumpThreadCost > Threshold) {
1055     DEBUG(errs() << "  Not threading BB '" << BB->getName()
1056           << "' - Cost is too high: " << JumpThreadCost << "\n");
1057     return false;
1058   }
1059   
1060   // And finally, do it!
1061   DEBUG(errs() << "  Threading edge from '" << PredBB->getName() << "' to '"
1062         << SuccBB->getName() << "' with cost: " << JumpThreadCost
1063         << ", across block:\n    "
1064         << *BB << "\n");
1065   
1066   // We are going to have to map operands from the original BB block to the new
1067   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
1068   // account for entry from PredBB.
1069   DenseMap<Instruction*, Value*> ValueMapping;
1070   
1071   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), 
1072                                          BB->getName()+".thread", 
1073                                          BB->getParent(), BB);
1074   NewBB->moveAfter(PredBB);
1075   
1076   BasicBlock::iterator BI = BB->begin();
1077   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1078     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1079   
1080   // Clone the non-phi instructions of BB into NewBB, keeping track of the
1081   // mapping and using it to remap operands in the cloned instructions.
1082   for (; !isa<TerminatorInst>(BI); ++BI) {
1083     Instruction *New = BI->clone();
1084     New->setName(BI->getName());
1085     NewBB->getInstList().push_back(New);
1086     ValueMapping[BI] = New;
1087    
1088     // Remap operands to patch up intra-block references.
1089     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1090       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1091         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1092         if (I != ValueMapping.end())
1093           New->setOperand(i, I->second);
1094       }
1095   }
1096   
1097   // We didn't copy the terminator from BB over to NewBB, because there is now
1098   // an unconditional jump to SuccBB.  Insert the unconditional jump.
1099   BranchInst::Create(SuccBB, NewBB);
1100   
1101   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1102   // PHI nodes for NewBB now.
1103   AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
1104   
1105   // If there were values defined in BB that are used outside the block, then we
1106   // now have to update all uses of the value to use either the original value,
1107   // the cloned value, or some PHI derived value.  This can require arbitrary
1108   // PHI insertion, of which we are prepared to do, clean these up now.
1109   SSAUpdater SSAUpdate;
1110   SmallVector<Use*, 16> UsesToRename;
1111   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1112     // Scan all uses of this instruction to see if it is used outside of its
1113     // block, and if so, record them in UsesToRename.
1114     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1115          ++UI) {
1116       Instruction *User = cast<Instruction>(*UI);
1117       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1118         if (UserPN->getIncomingBlock(UI) == BB)
1119           continue;
1120       } else if (User->getParent() == BB)
1121         continue;
1122       
1123       UsesToRename.push_back(&UI.getUse());
1124     }
1125     
1126     // If there are no uses outside the block, we're done with this instruction.
1127     if (UsesToRename.empty())
1128       continue;
1129     
1130     DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1131
1132     // We found a use of I outside of BB.  Rename all uses of I that are outside
1133     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1134     // with the two values we know.
1135     SSAUpdate.Initialize(I);
1136     SSAUpdate.AddAvailableValue(BB, I);
1137     SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1138     
1139     while (!UsesToRename.empty())
1140       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1141     DEBUG(errs() << "\n");
1142   }
1143   
1144   
1145   // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
1146   // NewBB instead of BB.  This eliminates predecessors from BB, which requires
1147   // us to simplify any PHI nodes in BB.
1148   TerminatorInst *PredTerm = PredBB->getTerminator();
1149   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1150     if (PredTerm->getSuccessor(i) == BB) {
1151       BB->removePredecessor(PredBB);
1152       PredTerm->setSuccessor(i, NewBB);
1153     }
1154   
1155   // At this point, the IR is fully up to date and consistent.  Do a quick scan
1156   // over the new instructions and zap any that are constants or dead.  This
1157   // frequently happens because of phi translation.
1158   BI = NewBB->begin();
1159   for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1160     Instruction *Inst = BI++;
1161     if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
1162       Inst->replaceAllUsesWith(C);
1163       Inst->eraseFromParent();
1164       continue;
1165     }
1166     
1167     RecursivelyDeleteTriviallyDeadInstructions(Inst);
1168   }
1169   
1170   // Threaded an edge!
1171   ++NumThreads;
1172   return true;
1173 }
1174
1175 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1176 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1177 /// If we can duplicate the contents of BB up into PredBB do so now, this
1178 /// improves the odds that the branch will be on an analyzable instruction like
1179 /// a compare.
1180 bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1181                                                      BasicBlock *PredBB) {
1182   // If BB is a loop header, then duplicating this block outside the loop would
1183   // cause us to transform this into an irreducible loop, don't do this.
1184   // See the comments above FindLoopHeaders for justifications and caveats.
1185   if (LoopHeaders.count(BB)) {
1186     DEBUG(errs() << "  Not duplicating loop header '" << BB->getName()
1187           << "' into predecessor block '" << PredBB->getName()
1188           << "' - it might create an irreducible loop!\n");
1189     return false;
1190   }
1191   
1192   unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1193   if (DuplicationCost > Threshold) {
1194     DEBUG(errs() << "  Not duplicating BB '" << BB->getName()
1195           << "' - Cost is too high: " << DuplicationCost << "\n");
1196     return false;
1197   }
1198   
1199   // Okay, we decided to do this!  Clone all the instructions in BB onto the end
1200   // of PredBB.
1201   DEBUG(errs() << "  Duplicating block '" << BB->getName() << "' into end of '"
1202         << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
1203         << DuplicationCost << " block is:" << *BB << "\n");
1204   
1205   // We are going to have to map operands from the original BB block into the
1206   // PredBB block.  Evaluate PHI nodes in BB.
1207   DenseMap<Instruction*, Value*> ValueMapping;
1208   
1209   BasicBlock::iterator BI = BB->begin();
1210   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1211     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1212   
1213   BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1214   
1215   // Clone the non-phi instructions of BB into PredBB, keeping track of the
1216   // mapping and using it to remap operands in the cloned instructions.
1217   for (; BI != BB->end(); ++BI) {
1218     Instruction *New = BI->clone();
1219     New->setName(BI->getName());
1220     PredBB->getInstList().insert(OldPredBranch, New);
1221     ValueMapping[BI] = New;
1222     
1223     // Remap operands to patch up intra-block references.
1224     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1225       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1226         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1227         if (I != ValueMapping.end())
1228           New->setOperand(i, I->second);
1229       }
1230   }
1231   
1232   // Check to see if the targets of the branch had PHI nodes. If so, we need to
1233   // add entries to the PHI nodes for branch from PredBB now.
1234   BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1235   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1236                                   ValueMapping);
1237   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1238                                   ValueMapping);
1239   
1240   // If there were values defined in BB that are used outside the block, then we
1241   // now have to update all uses of the value to use either the original value,
1242   // the cloned value, or some PHI derived value.  This can require arbitrary
1243   // PHI insertion, of which we are prepared to do, clean these up now.
1244   SSAUpdater SSAUpdate;
1245   SmallVector<Use*, 16> UsesToRename;
1246   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1247     // Scan all uses of this instruction to see if it is used outside of its
1248     // block, and if so, record them in UsesToRename.
1249     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1250          ++UI) {
1251       Instruction *User = cast<Instruction>(*UI);
1252       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1253         if (UserPN->getIncomingBlock(UI) == BB)
1254           continue;
1255       } else if (User->getParent() == BB)
1256         continue;
1257       
1258       UsesToRename.push_back(&UI.getUse());
1259     }
1260     
1261     // If there are no uses outside the block, we're done with this instruction.
1262     if (UsesToRename.empty())
1263       continue;
1264     
1265     DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1266     
1267     // We found a use of I outside of BB.  Rename all uses of I that are outside
1268     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1269     // with the two values we know.
1270     SSAUpdate.Initialize(I);
1271     SSAUpdate.AddAvailableValue(BB, I);
1272     SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1273     
1274     while (!UsesToRename.empty())
1275       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1276     DEBUG(errs() << "\n");
1277   }
1278   
1279   // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1280   // that we nuked.
1281   BB->removePredecessor(PredBB);
1282   
1283   // Remove the unconditional branch at the end of the PredBB block.
1284   OldPredBranch->eraseFromParent();
1285   
1286   ++NumDupes;
1287   return true;
1288 }
1289
1290