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