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