move FindAvailableLoadedValue from JumpThreading to Transforms/Utils.
[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/Pass.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 using namespace llvm;
27
28 STATISTIC(NumThreads, "Number of jumps threaded");
29 STATISTIC(NumFolds,   "Number of terminators folded");
30
31 static cl::opt<unsigned>
32 Threshold("jump-threading-threshold", 
33           cl::desc("Max block size to duplicate for jump threading"),
34           cl::init(6), cl::Hidden);
35
36 namespace {
37   /// This pass performs 'jump threading', which looks at blocks that have
38   /// multiple predecessors and multiple successors.  If one or more of the
39   /// predecessors of the block can be proven to always jump to one of the
40   /// successors, we forward the edge from the predecessor to the successor by
41   /// duplicating the contents of this block.
42   ///
43   /// An example of when this can occur is code like this:
44   ///
45   ///   if () { ...
46   ///     X = 4;
47   ///   }
48   ///   if (X < 3) {
49   ///
50   /// In this case, the unconditional branch at the end of the first if can be
51   /// revectored to the false side of the second if.
52   ///
53   class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
54   public:
55     static char ID; // Pass identification
56     JumpThreading() : FunctionPass(&ID) {}
57
58     bool runOnFunction(Function &F);
59     bool ProcessBlock(BasicBlock *BB);
60     void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
61     BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
62
63     bool ProcessJumpOnPHI(PHINode *PN);
64     bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
65     bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
66     
67     bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
68   };
69 }
70
71 char JumpThreading::ID = 0;
72 static RegisterPass<JumpThreading>
73 X("jump-threading", "Jump Threading");
74
75 // Public interface to the Jump Threading pass
76 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
77
78 /// runOnFunction - Top level algorithm.
79 ///
80 bool JumpThreading::runOnFunction(Function &F) {
81   DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
82   
83   bool AnotherIteration = true, EverChanged = false;
84   while (AnotherIteration) {
85     AnotherIteration = false;
86     bool Changed = false;
87     for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
88       while (ProcessBlock(I))
89         Changed = true;
90     AnotherIteration = Changed;
91     EverChanged |= Changed;
92   }
93   return EverChanged;
94 }
95
96 /// FactorCommonPHIPreds - If there are multiple preds with the same incoming
97 /// value for the PHI, factor them together so we get one block to thread for
98 /// the whole group.
99 /// This is important for things like "phi i1 [true, true, false, true, x]"
100 /// where we only need to clone the block for the true blocks once.
101 ///
102 BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
103   SmallVector<BasicBlock*, 16> CommonPreds;
104   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
105     if (PN->getIncomingValue(i) == CstVal)
106       CommonPreds.push_back(PN->getIncomingBlock(i));
107   
108   if (CommonPreds.size() == 1)
109     return CommonPreds[0];
110     
111   DOUT << "  Factoring out " << CommonPreds.size()
112        << " common predecessors.\n";
113   return SplitBlockPredecessors(PN->getParent(),
114                                 &CommonPreds[0], CommonPreds.size(),
115                                 ".thr_comm", this);
116 }
117   
118
119 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
120 /// thread across it.
121 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
122   /// Ignore PHI nodes, these will be flattened when duplication happens.
123   BasicBlock::const_iterator I = BB->getFirstNonPHI();
124
125   // Sum up the cost of each instruction until we get to the terminator.  Don't
126   // include the terminator because the copy won't include it.
127   unsigned Size = 0;
128   for (; !isa<TerminatorInst>(I); ++I) {
129     // Debugger intrinsics don't incur code size.
130     if (isa<DbgInfoIntrinsic>(I)) continue;
131     
132     // If this is a pointer->pointer bitcast, it is free.
133     if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
134       continue;
135     
136     // All other instructions count for at least one unit.
137     ++Size;
138     
139     // Calls are more expensive.  If they are non-intrinsic calls, we model them
140     // as having cost of 4.  If they are a non-vector intrinsic, we model them
141     // as having cost of 2 total, and if they are a vector intrinsic, we model
142     // them as having cost 1.
143     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
144       if (!isa<IntrinsicInst>(CI))
145         Size += 3;
146       else if (isa<VectorType>(CI->getType()))
147         Size += 1;
148     }
149   }
150   
151   // Threading through a switch statement is particularly profitable.  If this
152   // block ends in a switch, decrease its cost to make it more likely to happen.
153   if (isa<SwitchInst>(I))
154     Size = Size > 6 ? Size-6 : 0;
155   
156   return Size;
157 }
158
159 /// ProcessBlock - If there are any predecessors whose control can be threaded
160 /// through to a successor, transform them now.
161 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
162   // If this block has a single predecessor, and if that pred has a single
163   // successor, merge the blocks.  This encourages recursive jump threading
164   // because now the condition in this block can be threaded through
165   // predecessors of our predecessor block.
166   if (BasicBlock *SinglePred = BB->getSinglePredecessor())
167     if (SinglePred->getTerminator()->getNumSuccessors() == 1) {
168       MergeBasicBlockIntoOnlyPred(BB);
169       return true;
170     }
171   
172   // See if this block ends with a branch or switch.  If so, see if the
173   // condition is a phi node.  If so, and if an entry of the phi node is a
174   // constant, we can thread the block.
175   Value *Condition;
176   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
177     // Can't thread an unconditional jump.
178     if (BI->isUnconditional()) return false;
179     Condition = BI->getCondition();
180   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
181     Condition = SI->getCondition();
182   else
183     return false; // Must be an invoke.
184   
185   // If the terminator of this block is branching on a constant, simplify the
186   // terminator to an unconditional branch.  This can occur due to threading in
187   // other blocks.
188   if (isa<ConstantInt>(Condition)) {
189     DOUT << "  In block '" << BB->getNameStart()
190          << "' folding terminator: " << *BB->getTerminator();
191     ++NumFolds;
192     ConstantFoldTerminator(BB);
193     return true;
194   }
195   
196   // If there is only a single predecessor of this block, nothing to fold.
197   if (BB->getSinglePredecessor())
198     return false;
199
200   // See if this is a phi node in the current block.
201   PHINode *PN = dyn_cast<PHINode>(Condition);
202   if (PN && PN->getParent() == BB)
203     return ProcessJumpOnPHI(PN);
204   
205   // If this is a conditional branch whose condition is and/or of a phi, try to
206   // simplify it.
207   if (BinaryOperator *CondI = dyn_cast<BinaryOperator>(Condition)) {
208     if ((CondI->getOpcode() == Instruction::And || 
209          CondI->getOpcode() == Instruction::Or) &&
210         isa<BranchInst>(BB->getTerminator()) &&
211         ProcessBranchOnLogical(CondI, BB,
212                                CondI->getOpcode() == Instruction::And))
213       return true;
214   }
215   
216   // If we have "br (phi != 42)" and the phi node has any constant values as 
217   // operands, we can thread through this block.
218   if (CmpInst *CondCmp = dyn_cast<CmpInst>(Condition))
219     if (isa<PHINode>(CondCmp->getOperand(0)) &&
220         isa<Constant>(CondCmp->getOperand(1)) &&
221         ProcessBranchOnCompare(CondCmp, BB))
222       return true;
223
224   // Check for some cases that are worth simplifying.  Right now we want to look
225   // for loads that are used by a switch or by the condition for the branch.  If
226   // we see one, check to see if it's partially redundant.  If so, insert a PHI
227   // which can then be used to thread the values.
228   //
229   // This is particularly important because reg2mem inserts loads and stores all
230   // over the place, and this blocks jump threading if we don't zap them.
231   Value *SimplifyValue = Condition;
232   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
233     if (isa<Constant>(CondCmp->getOperand(1)))
234       SimplifyValue = CondCmp->getOperand(0);
235   
236   if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
237     if (SimplifyPartiallyRedundantLoad(LI))
238       return true;
239   
240   // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
241   // "(X == 4)" thread through this block.
242   
243   return false;
244 }
245
246 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
247 /// load instruction, eliminate it by replacing it with a PHI node.  This is an
248 /// important optimization that encourages jump threading, and needs to be run
249 /// interlaced with other jump threading tasks.
250 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
251   // Don't hack volatile loads.
252   if (LI->isVolatile()) return false;
253   
254   // If the load is defined in a block with exactly one predecessor, it can't be
255   // partially redundant.
256   BasicBlock *LoadBB = LI->getParent();
257   if (LoadBB->getSinglePredecessor())
258     return false;
259   
260   Value *LoadedPtr = LI->getOperand(0);
261
262   // If the loaded operand is defined in the LoadBB, it can't be available.
263   // FIXME: Could do PHI translation, that would be fun :)
264   if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
265     if (PtrOp->getParent() == LoadBB)
266       return false;
267   
268   // Scan a few instructions up from the load, to see if it is obviously live at
269   // the entry to its block.
270   BasicBlock::iterator BBIt = LI;
271
272   if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB, 
273                                                      BBIt, 6)) {
274     // If the value if the load is locally available within the block, just use
275     // it.  This frequently occurs for reg2mem'd allocas.
276     //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
277     LI->replaceAllUsesWith(AvailableVal);
278     LI->eraseFromParent();
279     return true;
280   }
281
282   // Otherwise, if we scanned the whole block and got to the top of the block,
283   // we know the block is locally transparent to the load.  If not, something
284   // might clobber its value.
285   if (BBIt != LoadBB->begin())
286     return false;
287   
288   
289   SmallPtrSet<BasicBlock*, 8> PredsScanned;
290   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
291   AvailablePredsTy AvailablePreds;
292   BasicBlock *OneUnavailablePred = 0;
293   
294   // If we got here, the loaded value is transparent through to the start of the
295   // block.  Check to see if it is available in any of the predecessor blocks.
296   for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
297        PI != PE; ++PI) {
298     BasicBlock *PredBB = *PI;
299
300     // If we already scanned this predecessor, skip it.
301     if (!PredsScanned.insert(PredBB))
302       continue;
303
304     // Scan the predecessor to see if the value is available in the pred.
305     BBIt = PredBB->end();
306     Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
307     if (!PredAvailable) {
308       OneUnavailablePred = PredBB;
309       continue;
310     }
311     
312     // If so, this load is partially redundant.  Remember this info so that we
313     // can create a PHI node.
314     AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
315   }
316   
317   // If the loaded value isn't available in any predecessor, it isn't partially
318   // redundant.
319   if (AvailablePreds.empty()) return false;
320   
321   // Okay, the loaded value is available in at least one (and maybe all!)
322   // predecessors.  If the value is unavailable in more than one unique
323   // predecessor, we want to insert a merge block for those common predecessors.
324   // This ensures that we only have to insert one reload, thus not increasing
325   // code size.
326   BasicBlock *UnavailablePred = 0;
327   
328   // If there is exactly one predecessor where the value is unavailable, the
329   // already computed 'OneUnavailablePred' block is it.  If it ends in an
330   // unconditional branch, we know that it isn't a critical edge.
331   if (PredsScanned.size() == AvailablePreds.size()+1 &&
332       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
333     UnavailablePred = OneUnavailablePred;
334   } else if (PredsScanned.size() != AvailablePreds.size()) {
335     // Otherwise, we had multiple unavailable predecessors or we had a critical
336     // edge from the one.
337     SmallVector<BasicBlock*, 8> PredsToSplit;
338     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
339
340     for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
341       AvailablePredSet.insert(AvailablePreds[i].first);
342
343     // Add all the unavailable predecessors to the PredsToSplit list.
344     for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
345          PI != PE; ++PI)
346       if (!AvailablePredSet.count(*PI))
347         PredsToSplit.push_back(*PI);
348     
349     // Split them out to their own block.
350     UnavailablePred =
351       SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
352                              "thread-split", this);
353   }
354   
355   // If the value isn't available in all predecessors, then there will be
356   // exactly one where it isn't available.  Insert a load on that edge and add
357   // it to the AvailablePreds list.
358   if (UnavailablePred) {
359     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
360            "Can't handle critical edge here!");
361     Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
362                                  UnavailablePred->getTerminator());
363     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
364   }
365   
366   // Now we know that each predecessor of this block has a value in
367   // AvailablePreds, sort them for efficient access as we're walking the preds.
368   std::sort(AvailablePreds.begin(), AvailablePreds.end());
369   
370   // Create a PHI node at the start of the block for the PRE'd load value.
371   PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
372   PN->takeName(LI);
373   
374   // Insert new entries into the PHI for each predecessor.  A single block may
375   // have multiple entries here.
376   for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
377        ++PI) {
378     AvailablePredsTy::iterator I = 
379       std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
380                        std::make_pair(*PI, (Value*)0));
381     
382     assert(I != AvailablePreds.end() && I->first == *PI &&
383            "Didn't find entry for predecessor!");
384     
385     PN->addIncoming(I->second, I->first);
386   }
387   
388   //cerr << "PRE: " << *LI << *PN << "\n";
389   
390   LI->replaceAllUsesWith(PN);
391   LI->eraseFromParent();
392   
393   return true;
394 }
395
396
397 /// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
398 /// the current block.  See if there are any simplifications we can do based on
399 /// inputs to the phi node.
400 /// 
401 bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
402   // See if the phi node has any constant values.  If so, we can determine where
403   // the corresponding predecessor will branch.
404   ConstantInt *PredCst = 0;
405   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
406     if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
407       break;
408   
409   // If no incoming value has a constant, we don't know the destination of any
410   // predecessors.
411   if (PredCst == 0)
412     return false;
413   
414   // See if the cost of duplicating this block is low enough.
415   BasicBlock *BB = PN->getParent();
416   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
417   if (JumpThreadCost > Threshold) {
418     DOUT << "  Not threading BB '" << BB->getNameStart()
419          << "' - Cost is too high: " << JumpThreadCost << "\n";
420     return false;
421   }
422   
423   // If so, we can actually do this threading.  Merge any common predecessors
424   // that will act the same.
425   BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
426   
427   // Next, figure out which successor we are threading to.
428   BasicBlock *SuccBB;
429   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
430     SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
431   else {
432     SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
433     SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
434   }
435   
436   // If threading to the same block as we come from, we would infinite loop.
437   if (SuccBB == BB) {
438     DOUT << "  Not threading BB '" << BB->getNameStart()
439          << "' - would thread to self!\n";
440     return false;
441   }
442   
443   // And finally, do it!
444   DOUT << "  Threading edge from '" << PredBB->getNameStart() << "' to '"
445        << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
446        << ", across block:\n    "
447        << *BB << "\n";
448        
449   ThreadEdge(BB, PredBB, SuccBB);
450   ++NumThreads;
451   return true;
452 }
453
454 /// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
455 /// whose condition is an AND/OR where one side is PN.  If PN has constant
456 /// operands that permit us to evaluate the condition for some operand, thread
457 /// through the block.  For example with:
458 ///   br (and X, phi(Y, Z, false))
459 /// the predecessor corresponding to the 'false' will always jump to the false
460 /// destination of the branch.
461 ///
462 bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
463                                            bool isAnd) {
464   // If this is a binary operator tree of the same AND/OR opcode, check the
465   // LHS/RHS.
466   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
467     if ((isAnd && BO->getOpcode() == Instruction::And) ||
468         (!isAnd && BO->getOpcode() == Instruction::Or)) {
469       if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
470         return true;
471       if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
472         return true;
473     }
474       
475   // If this isn't a PHI node, we can't handle it.
476   PHINode *PN = dyn_cast<PHINode>(V);
477   if (!PN || PN->getParent() != BB) return false;
478                                              
479   // We can only do the simplification for phi nodes of 'false' with AND or
480   // 'true' with OR.  See if we have any entries in the phi for this.
481   unsigned PredNo = ~0U;
482   ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
483   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
484     if (PN->getIncomingValue(i) == PredCst) {
485       PredNo = i;
486       break;
487     }
488   }
489   
490   // If no match, bail out.
491   if (PredNo == ~0U)
492     return false;
493   
494   // See if the cost of duplicating this block is low enough.
495   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
496   if (JumpThreadCost > Threshold) {
497     DOUT << "  Not threading BB '" << BB->getNameStart()
498          << "' - Cost is too high: " << JumpThreadCost << "\n";
499     return false;
500   }
501
502   // If so, we can actually do this threading.  Merge any common predecessors
503   // that will act the same.
504   BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
505   
506   // Next, figure out which successor we are threading to.  If this was an AND,
507   // the constant must be FALSE, and we must be targeting the 'false' block.
508   // If this is an OR, the constant must be TRUE, and we must be targeting the
509   // 'true' block.
510   BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
511   
512   // If threading to the same block as we come from, we would infinite loop.
513   if (SuccBB == BB) {
514     DOUT << "  Not threading BB '" << BB->getNameStart()
515     << "' - would thread to self!\n";
516     return false;
517   }
518   
519   // And finally, do it!
520   DOUT << "  Threading edge through bool from '" << PredBB->getNameStart()
521        << "' to '" << SuccBB->getNameStart() << "' with cost: "
522        << JumpThreadCost << ", across block:\n    "
523        << *BB << "\n";
524   
525   ThreadEdge(BB, PredBB, SuccBB);
526   ++NumThreads;
527   return true;
528 }
529
530 /// ProcessBranchOnCompare - We found a branch on a comparison between a phi
531 /// node and a constant.  If the PHI node contains any constants as inputs, we
532 /// can fold the compare for that edge and thread through it.
533 bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
534   PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
535   Constant *RHS = cast<Constant>(Cmp->getOperand(1));
536   
537   // If the phi isn't in the current block, an incoming edge to this block
538   // doesn't control the destination.
539   if (PN->getParent() != BB)
540     return false;
541   
542   // We can do this simplification if any comparisons fold to true or false.
543   // See if any do.
544   Constant *PredCst = 0;
545   bool TrueDirection = false;
546   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
547     PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
548     if (PredCst == 0) continue;
549     
550     Constant *Res;
551     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
552       Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
553     else
554       Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
555                                   PredCst, RHS);
556     // If this folded to a constant expr, we can't do anything.
557     if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
558       TrueDirection = ResC->getZExtValue();
559       break;
560     }
561     // If this folded to undef, just go the false way.
562     if (isa<UndefValue>(Res)) {
563       TrueDirection = false;
564       break;
565     }
566     
567     // Otherwise, we can't fold this input.
568     PredCst = 0;
569   }
570   
571   // If no match, bail out.
572   if (PredCst == 0)
573     return false;
574   
575   // See if the cost of duplicating this block is low enough.
576   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
577   if (JumpThreadCost > Threshold) {
578     DOUT << "  Not threading BB '" << BB->getNameStart()
579          << "' - Cost is too high: " << JumpThreadCost << "\n";
580     return false;
581   }
582   
583   // If so, we can actually do this threading.  Merge any common predecessors
584   // that will act the same.
585   BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
586   
587   // Next, get our successor.
588   BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
589   
590   // If threading to the same block as we come from, we would infinite loop.
591   if (SuccBB == BB) {
592     DOUT << "  Not threading BB '" << BB->getNameStart()
593     << "' - would thread to self!\n";
594     return false;
595   }
596   
597   
598   // And finally, do it!
599   DOUT << "  Threading edge through bool from '" << PredBB->getNameStart()
600        << "' to '" << SuccBB->getNameStart() << "' with cost: "
601        << JumpThreadCost << ", across block:\n    "
602        << *BB << "\n";
603   
604   ThreadEdge(BB, PredBB, SuccBB);
605   ++NumThreads;
606   return true;
607 }
608
609
610 /// ThreadEdge - We have decided that it is safe and profitable to thread an
611 /// edge from PredBB to SuccBB across BB.  Transform the IR to reflect this
612 /// change.
613 void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, 
614                                BasicBlock *SuccBB) {
615
616   // Jump Threading can not update SSA properties correctly if the values
617   // defined in the duplicated block are used outside of the block itself.  For
618   // this reason, we spill all values that are used outside of BB to the stack.
619   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
620     if (!I->isUsedOutsideOfBlock(BB))
621       continue;
622     
623     // We found a use of I outside of BB.  Create a new stack slot to
624     // break this inter-block usage pattern.
625     DemoteRegToStack(*I);
626   }
627  
628   // We are going to have to map operands from the original BB block to the new
629   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
630   // account for entry from PredBB.
631   DenseMap<Instruction*, Value*> ValueMapping;
632   
633   BasicBlock *NewBB =
634     BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
635   NewBB->moveAfter(PredBB);
636   
637   BasicBlock::iterator BI = BB->begin();
638   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
639     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
640   
641   // Clone the non-phi instructions of BB into NewBB, keeping track of the
642   // mapping and using it to remap operands in the cloned instructions.
643   for (; !isa<TerminatorInst>(BI); ++BI) {
644     Instruction *New = BI->clone();
645     New->setName(BI->getNameStart());
646     NewBB->getInstList().push_back(New);
647     ValueMapping[BI] = New;
648    
649     // Remap operands to patch up intra-block references.
650     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
651       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
652         if (Value *Remapped = ValueMapping[Inst])
653           New->setOperand(i, Remapped);
654   }
655   
656   // We didn't copy the terminator from BB over to NewBB, because there is now
657   // an unconditional jump to SuccBB.  Insert the unconditional jump.
658   BranchInst::Create(SuccBB, NewBB);
659   
660   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
661   // PHI nodes for NewBB now.
662   for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
663     PHINode *PN = cast<PHINode>(PNI);
664     // Ok, we have a PHI node.  Figure out what the incoming value was for the
665     // DestBlock.
666     Value *IV = PN->getIncomingValueForBlock(BB);
667     
668     // Remap the value if necessary.
669     if (Instruction *Inst = dyn_cast<Instruction>(IV))
670       if (Value *MappedIV = ValueMapping[Inst])
671         IV = MappedIV;
672     PN->addIncoming(IV, NewBB);
673   }
674   
675   // Finally, NewBB is good to go.  Update the terminator of PredBB to jump to
676   // NewBB instead of BB.  This eliminates predecessors from BB, which requires
677   // us to simplify any PHI nodes in BB.
678   TerminatorInst *PredTerm = PredBB->getTerminator();
679   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
680     if (PredTerm->getSuccessor(i) == BB) {
681       BB->removePredecessor(PredBB);
682       PredTerm->setSuccessor(i, NewBB);
683     }
684 }