don't call MergeBasicBlockIntoOnlyPred on a block whose only
[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         SinglePred != BB) {
169       // Remember if SinglePred was the entry block of the function.  If so, we
170       // will need to move BB back to the entry position.
171       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
172       MergeBasicBlockIntoOnlyPred(BB);
173       
174       if (isEntry && BB != &BB->getParent()->getEntryBlock())
175         BB->moveBefore(&BB->getParent()->getEntryBlock());
176       return true;
177     }
178   
179   // See if this block ends with a branch or switch.  If so, see if the
180   // condition is a phi node.  If so, and if an entry of the phi node is a
181   // constant, we can thread the block.
182   Value *Condition;
183   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
184     // Can't thread an unconditional jump.
185     if (BI->isUnconditional()) return false;
186     Condition = BI->getCondition();
187   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
188     Condition = SI->getCondition();
189   else
190     return false; // Must be an invoke.
191   
192   // If the terminator of this block is branching on a constant, simplify the
193   // terminator to an unconditional branch.  This can occur due to threading in
194   // other blocks.
195   if (isa<ConstantInt>(Condition)) {
196     DOUT << "  In block '" << BB->getNameStart()
197          << "' folding terminator: " << *BB->getTerminator();
198     ++NumFolds;
199     ConstantFoldTerminator(BB);
200     return true;
201   }
202   
203   // If there is only a single predecessor of this block, nothing to fold.
204   if (BB->getSinglePredecessor())
205     return false;
206
207   // See if this is a phi node in the current block.
208   PHINode *PN = dyn_cast<PHINode>(Condition);
209   if (PN && PN->getParent() == BB)
210     return ProcessJumpOnPHI(PN);
211   
212   // If this is a conditional branch whose condition is and/or of a phi, try to
213   // simplify it.
214   if (BinaryOperator *CondI = dyn_cast<BinaryOperator>(Condition)) {
215     if ((CondI->getOpcode() == Instruction::And || 
216          CondI->getOpcode() == Instruction::Or) &&
217         isa<BranchInst>(BB->getTerminator()) &&
218         ProcessBranchOnLogical(CondI, BB,
219                                CondI->getOpcode() == Instruction::And))
220       return true;
221   }
222   
223   // If we have "br (phi != 42)" and the phi node has any constant values as 
224   // operands, we can thread through this block.
225   if (CmpInst *CondCmp = dyn_cast<CmpInst>(Condition))
226     if (isa<PHINode>(CondCmp->getOperand(0)) &&
227         isa<Constant>(CondCmp->getOperand(1)) &&
228         ProcessBranchOnCompare(CondCmp, BB))
229       return true;
230
231   // Check for some cases that are worth simplifying.  Right now we want to look
232   // for loads that are used by a switch or by the condition for the branch.  If
233   // we see one, check to see if it's partially redundant.  If so, insert a PHI
234   // which can then be used to thread the values.
235   //
236   // This is particularly important because reg2mem inserts loads and stores all
237   // over the place, and this blocks jump threading if we don't zap them.
238   Value *SimplifyValue = Condition;
239   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
240     if (isa<Constant>(CondCmp->getOperand(1)))
241       SimplifyValue = CondCmp->getOperand(0);
242   
243   if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
244     if (SimplifyPartiallyRedundantLoad(LI))
245       return true;
246   
247   // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
248   // "(X == 4)" thread through this block.
249   
250   return false;
251 }
252
253 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
254 /// load instruction, eliminate it by replacing it with a PHI node.  This is an
255 /// important optimization that encourages jump threading, and needs to be run
256 /// interlaced with other jump threading tasks.
257 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
258   // Don't hack volatile loads.
259   if (LI->isVolatile()) return false;
260   
261   // If the load is defined in a block with exactly one predecessor, it can't be
262   // partially redundant.
263   BasicBlock *LoadBB = LI->getParent();
264   if (LoadBB->getSinglePredecessor())
265     return false;
266   
267   Value *LoadedPtr = LI->getOperand(0);
268
269   // If the loaded operand is defined in the LoadBB, it can't be available.
270   // FIXME: Could do PHI translation, that would be fun :)
271   if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
272     if (PtrOp->getParent() == LoadBB)
273       return false;
274   
275   // Scan a few instructions up from the load, to see if it is obviously live at
276   // the entry to its block.
277   BasicBlock::iterator BBIt = LI;
278
279   if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB, 
280                                                      BBIt, 6)) {
281     // If the value if the load is locally available within the block, just use
282     // it.  This frequently occurs for reg2mem'd allocas.
283     //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
284     LI->replaceAllUsesWith(AvailableVal);
285     LI->eraseFromParent();
286     return true;
287   }
288
289   // Otherwise, if we scanned the whole block and got to the top of the block,
290   // we know the block is locally transparent to the load.  If not, something
291   // might clobber its value.
292   if (BBIt != LoadBB->begin())
293     return false;
294   
295   
296   SmallPtrSet<BasicBlock*, 8> PredsScanned;
297   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
298   AvailablePredsTy AvailablePreds;
299   BasicBlock *OneUnavailablePred = 0;
300   
301   // If we got here, the loaded value is transparent through to the start of the
302   // block.  Check to see if it is available in any of the predecessor blocks.
303   for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
304        PI != PE; ++PI) {
305     BasicBlock *PredBB = *PI;
306
307     // If we already scanned this predecessor, skip it.
308     if (!PredsScanned.insert(PredBB))
309       continue;
310
311     // Scan the predecessor to see if the value is available in the pred.
312     BBIt = PredBB->end();
313     Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
314     if (!PredAvailable) {
315       OneUnavailablePred = PredBB;
316       continue;
317     }
318     
319     // If so, this load is partially redundant.  Remember this info so that we
320     // can create a PHI node.
321     AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
322   }
323   
324   // If the loaded value isn't available in any predecessor, it isn't partially
325   // redundant.
326   if (AvailablePreds.empty()) return false;
327   
328   // Okay, the loaded value is available in at least one (and maybe all!)
329   // predecessors.  If the value is unavailable in more than one unique
330   // predecessor, we want to insert a merge block for those common predecessors.
331   // This ensures that we only have to insert one reload, thus not increasing
332   // code size.
333   BasicBlock *UnavailablePred = 0;
334   
335   // If there is exactly one predecessor where the value is unavailable, the
336   // already computed 'OneUnavailablePred' block is it.  If it ends in an
337   // unconditional branch, we know that it isn't a critical edge.
338   if (PredsScanned.size() == AvailablePreds.size()+1 &&
339       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
340     UnavailablePred = OneUnavailablePred;
341   } else if (PredsScanned.size() != AvailablePreds.size()) {
342     // Otherwise, we had multiple unavailable predecessors or we had a critical
343     // edge from the one.
344     SmallVector<BasicBlock*, 8> PredsToSplit;
345     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
346
347     for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
348       AvailablePredSet.insert(AvailablePreds[i].first);
349
350     // Add all the unavailable predecessors to the PredsToSplit list.
351     for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
352          PI != PE; ++PI)
353       if (!AvailablePredSet.count(*PI))
354         PredsToSplit.push_back(*PI);
355     
356     // Split them out to their own block.
357     UnavailablePred =
358       SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
359                              "thread-split", this);
360   }
361   
362   // If the value isn't available in all predecessors, then there will be
363   // exactly one where it isn't available.  Insert a load on that edge and add
364   // it to the AvailablePreds list.
365   if (UnavailablePred) {
366     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
367            "Can't handle critical edge here!");
368     Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
369                                  UnavailablePred->getTerminator());
370     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
371   }
372   
373   // Now we know that each predecessor of this block has a value in
374   // AvailablePreds, sort them for efficient access as we're walking the preds.
375   std::sort(AvailablePreds.begin(), AvailablePreds.end());
376   
377   // Create a PHI node at the start of the block for the PRE'd load value.
378   PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
379   PN->takeName(LI);
380   
381   // Insert new entries into the PHI for each predecessor.  A single block may
382   // have multiple entries here.
383   for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
384        ++PI) {
385     AvailablePredsTy::iterator I = 
386       std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
387                        std::make_pair(*PI, (Value*)0));
388     
389     assert(I != AvailablePreds.end() && I->first == *PI &&
390            "Didn't find entry for predecessor!");
391     
392     PN->addIncoming(I->second, I->first);
393   }
394   
395   //cerr << "PRE: " << *LI << *PN << "\n";
396   
397   LI->replaceAllUsesWith(PN);
398   LI->eraseFromParent();
399   
400   return true;
401 }
402
403
404 /// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
405 /// the current block.  See if there are any simplifications we can do based on
406 /// inputs to the phi node.
407 /// 
408 bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
409   // See if the phi node has any constant values.  If so, we can determine where
410   // the corresponding predecessor will branch.
411   ConstantInt *PredCst = 0;
412   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
413     if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
414       break;
415   
416   // If no incoming value has a constant, we don't know the destination of any
417   // predecessors.
418   if (PredCst == 0)
419     return false;
420   
421   // See if the cost of duplicating this block is low enough.
422   BasicBlock *BB = PN->getParent();
423   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
424   if (JumpThreadCost > Threshold) {
425     DOUT << "  Not threading BB '" << BB->getNameStart()
426          << "' - Cost is too high: " << JumpThreadCost << "\n";
427     return false;
428   }
429   
430   // If so, we can actually do this threading.  Merge any common predecessors
431   // that will act the same.
432   BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
433   
434   // Next, figure out which successor we are threading to.
435   BasicBlock *SuccBB;
436   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
437     SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
438   else {
439     SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
440     SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
441   }
442   
443   // If threading to the same block as we come from, we would infinite loop.
444   if (SuccBB == BB) {
445     DOUT << "  Not threading BB '" << BB->getNameStart()
446          << "' - would thread to self!\n";
447     return false;
448   }
449   
450   // And finally, do it!
451   DOUT << "  Threading edge from '" << PredBB->getNameStart() << "' to '"
452        << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
453        << ", across block:\n    "
454        << *BB << "\n";
455        
456   ThreadEdge(BB, PredBB, SuccBB);
457   ++NumThreads;
458   return true;
459 }
460
461 /// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
462 /// whose condition is an AND/OR where one side is PN.  If PN has constant
463 /// operands that permit us to evaluate the condition for some operand, thread
464 /// through the block.  For example with:
465 ///   br (and X, phi(Y, Z, false))
466 /// the predecessor corresponding to the 'false' will always jump to the false
467 /// destination of the branch.
468 ///
469 bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
470                                            bool isAnd) {
471   // If this is a binary operator tree of the same AND/OR opcode, check the
472   // LHS/RHS.
473   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
474     if ((isAnd && BO->getOpcode() == Instruction::And) ||
475         (!isAnd && BO->getOpcode() == Instruction::Or)) {
476       if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
477         return true;
478       if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
479         return true;
480     }
481       
482   // If this isn't a PHI node, we can't handle it.
483   PHINode *PN = dyn_cast<PHINode>(V);
484   if (!PN || PN->getParent() != BB) return false;
485                                              
486   // We can only do the simplification for phi nodes of 'false' with AND or
487   // 'true' with OR.  See if we have any entries in the phi for this.
488   unsigned PredNo = ~0U;
489   ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
490   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
491     if (PN->getIncomingValue(i) == PredCst) {
492       PredNo = i;
493       break;
494     }
495   }
496   
497   // If no match, bail out.
498   if (PredNo == ~0U)
499     return false;
500   
501   // See if the cost of duplicating this block is low enough.
502   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
503   if (JumpThreadCost > Threshold) {
504     DOUT << "  Not threading BB '" << BB->getNameStart()
505          << "' - Cost is too high: " << JumpThreadCost << "\n";
506     return false;
507   }
508
509   // If so, we can actually do this threading.  Merge any common predecessors
510   // that will act the same.
511   BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
512   
513   // Next, figure out which successor we are threading to.  If this was an AND,
514   // the constant must be FALSE, and we must be targeting the 'false' block.
515   // If this is an OR, the constant must be TRUE, and we must be targeting the
516   // 'true' block.
517   BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
518   
519   // If threading to the same block as we come from, we would infinite loop.
520   if (SuccBB == BB) {
521     DOUT << "  Not threading BB '" << BB->getNameStart()
522     << "' - would thread to self!\n";
523     return false;
524   }
525   
526   // And finally, do it!
527   DOUT << "  Threading edge through bool from '" << PredBB->getNameStart()
528        << "' to '" << SuccBB->getNameStart() << "' with cost: "
529        << JumpThreadCost << ", across block:\n    "
530        << *BB << "\n";
531   
532   ThreadEdge(BB, PredBB, SuccBB);
533   ++NumThreads;
534   return true;
535 }
536
537 /// ProcessBranchOnCompare - We found a branch on a comparison between a phi
538 /// node and a constant.  If the PHI node contains any constants as inputs, we
539 /// can fold the compare for that edge and thread through it.
540 bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
541   PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
542   Constant *RHS = cast<Constant>(Cmp->getOperand(1));
543   
544   // If the phi isn't in the current block, an incoming edge to this block
545   // doesn't control the destination.
546   if (PN->getParent() != BB)
547     return false;
548   
549   // We can do this simplification if any comparisons fold to true or false.
550   // See if any do.
551   Constant *PredCst = 0;
552   bool TrueDirection = false;
553   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
554     PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
555     if (PredCst == 0) continue;
556     
557     Constant *Res;
558     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
559       Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
560     else
561       Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
562                                   PredCst, RHS);
563     // If this folded to a constant expr, we can't do anything.
564     if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
565       TrueDirection = ResC->getZExtValue();
566       break;
567     }
568     // If this folded to undef, just go the false way.
569     if (isa<UndefValue>(Res)) {
570       TrueDirection = false;
571       break;
572     }
573     
574     // Otherwise, we can't fold this input.
575     PredCst = 0;
576   }
577   
578   // If no match, bail out.
579   if (PredCst == 0)
580     return false;
581   
582   // See if the cost of duplicating this block is low enough.
583   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
584   if (JumpThreadCost > Threshold) {
585     DOUT << "  Not threading BB '" << BB->getNameStart()
586          << "' - Cost is too high: " << JumpThreadCost << "\n";
587     return false;
588   }
589   
590   // If so, we can actually do this threading.  Merge any common predecessors
591   // that will act the same.
592   BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
593   
594   // Next, get our successor.
595   BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
596   
597   // If threading to the same block as we come from, we would infinite loop.
598   if (SuccBB == BB) {
599     DOUT << "  Not threading BB '" << BB->getNameStart()
600     << "' - would thread to self!\n";
601     return false;
602   }
603   
604   
605   // And finally, do it!
606   DOUT << "  Threading edge through bool from '" << PredBB->getNameStart()
607        << "' to '" << SuccBB->getNameStart() << "' with cost: "
608        << JumpThreadCost << ", across block:\n    "
609        << *BB << "\n";
610   
611   ThreadEdge(BB, PredBB, SuccBB);
612   ++NumThreads;
613   return true;
614 }
615
616
617 /// ThreadEdge - We have decided that it is safe and profitable to thread an
618 /// edge from PredBB to SuccBB across BB.  Transform the IR to reflect this
619 /// change.
620 void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, 
621                                BasicBlock *SuccBB) {
622
623   // Jump Threading can not update SSA properties correctly if the values
624   // defined in the duplicated block are used outside of the block itself.  For
625   // this reason, we spill all values that are used outside of BB to the stack.
626   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
627     if (!I->isUsedOutsideOfBlock(BB))
628       continue;
629     
630     // We found a use of I outside of BB.  Create a new stack slot to
631     // break this inter-block usage pattern.
632     DemoteRegToStack(*I);
633   }
634  
635   // We are going to have to map operands from the original BB block to the new
636   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
637   // account for entry from PredBB.
638   DenseMap<Instruction*, Value*> ValueMapping;
639   
640   BasicBlock *NewBB =
641     BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
642   NewBB->moveAfter(PredBB);
643   
644   BasicBlock::iterator BI = BB->begin();
645   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
646     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
647   
648   // Clone the non-phi instructions of BB into NewBB, keeping track of the
649   // mapping and using it to remap operands in the cloned instructions.
650   for (; !isa<TerminatorInst>(BI); ++BI) {
651     Instruction *New = BI->clone();
652     New->setName(BI->getNameStart());
653     NewBB->getInstList().push_back(New);
654     ValueMapping[BI] = New;
655    
656     // Remap operands to patch up intra-block references.
657     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
658       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
659         if (Value *Remapped = ValueMapping[Inst])
660           New->setOperand(i, Remapped);
661   }
662   
663   // We didn't copy the terminator from BB over to NewBB, because there is now
664   // an unconditional jump to SuccBB.  Insert the unconditional jump.
665   BranchInst::Create(SuccBB, NewBB);
666   
667   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
668   // PHI nodes for NewBB now.
669   for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
670     PHINode *PN = cast<PHINode>(PNI);
671     // Ok, we have a PHI node.  Figure out what the incoming value was for the
672     // DestBlock.
673     Value *IV = PN->getIncomingValueForBlock(BB);
674     
675     // Remap the value if necessary.
676     if (Instruction *Inst = dyn_cast<Instruction>(IV))
677       if (Value *MappedIV = ValueMapping[Inst])
678         IV = MappedIV;
679     PN->addIncoming(IV, NewBB);
680   }
681   
682   // Finally, NewBB is good to go.  Update the terminator of PredBB to jump to
683   // NewBB instead of BB.  This eliminates predecessors from BB, which requires
684   // us to simplify any PHI nodes in BB.
685   TerminatorInst *PredTerm = PredBB->getTerminator();
686   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
687     if (PredTerm->getSuccessor(i) == BB) {
688       BB->removePredecessor(PredBB);
689       PredTerm->setSuccessor(i, NewBB);
690     }
691 }