Home | History | Annotate | Download | only in Scalar
      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/ADT/DenseMap.h"
     17 #include "llvm/ADT/DenseSet.h"
     18 #include "llvm/ADT/STLExtras.h"
     19 #include "llvm/ADT/SmallPtrSet.h"
     20 #include "llvm/ADT/SmallSet.h"
     21 #include "llvm/ADT/Statistic.h"
     22 #include "llvm/Analysis/CFG.h"
     23 #include "llvm/Analysis/ConstantFolding.h"
     24 #include "llvm/Analysis/InstructionSimplify.h"
     25 #include "llvm/Analysis/LazyValueInfo.h"
     26 #include "llvm/Analysis/Loads.h"
     27 #include "llvm/IR/DataLayout.h"
     28 #include "llvm/IR/IntrinsicInst.h"
     29 #include "llvm/IR/LLVMContext.h"
     30 #include "llvm/Pass.h"
     31 #include "llvm/Support/CommandLine.h"
     32 #include "llvm/Support/Debug.h"
     33 #include "llvm/Support/ValueHandle.h"
     34 #include "llvm/Support/raw_ostream.h"
     35 #include "llvm/Target/TargetLibraryInfo.h"
     36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
     37 #include "llvm/Transforms/Utils/Local.h"
     38 #include "llvm/Transforms/Utils/SSAUpdater.h"
     39 using namespace llvm;
     40 
     41 STATISTIC(NumThreads, "Number of jumps threaded");
     42 STATISTIC(NumFolds,   "Number of terminators folded");
     43 STATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
     44 
     45 static cl::opt<unsigned>
     46 Threshold("jump-threading-threshold",
     47           cl::desc("Max block size to duplicate for jump threading"),
     48           cl::init(6), cl::Hidden);
     49 
     50 namespace {
     51   // These are at global scope so static functions can use them too.
     52   typedef SmallVectorImpl<std::pair<Constant*, BasicBlock*> > PredValueInfo;
     53   typedef SmallVector<std::pair<Constant*, BasicBlock*>, 8> PredValueInfoTy;
     54 
     55   // This is used to keep track of what kind of constant we're currently hoping
     56   // to find.
     57   enum ConstantPreference {
     58     WantInteger,
     59     WantBlockAddress
     60   };
     61 
     62   /// This pass performs 'jump threading', which looks at blocks that have
     63   /// multiple predecessors and multiple successors.  If one or more of the
     64   /// predecessors of the block can be proven to always jump to one of the
     65   /// successors, we forward the edge from the predecessor to the successor by
     66   /// duplicating the contents of this block.
     67   ///
     68   /// An example of when this can occur is code like this:
     69   ///
     70   ///   if () { ...
     71   ///     X = 4;
     72   ///   }
     73   ///   if (X < 3) {
     74   ///
     75   /// In this case, the unconditional branch at the end of the first if can be
     76   /// revectored to the false side of the second if.
     77   ///
     78   class JumpThreading : public FunctionPass {
     79     DataLayout *TD;
     80     TargetLibraryInfo *TLI;
     81     LazyValueInfo *LVI;
     82 #ifdef NDEBUG
     83     SmallPtrSet<BasicBlock*, 16> LoopHeaders;
     84 #else
     85     SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
     86 #endif
     87     DenseSet<std::pair<Value*, BasicBlock*> > RecursionSet;
     88 
     89     // RAII helper for updating the recursion stack.
     90     struct RecursionSetRemover {
     91       DenseSet<std::pair<Value*, BasicBlock*> > &TheSet;
     92       std::pair<Value*, BasicBlock*> ThePair;
     93 
     94       RecursionSetRemover(DenseSet<std::pair<Value*, BasicBlock*> > &S,
     95                           std::pair<Value*, BasicBlock*> P)
     96         : TheSet(S), ThePair(P) { }
     97 
     98       ~RecursionSetRemover() {
     99         TheSet.erase(ThePair);
    100       }
    101     };
    102   public:
    103     static char ID; // Pass identification
    104     JumpThreading() : FunctionPass(ID) {
    105       initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
    106     }
    107 
    108     bool runOnFunction(Function &F);
    109 
    110     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    111       AU.addRequired<LazyValueInfo>();
    112       AU.addPreserved<LazyValueInfo>();
    113       AU.addRequired<TargetLibraryInfo>();
    114     }
    115 
    116     void FindLoopHeaders(Function &F);
    117     bool ProcessBlock(BasicBlock *BB);
    118     bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
    119                     BasicBlock *SuccBB);
    120     bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
    121                                   const SmallVectorImpl<BasicBlock *> &PredBBs);
    122 
    123     bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
    124                                          PredValueInfo &Result,
    125                                          ConstantPreference Preference);
    126     bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
    127                                 ConstantPreference Preference);
    128 
    129     bool ProcessBranchOnPHI(PHINode *PN);
    130     bool ProcessBranchOnXOR(BinaryOperator *BO);
    131 
    132     bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
    133     bool TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB);
    134   };
    135 }
    136 
    137 char JumpThreading::ID = 0;
    138 INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
    139                 "Jump Threading", false, false)
    140 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
    141 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
    142 INITIALIZE_PASS_END(JumpThreading, "jump-threading",
    143                 "Jump Threading", false, false)
    144 
    145 // Public interface to the Jump Threading pass
    146 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
    147 
    148 /// runOnFunction - Top level algorithm.
    149 ///
    150 bool JumpThreading::runOnFunction(Function &F) {
    151   DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
    152   TD = getAnalysisIfAvailable<DataLayout>();
    153   TLI = &getAnalysis<TargetLibraryInfo>();
    154   LVI = &getAnalysis<LazyValueInfo>();
    155 
    156   FindLoopHeaders(F);
    157 
    158   bool Changed, EverChanged = false;
    159   do {
    160     Changed = false;
    161     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
    162       BasicBlock *BB = I;
    163       // Thread all of the branches we can over this block.
    164       while (ProcessBlock(BB))
    165         Changed = true;
    166 
    167       ++I;
    168 
    169       // If the block is trivially dead, zap it.  This eliminates the successor
    170       // edges which simplifies the CFG.
    171       if (pred_begin(BB) == pred_end(BB) &&
    172           BB != &BB->getParent()->getEntryBlock()) {
    173         DEBUG(dbgs() << "  JT: Deleting dead block '" << BB->getName()
    174               << "' with terminator: " << *BB->getTerminator() << '\n');
    175         LoopHeaders.erase(BB);
    176         LVI->eraseBlock(BB);
    177         DeleteDeadBlock(BB);
    178         Changed = true;
    179         continue;
    180       }
    181 
    182       BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
    183 
    184       // Can't thread an unconditional jump, but if the block is "almost
    185       // empty", we can replace uses of it with uses of the successor and make
    186       // this dead.
    187       if (BI && BI->isUnconditional() &&
    188           BB != &BB->getParent()->getEntryBlock() &&
    189           // If the terminator is the only non-phi instruction, try to nuke it.
    190           BB->getFirstNonPHIOrDbg()->isTerminator()) {
    191         // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
    192         // block, we have to make sure it isn't in the LoopHeaders set.  We
    193         // reinsert afterward if needed.
    194         bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
    195         BasicBlock *Succ = BI->getSuccessor(0);
    196 
    197         // FIXME: It is always conservatively correct to drop the info
    198         // for a block even if it doesn't get erased.  This isn't totally
    199         // awesome, but it allows us to use AssertingVH to prevent nasty
    200         // dangling pointer issues within LazyValueInfo.
    201         LVI->eraseBlock(BB);
    202         if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
    203           Changed = true;
    204           // If we deleted BB and BB was the header of a loop, then the
    205           // successor is now the header of the loop.
    206           BB = Succ;
    207         }
    208 
    209         if (ErasedFromLoopHeaders)
    210           LoopHeaders.insert(BB);
    211       }
    212     }
    213     EverChanged |= Changed;
    214   } while (Changed);
    215 
    216   LoopHeaders.clear();
    217   return EverChanged;
    218 }
    219 
    220 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
    221 /// thread across it. Stop scanning the block when passing the threshold.
    222 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB,
    223                                              unsigned Threshold) {
    224   /// Ignore PHI nodes, these will be flattened when duplication happens.
    225   BasicBlock::const_iterator I = BB->getFirstNonPHI();
    226 
    227   // FIXME: THREADING will delete values that are just used to compute the
    228   // branch, so they shouldn't count against the duplication cost.
    229 
    230   // Sum up the cost of each instruction until we get to the terminator.  Don't
    231   // include the terminator because the copy won't include it.
    232   unsigned Size = 0;
    233   for (; !isa<TerminatorInst>(I); ++I) {
    234 
    235     // Stop scanning the block if we've reached the threshold.
    236     if (Size > Threshold)
    237       return Size;
    238 
    239     // Debugger intrinsics don't incur code size.
    240     if (isa<DbgInfoIntrinsic>(I)) continue;
    241 
    242     // If this is a pointer->pointer bitcast, it is free.
    243     if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
    244       continue;
    245 
    246     // All other instructions count for at least one unit.
    247     ++Size;
    248 
    249     // Calls are more expensive.  If they are non-intrinsic calls, we model them
    250     // as having cost of 4.  If they are a non-vector intrinsic, we model them
    251     // as having cost of 2 total, and if they are a vector intrinsic, we model
    252     // them as having cost 1.
    253     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
    254       if (CI->hasFnAttr(Attribute::NoDuplicate))
    255         // Blocks with NoDuplicate are modelled as having infinite cost, so they
    256         // are never duplicated.
    257         return ~0U;
    258       else if (!isa<IntrinsicInst>(CI))
    259         Size += 3;
    260       else if (!CI->getType()->isVectorTy())
    261         Size += 1;
    262     }
    263   }
    264 
    265   // Threading through a switch statement is particularly profitable.  If this
    266   // block ends in a switch, decrease its cost to make it more likely to happen.
    267   if (isa<SwitchInst>(I))
    268     Size = Size > 6 ? Size-6 : 0;
    269 
    270   // The same holds for indirect branches, but slightly more so.
    271   if (isa<IndirectBrInst>(I))
    272     Size = Size > 8 ? Size-8 : 0;
    273 
    274   return Size;
    275 }
    276 
    277 /// FindLoopHeaders - We do not want jump threading to turn proper loop
    278 /// structures into irreducible loops.  Doing this breaks up the loop nesting
    279 /// hierarchy and pessimizes later transformations.  To prevent this from
    280 /// happening, we first have to find the loop headers.  Here we approximate this
    281 /// by finding targets of backedges in the CFG.
    282 ///
    283 /// Note that there definitely are cases when we want to allow threading of
    284 /// edges across a loop header.  For example, threading a jump from outside the
    285 /// loop (the preheader) to an exit block of the loop is definitely profitable.
    286 /// It is also almost always profitable to thread backedges from within the loop
    287 /// to exit blocks, and is often profitable to thread backedges to other blocks
    288 /// within the loop (forming a nested loop).  This simple analysis is not rich
    289 /// enough to track all of these properties and keep it up-to-date as the CFG
    290 /// mutates, so we don't allow any of these transformations.
    291 ///
    292 void JumpThreading::FindLoopHeaders(Function &F) {
    293   SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
    294   FindFunctionBackedges(F, Edges);
    295 
    296   for (unsigned i = 0, e = Edges.size(); i != e; ++i)
    297     LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
    298 }
    299 
    300 /// getKnownConstant - Helper method to determine if we can thread over a
    301 /// terminator with the given value as its condition, and if so what value to
    302 /// use for that. What kind of value this is depends on whether we want an
    303 /// integer or a block address, but an undef is always accepted.
    304 /// Returns null if Val is null or not an appropriate constant.
    305 static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
    306   if (!Val)
    307     return 0;
    308 
    309   // Undef is "known" enough.
    310   if (UndefValue *U = dyn_cast<UndefValue>(Val))
    311     return U;
    312 
    313   if (Preference == WantBlockAddress)
    314     return dyn_cast<BlockAddress>(Val->stripPointerCasts());
    315 
    316   return dyn_cast<ConstantInt>(Val);
    317 }
    318 
    319 /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
    320 /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
    321 /// in any of our predecessors.  If so, return the known list of value and pred
    322 /// BB in the result vector.
    323 ///
    324 /// This returns true if there were any known values.
    325 ///
    326 bool JumpThreading::
    327 ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB, PredValueInfo &Result,
    328                                 ConstantPreference Preference) {
    329   // This method walks up use-def chains recursively.  Because of this, we could
    330   // get into an infinite loop going around loops in the use-def chain.  To
    331   // prevent this, keep track of what (value, block) pairs we've already visited
    332   // and terminate the search if we loop back to them
    333   if (!RecursionSet.insert(std::make_pair(V, BB)).second)
    334     return false;
    335 
    336   // An RAII help to remove this pair from the recursion set once the recursion
    337   // stack pops back out again.
    338   RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
    339 
    340   // If V is a constant, then it is known in all predecessors.
    341   if (Constant *KC = getKnownConstant(V, Preference)) {
    342     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
    343       Result.push_back(std::make_pair(KC, *PI));
    344 
    345     return true;
    346   }
    347 
    348   // If V is a non-instruction value, or an instruction in a different block,
    349   // then it can't be derived from a PHI.
    350   Instruction *I = dyn_cast<Instruction>(V);
    351   if (I == 0 || I->getParent() != BB) {
    352 
    353     // Okay, if this is a live-in value, see if it has a known value at the end
    354     // of any of our predecessors.
    355     //
    356     // FIXME: This should be an edge property, not a block end property.
    357     /// TODO: Per PR2563, we could infer value range information about a
    358     /// predecessor based on its terminator.
    359     //
    360     // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
    361     // "I" is a non-local compare-with-a-constant instruction.  This would be
    362     // able to handle value inequalities better, for example if the compare is
    363     // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
    364     // Perhaps getConstantOnEdge should be smart enough to do this?
    365 
    366     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
    367       BasicBlock *P = *PI;
    368       // If the value is known by LazyValueInfo to be a constant in a
    369       // predecessor, use that information to try to thread this block.
    370       Constant *PredCst = LVI->getConstantOnEdge(V, P, BB);
    371       if (Constant *KC = getKnownConstant(PredCst, Preference))
    372         Result.push_back(std::make_pair(KC, P));
    373     }
    374 
    375     return !Result.empty();
    376   }
    377 
    378   /// If I is a PHI node, then we know the incoming values for any constants.
    379   if (PHINode *PN = dyn_cast<PHINode>(I)) {
    380     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
    381       Value *InVal = PN->getIncomingValue(i);
    382       if (Constant *KC = getKnownConstant(InVal, Preference)) {
    383         Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
    384       } else {
    385         Constant *CI = LVI->getConstantOnEdge(InVal,
    386                                               PN->getIncomingBlock(i), BB);
    387         if (Constant *KC = getKnownConstant(CI, Preference))
    388           Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
    389       }
    390     }
    391 
    392     return !Result.empty();
    393   }
    394 
    395   PredValueInfoTy LHSVals, RHSVals;
    396 
    397   // Handle some boolean conditions.
    398   if (I->getType()->getPrimitiveSizeInBits() == 1) {
    399     assert(Preference == WantInteger && "One-bit non-integer type?");
    400     // X | true -> true
    401     // X & false -> false
    402     if (I->getOpcode() == Instruction::Or ||
    403         I->getOpcode() == Instruction::And) {
    404       ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
    405                                       WantInteger);
    406       ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals,
    407                                       WantInteger);
    408 
    409       if (LHSVals.empty() && RHSVals.empty())
    410         return false;
    411 
    412       ConstantInt *InterestingVal;
    413       if (I->getOpcode() == Instruction::Or)
    414         InterestingVal = ConstantInt::getTrue(I->getContext());
    415       else
    416         InterestingVal = ConstantInt::getFalse(I->getContext());
    417 
    418       SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
    419 
    420       // Scan for the sentinel.  If we find an undef, force it to the
    421       // interesting value: x|undef -> true and x&undef -> false.
    422       for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
    423         if (LHSVals[i].first == InterestingVal ||
    424             isa<UndefValue>(LHSVals[i].first)) {
    425           Result.push_back(LHSVals[i]);
    426           Result.back().first = InterestingVal;
    427           LHSKnownBBs.insert(LHSVals[i].second);
    428         }
    429       for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
    430         if (RHSVals[i].first == InterestingVal ||
    431             isa<UndefValue>(RHSVals[i].first)) {
    432           // If we already inferred a value for this block on the LHS, don't
    433           // re-add it.
    434           if (!LHSKnownBBs.count(RHSVals[i].second)) {
    435             Result.push_back(RHSVals[i]);
    436             Result.back().first = InterestingVal;
    437           }
    438         }
    439 
    440       return !Result.empty();
    441     }
    442 
    443     // Handle the NOT form of XOR.
    444     if (I->getOpcode() == Instruction::Xor &&
    445         isa<ConstantInt>(I->getOperand(1)) &&
    446         cast<ConstantInt>(I->getOperand(1))->isOne()) {
    447       ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result,
    448                                       WantInteger);
    449       if (Result.empty())
    450         return false;
    451 
    452       // Invert the known values.
    453       for (unsigned i = 0, e = Result.size(); i != e; ++i)
    454         Result[i].first = ConstantExpr::getNot(Result[i].first);
    455 
    456       return true;
    457     }
    458 
    459   // Try to simplify some other binary operator values.
    460   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
    461     assert(Preference != WantBlockAddress
    462             && "A binary operator creating a block address?");
    463     if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
    464       PredValueInfoTy LHSVals;
    465       ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals,
    466                                       WantInteger);
    467 
    468       // Try to use constant folding to simplify the binary operator.
    469       for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
    470         Constant *V = LHSVals[i].first;
    471         Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
    472 
    473         if (Constant *KC = getKnownConstant(Folded, WantInteger))
    474           Result.push_back(std::make_pair(KC, LHSVals[i].second));
    475       }
    476     }
    477 
    478     return !Result.empty();
    479   }
    480 
    481   // Handle compare with phi operand, where the PHI is defined in this block.
    482   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
    483     assert(Preference == WantInteger && "Compares only produce integers");
    484     PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
    485     if (PN && PN->getParent() == BB) {
    486       // We can do this simplification if any comparisons fold to true or false.
    487       // See if any do.
    488       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
    489         BasicBlock *PredBB = PN->getIncomingBlock(i);
    490         Value *LHS = PN->getIncomingValue(i);
    491         Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
    492 
    493         Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, TD);
    494         if (Res == 0) {
    495           if (!isa<Constant>(RHS))
    496             continue;
    497 
    498           LazyValueInfo::Tristate
    499             ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
    500                                            cast<Constant>(RHS), PredBB, BB);
    501           if (ResT == LazyValueInfo::Unknown)
    502             continue;
    503           Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
    504         }
    505 
    506         if (Constant *KC = getKnownConstant(Res, WantInteger))
    507           Result.push_back(std::make_pair(KC, PredBB));
    508       }
    509 
    510       return !Result.empty();
    511     }
    512 
    513 
    514     // If comparing a live-in value against a constant, see if we know the
    515     // live-in value on any predecessors.
    516     if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
    517       if (!isa<Instruction>(Cmp->getOperand(0)) ||
    518           cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
    519         Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
    520 
    521         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
    522           BasicBlock *P = *PI;
    523           // If the value is known by LazyValueInfo to be a constant in a
    524           // predecessor, use that information to try to thread this block.
    525           LazyValueInfo::Tristate Res =
    526             LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
    527                                     RHSCst, P, BB);
    528           if (Res == LazyValueInfo::Unknown)
    529             continue;
    530 
    531           Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
    532           Result.push_back(std::make_pair(ResC, P));
    533         }
    534 
    535         return !Result.empty();
    536       }
    537 
    538       // Try to find a constant value for the LHS of a comparison,
    539       // and evaluate it statically if we can.
    540       if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
    541         PredValueInfoTy LHSVals;
    542         ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
    543                                         WantInteger);
    544 
    545         for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
    546           Constant *V = LHSVals[i].first;
    547           Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
    548                                                       V, CmpConst);
    549           if (Constant *KC = getKnownConstant(Folded, WantInteger))
    550             Result.push_back(std::make_pair(KC, LHSVals[i].second));
    551         }
    552 
    553         return !Result.empty();
    554       }
    555     }
    556   }
    557 
    558   if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
    559     // Handle select instructions where at least one operand is a known constant
    560     // and we can figure out the condition value for any predecessor block.
    561     Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
    562     Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
    563     PredValueInfoTy Conds;
    564     if ((TrueVal || FalseVal) &&
    565         ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds,
    566                                         WantInteger)) {
    567       for (unsigned i = 0, e = Conds.size(); i != e; ++i) {
    568         Constant *Cond = Conds[i].first;
    569 
    570         // Figure out what value to use for the condition.
    571         bool KnownCond;
    572         if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
    573           // A known boolean.
    574           KnownCond = CI->isOne();
    575         } else {
    576           assert(isa<UndefValue>(Cond) && "Unexpected condition value");
    577           // Either operand will do, so be sure to pick the one that's a known
    578           // constant.
    579           // FIXME: Do this more cleverly if both values are known constants?
    580           KnownCond = (TrueVal != 0);
    581         }
    582 
    583         // See if the select has a known constant value for this predecessor.
    584         if (Constant *Val = KnownCond ? TrueVal : FalseVal)
    585           Result.push_back(std::make_pair(Val, Conds[i].second));
    586       }
    587 
    588       return !Result.empty();
    589     }
    590   }
    591 
    592   // If all else fails, see if LVI can figure out a constant value for us.
    593   Constant *CI = LVI->getConstant(V, BB);
    594   if (Constant *KC = getKnownConstant(CI, Preference)) {
    595     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
    596       Result.push_back(std::make_pair(KC, *PI));
    597   }
    598 
    599   return !Result.empty();
    600 }
    601 
    602 
    603 
    604 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
    605 /// in an undefined jump, decide which block is best to revector to.
    606 ///
    607 /// Since we can pick an arbitrary destination, we pick the successor with the
    608 /// fewest predecessors.  This should reduce the in-degree of the others.
    609 ///
    610 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
    611   TerminatorInst *BBTerm = BB->getTerminator();
    612   unsigned MinSucc = 0;
    613   BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
    614   // Compute the successor with the minimum number of predecessors.
    615   unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
    616   for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
    617     TestBB = BBTerm->getSuccessor(i);
    618     unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
    619     if (NumPreds < MinNumPreds) {
    620       MinSucc = i;
    621       MinNumPreds = NumPreds;
    622     }
    623   }
    624 
    625   return MinSucc;
    626 }
    627 
    628 static bool hasAddressTakenAndUsed(BasicBlock *BB) {
    629   if (!BB->hasAddressTaken()) return false;
    630 
    631   // If the block has its address taken, it may be a tree of dead constants
    632   // hanging off of it.  These shouldn't keep the block alive.
    633   BlockAddress *BA = BlockAddress::get(BB);
    634   BA->removeDeadConstantUsers();
    635   return !BA->use_empty();
    636 }
    637 
    638 /// ProcessBlock - If there are any predecessors whose control can be threaded
    639 /// through to a successor, transform them now.
    640 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
    641   // If the block is trivially dead, just return and let the caller nuke it.
    642   // This simplifies other transformations.
    643   if (pred_begin(BB) == pred_end(BB) &&
    644       BB != &BB->getParent()->getEntryBlock())
    645     return false;
    646 
    647   // If this block has a single predecessor, and if that pred has a single
    648   // successor, merge the blocks.  This encourages recursive jump threading
    649   // because now the condition in this block can be threaded through
    650   // predecessors of our predecessor block.
    651   if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
    652     if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
    653         SinglePred != BB && !hasAddressTakenAndUsed(BB)) {
    654       // If SinglePred was a loop header, BB becomes one.
    655       if (LoopHeaders.erase(SinglePred))
    656         LoopHeaders.insert(BB);
    657 
    658       // Remember if SinglePred was the entry block of the function.  If so, we
    659       // will need to move BB back to the entry position.
    660       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
    661       LVI->eraseBlock(SinglePred);
    662       MergeBasicBlockIntoOnlyPred(BB);
    663 
    664       if (isEntry && BB != &BB->getParent()->getEntryBlock())
    665         BB->moveBefore(&BB->getParent()->getEntryBlock());
    666       return true;
    667     }
    668   }
    669 
    670   // What kind of constant we're looking for.
    671   ConstantPreference Preference = WantInteger;
    672 
    673   // Look to see if the terminator is a conditional branch, switch or indirect
    674   // branch, if not we can't thread it.
    675   Value *Condition;
    676   Instruction *Terminator = BB->getTerminator();
    677   if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
    678     // Can't thread an unconditional jump.
    679     if (BI->isUnconditional()) return false;
    680     Condition = BI->getCondition();
    681   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
    682     Condition = SI->getCondition();
    683   } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
    684     // Can't thread indirect branch with no successors.
    685     if (IB->getNumSuccessors() == 0) return false;
    686     Condition = IB->getAddress()->stripPointerCasts();
    687     Preference = WantBlockAddress;
    688   } else {
    689     return false; // Must be an invoke.
    690   }
    691 
    692   // Run constant folding to see if we can reduce the condition to a simple
    693   // constant.
    694   if (Instruction *I = dyn_cast<Instruction>(Condition)) {
    695     Value *SimpleVal = ConstantFoldInstruction(I, TD, TLI);
    696     if (SimpleVal) {
    697       I->replaceAllUsesWith(SimpleVal);
    698       I->eraseFromParent();
    699       Condition = SimpleVal;
    700     }
    701   }
    702 
    703   // If the terminator is branching on an undef, we can pick any of the
    704   // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
    705   if (isa<UndefValue>(Condition)) {
    706     unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
    707 
    708     // Fold the branch/switch.
    709     TerminatorInst *BBTerm = BB->getTerminator();
    710     for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
    711       if (i == BestSucc) continue;
    712       BBTerm->getSuccessor(i)->removePredecessor(BB, true);
    713     }
    714 
    715     DEBUG(dbgs() << "  In block '" << BB->getName()
    716           << "' folding undef terminator: " << *BBTerm << '\n');
    717     BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
    718     BBTerm->eraseFromParent();
    719     return true;
    720   }
    721 
    722   // If the terminator of this block is branching on a constant, simplify the
    723   // terminator to an unconditional branch.  This can occur due to threading in
    724   // other blocks.
    725   if (getKnownConstant(Condition, Preference)) {
    726     DEBUG(dbgs() << "  In block '" << BB->getName()
    727           << "' folding terminator: " << *BB->getTerminator() << '\n');
    728     ++NumFolds;
    729     ConstantFoldTerminator(BB, true);
    730     return true;
    731   }
    732 
    733   Instruction *CondInst = dyn_cast<Instruction>(Condition);
    734 
    735   // All the rest of our checks depend on the condition being an instruction.
    736   if (CondInst == 0) {
    737     // FIXME: Unify this with code below.
    738     if (ProcessThreadableEdges(Condition, BB, Preference))
    739       return true;
    740     return false;
    741   }
    742 
    743 
    744   if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
    745     // For a comparison where the LHS is outside this block, it's possible
    746     // that we've branched on it before.  Used LVI to see if we can simplify
    747     // the branch based on that.
    748     BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
    749     Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
    750     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
    751     if (CondBr && CondConst && CondBr->isConditional() && PI != PE &&
    752         (!isa<Instruction>(CondCmp->getOperand(0)) ||
    753          cast<Instruction>(CondCmp->getOperand(0))->getParent() != BB)) {
    754       // For predecessor edge, determine if the comparison is true or false
    755       // on that edge.  If they're all true or all false, we can simplify the
    756       // branch.
    757       // FIXME: We could handle mixed true/false by duplicating code.
    758       LazyValueInfo::Tristate Baseline =
    759         LVI->getPredicateOnEdge(CondCmp->getPredicate(), CondCmp->getOperand(0),
    760                                 CondConst, *PI, BB);
    761       if (Baseline != LazyValueInfo::Unknown) {
    762         // Check that all remaining incoming values match the first one.
    763         while (++PI != PE) {
    764           LazyValueInfo::Tristate Ret =
    765             LVI->getPredicateOnEdge(CondCmp->getPredicate(),
    766                                     CondCmp->getOperand(0), CondConst, *PI, BB);
    767           if (Ret != Baseline) break;
    768         }
    769 
    770         // If we terminated early, then one of the values didn't match.
    771         if (PI == PE) {
    772           unsigned ToRemove = Baseline == LazyValueInfo::True ? 1 : 0;
    773           unsigned ToKeep = Baseline == LazyValueInfo::True ? 0 : 1;
    774           CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
    775           BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
    776           CondBr->eraseFromParent();
    777           return true;
    778         }
    779       }
    780 
    781     }
    782 
    783     if (CondBr && CondConst && TryToUnfoldSelect(CondCmp, BB))
    784       return true;
    785   }
    786 
    787   // Check for some cases that are worth simplifying.  Right now we want to look
    788   // for loads that are used by a switch or by the condition for the branch.  If
    789   // we see one, check to see if it's partially redundant.  If so, insert a PHI
    790   // which can then be used to thread the values.
    791   //
    792   Value *SimplifyValue = CondInst;
    793   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
    794     if (isa<Constant>(CondCmp->getOperand(1)))
    795       SimplifyValue = CondCmp->getOperand(0);
    796 
    797   // TODO: There are other places where load PRE would be profitable, such as
    798   // more complex comparisons.
    799   if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
    800     if (SimplifyPartiallyRedundantLoad(LI))
    801       return true;
    802 
    803 
    804   // Handle a variety of cases where we are branching on something derived from
    805   // a PHI node in the current block.  If we can prove that any predecessors
    806   // compute a predictable value based on a PHI node, thread those predecessors.
    807   //
    808   if (ProcessThreadableEdges(CondInst, BB, Preference))
    809     return true;
    810 
    811   // If this is an otherwise-unfoldable branch on a phi node in the current
    812   // block, see if we can simplify.
    813   if (PHINode *PN = dyn_cast<PHINode>(CondInst))
    814     if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
    815       return ProcessBranchOnPHI(PN);
    816 
    817 
    818   // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
    819   if (CondInst->getOpcode() == Instruction::Xor &&
    820       CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
    821     return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
    822 
    823 
    824   // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
    825   // "(X == 4)", thread through this block.
    826 
    827   return false;
    828 }
    829 
    830 
    831 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
    832 /// load instruction, eliminate it by replacing it with a PHI node.  This is an
    833 /// important optimization that encourages jump threading, and needs to be run
    834 /// interlaced with other jump threading tasks.
    835 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
    836   // Don't hack volatile/atomic loads.
    837   if (!LI->isSimple()) return false;
    838 
    839   // If the load is defined in a block with exactly one predecessor, it can't be
    840   // partially redundant.
    841   BasicBlock *LoadBB = LI->getParent();
    842   if (LoadBB->getSinglePredecessor())
    843     return false;
    844 
    845   Value *LoadedPtr = LI->getOperand(0);
    846 
    847   // If the loaded operand is defined in the LoadBB, it can't be available.
    848   // TODO: Could do simple PHI translation, that would be fun :)
    849   if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
    850     if (PtrOp->getParent() == LoadBB)
    851       return false;
    852 
    853   // Scan a few instructions up from the load, to see if it is obviously live at
    854   // the entry to its block.
    855   BasicBlock::iterator BBIt = LI;
    856 
    857   if (Value *AvailableVal =
    858         FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
    859     // If the value if the load is locally available within the block, just use
    860     // it.  This frequently occurs for reg2mem'd allocas.
    861     //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
    862 
    863     // If the returned value is the load itself, replace with an undef. This can
    864     // only happen in dead loops.
    865     if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
    866     LI->replaceAllUsesWith(AvailableVal);
    867     LI->eraseFromParent();
    868     return true;
    869   }
    870 
    871   // Otherwise, if we scanned the whole block and got to the top of the block,
    872   // we know the block is locally transparent to the load.  If not, something
    873   // might clobber its value.
    874   if (BBIt != LoadBB->begin())
    875     return false;
    876 
    877   // If all of the loads and stores that feed the value have the same TBAA tag,
    878   // then we can propagate it onto any newly inserted loads.
    879   MDNode *TBAATag = LI->getMetadata(LLVMContext::MD_tbaa);
    880 
    881   SmallPtrSet<BasicBlock*, 8> PredsScanned;
    882   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
    883   AvailablePredsTy AvailablePreds;
    884   BasicBlock *OneUnavailablePred = 0;
    885 
    886   // If we got here, the loaded value is transparent through to the start of the
    887   // block.  Check to see if it is available in any of the predecessor blocks.
    888   for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
    889        PI != PE; ++PI) {
    890     BasicBlock *PredBB = *PI;
    891 
    892     // If we already scanned this predecessor, skip it.
    893     if (!PredsScanned.insert(PredBB))
    894       continue;
    895 
    896     // Scan the predecessor to see if the value is available in the pred.
    897     BBIt = PredBB->end();
    898     MDNode *ThisTBAATag = 0;
    899     Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6,
    900                                                     0, &ThisTBAATag);
    901     if (!PredAvailable) {
    902       OneUnavailablePred = PredBB;
    903       continue;
    904     }
    905 
    906     // If tbaa tags disagree or are not present, forget about them.
    907     if (TBAATag != ThisTBAATag) TBAATag = 0;
    908 
    909     // If so, this load is partially redundant.  Remember this info so that we
    910     // can create a PHI node.
    911     AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
    912   }
    913 
    914   // If the loaded value isn't available in any predecessor, it isn't partially
    915   // redundant.
    916   if (AvailablePreds.empty()) return false;
    917 
    918   // Okay, the loaded value is available in at least one (and maybe all!)
    919   // predecessors.  If the value is unavailable in more than one unique
    920   // predecessor, we want to insert a merge block for those common predecessors.
    921   // This ensures that we only have to insert one reload, thus not increasing
    922   // code size.
    923   BasicBlock *UnavailablePred = 0;
    924 
    925   // If there is exactly one predecessor where the value is unavailable, the
    926   // already computed 'OneUnavailablePred' block is it.  If it ends in an
    927   // unconditional branch, we know that it isn't a critical edge.
    928   if (PredsScanned.size() == AvailablePreds.size()+1 &&
    929       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
    930     UnavailablePred = OneUnavailablePred;
    931   } else if (PredsScanned.size() != AvailablePreds.size()) {
    932     // Otherwise, we had multiple unavailable predecessors or we had a critical
    933     // edge from the one.
    934     SmallVector<BasicBlock*, 8> PredsToSplit;
    935     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
    936 
    937     for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
    938       AvailablePredSet.insert(AvailablePreds[i].first);
    939 
    940     // Add all the unavailable predecessors to the PredsToSplit list.
    941     for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
    942          PI != PE; ++PI) {
    943       BasicBlock *P = *PI;
    944       // If the predecessor is an indirect goto, we can't split the edge.
    945       if (isa<IndirectBrInst>(P->getTerminator()))
    946         return false;
    947 
    948       if (!AvailablePredSet.count(P))
    949         PredsToSplit.push_back(P);
    950     }
    951 
    952     // Split them out to their own block.
    953     UnavailablePred =
    954       SplitBlockPredecessors(LoadBB, PredsToSplit, "thread-pre-split", this);
    955   }
    956 
    957   // If the value isn't available in all predecessors, then there will be
    958   // exactly one where it isn't available.  Insert a load on that edge and add
    959   // it to the AvailablePreds list.
    960   if (UnavailablePred) {
    961     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
    962            "Can't handle critical edge here!");
    963     LoadInst *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
    964                                  LI->getAlignment(),
    965                                  UnavailablePred->getTerminator());
    966     NewVal->setDebugLoc(LI->getDebugLoc());
    967     if (TBAATag)
    968       NewVal->setMetadata(LLVMContext::MD_tbaa, TBAATag);
    969 
    970     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
    971   }
    972 
    973   // Now we know that each predecessor of this block has a value in
    974   // AvailablePreds, sort them for efficient access as we're walking the preds.
    975   array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
    976 
    977   // Create a PHI node at the start of the block for the PRE'd load value.
    978   pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
    979   PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
    980                                 LoadBB->begin());
    981   PN->takeName(LI);
    982   PN->setDebugLoc(LI->getDebugLoc());
    983 
    984   // Insert new entries into the PHI for each predecessor.  A single block may
    985   // have multiple entries here.
    986   for (pred_iterator PI = PB; PI != PE; ++PI) {
    987     BasicBlock *P = *PI;
    988     AvailablePredsTy::iterator I =
    989       std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
    990                        std::make_pair(P, (Value*)0));
    991 
    992     assert(I != AvailablePreds.end() && I->first == P &&
    993            "Didn't find entry for predecessor!");
    994 
    995     PN->addIncoming(I->second, I->first);
    996   }
    997 
    998   //cerr << "PRE: " << *LI << *PN << "\n";
    999 
   1000   LI->replaceAllUsesWith(PN);
   1001   LI->eraseFromParent();
   1002 
   1003   return true;
   1004 }
   1005 
   1006 /// FindMostPopularDest - The specified list contains multiple possible
   1007 /// threadable destinations.  Pick the one that occurs the most frequently in
   1008 /// the list.
   1009 static BasicBlock *
   1010 FindMostPopularDest(BasicBlock *BB,
   1011                     const SmallVectorImpl<std::pair<BasicBlock*,
   1012                                   BasicBlock*> > &PredToDestList) {
   1013   assert(!PredToDestList.empty());
   1014 
   1015   // Determine popularity.  If there are multiple possible destinations, we
   1016   // explicitly choose to ignore 'undef' destinations.  We prefer to thread
   1017   // blocks with known and real destinations to threading undef.  We'll handle
   1018   // them later if interesting.
   1019   DenseMap<BasicBlock*, unsigned> DestPopularity;
   1020   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
   1021     if (PredToDestList[i].second)
   1022       DestPopularity[PredToDestList[i].second]++;
   1023 
   1024   // Find the most popular dest.
   1025   DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
   1026   BasicBlock *MostPopularDest = DPI->first;
   1027   unsigned Popularity = DPI->second;
   1028   SmallVector<BasicBlock*, 4> SamePopularity;
   1029 
   1030   for (++DPI; DPI != DestPopularity.end(); ++DPI) {
   1031     // If the popularity of this entry isn't higher than the popularity we've
   1032     // seen so far, ignore it.
   1033     if (DPI->second < Popularity)
   1034       ; // ignore.
   1035     else if (DPI->second == Popularity) {
   1036       // If it is the same as what we've seen so far, keep track of it.
   1037       SamePopularity.push_back(DPI->first);
   1038     } else {
   1039       // If it is more popular, remember it.
   1040       SamePopularity.clear();
   1041       MostPopularDest = DPI->first;
   1042       Popularity = DPI->second;
   1043     }
   1044   }
   1045 
   1046   // Okay, now we know the most popular destination.  If there is more than one
   1047   // destination, we need to determine one.  This is arbitrary, but we need
   1048   // to make a deterministic decision.  Pick the first one that appears in the
   1049   // successor list.
   1050   if (!SamePopularity.empty()) {
   1051     SamePopularity.push_back(MostPopularDest);
   1052     TerminatorInst *TI = BB->getTerminator();
   1053     for (unsigned i = 0; ; ++i) {
   1054       assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
   1055 
   1056       if (std::find(SamePopularity.begin(), SamePopularity.end(),
   1057                     TI->getSuccessor(i)) == SamePopularity.end())
   1058         continue;
   1059 
   1060       MostPopularDest = TI->getSuccessor(i);
   1061       break;
   1062     }
   1063   }
   1064 
   1065   // Okay, we have finally picked the most popular destination.
   1066   return MostPopularDest;
   1067 }
   1068 
   1069 bool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
   1070                                            ConstantPreference Preference) {
   1071   // If threading this would thread across a loop header, don't even try to
   1072   // thread the edge.
   1073   if (LoopHeaders.count(BB))
   1074     return false;
   1075 
   1076   PredValueInfoTy PredValues;
   1077   if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference))
   1078     return false;
   1079 
   1080   assert(!PredValues.empty() &&
   1081          "ComputeValueKnownInPredecessors returned true with no values");
   1082 
   1083   DEBUG(dbgs() << "IN BB: " << *BB;
   1084         for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
   1085           dbgs() << "  BB '" << BB->getName() << "': FOUND condition = "
   1086             << *PredValues[i].first
   1087             << " for pred '" << PredValues[i].second->getName() << "'.\n";
   1088         });
   1089 
   1090   // Decide what we want to thread through.  Convert our list of known values to
   1091   // a list of known destinations for each pred.  This also discards duplicate
   1092   // predecessors and keeps track of the undefined inputs (which are represented
   1093   // as a null dest in the PredToDestList).
   1094   SmallPtrSet<BasicBlock*, 16> SeenPreds;
   1095   SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
   1096 
   1097   BasicBlock *OnlyDest = 0;
   1098   BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
   1099 
   1100   for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
   1101     BasicBlock *Pred = PredValues[i].second;
   1102     if (!SeenPreds.insert(Pred))
   1103       continue;  // Duplicate predecessor entry.
   1104 
   1105     // If the predecessor ends with an indirect goto, we can't change its
   1106     // destination.
   1107     if (isa<IndirectBrInst>(Pred->getTerminator()))
   1108       continue;
   1109 
   1110     Constant *Val = PredValues[i].first;
   1111 
   1112     BasicBlock *DestBB;
   1113     if (isa<UndefValue>(Val))
   1114       DestBB = 0;
   1115     else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
   1116       DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
   1117     else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
   1118       DestBB = SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccessor();
   1119     } else {
   1120       assert(isa<IndirectBrInst>(BB->getTerminator())
   1121               && "Unexpected terminator");
   1122       DestBB = cast<BlockAddress>(Val)->getBasicBlock();
   1123     }
   1124 
   1125     // If we have exactly one destination, remember it for efficiency below.
   1126     if (PredToDestList.empty())
   1127       OnlyDest = DestBB;
   1128     else if (OnlyDest != DestBB)
   1129       OnlyDest = MultipleDestSentinel;
   1130 
   1131     PredToDestList.push_back(std::make_pair(Pred, DestBB));
   1132   }
   1133 
   1134   // If all edges were unthreadable, we fail.
   1135   if (PredToDestList.empty())
   1136     return false;
   1137 
   1138   // Determine which is the most common successor.  If we have many inputs and
   1139   // this block is a switch, we want to start by threading the batch that goes
   1140   // to the most popular destination first.  If we only know about one
   1141   // threadable destination (the common case) we can avoid this.
   1142   BasicBlock *MostPopularDest = OnlyDest;
   1143 
   1144   if (MostPopularDest == MultipleDestSentinel)
   1145     MostPopularDest = FindMostPopularDest(BB, PredToDestList);
   1146 
   1147   // Now that we know what the most popular destination is, factor all
   1148   // predecessors that will jump to it into a single predecessor.
   1149   SmallVector<BasicBlock*, 16> PredsToFactor;
   1150   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
   1151     if (PredToDestList[i].second == MostPopularDest) {
   1152       BasicBlock *Pred = PredToDestList[i].first;
   1153 
   1154       // This predecessor may be a switch or something else that has multiple
   1155       // edges to the block.  Factor each of these edges by listing them
   1156       // according to # occurrences in PredsToFactor.
   1157       TerminatorInst *PredTI = Pred->getTerminator();
   1158       for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
   1159         if (PredTI->getSuccessor(i) == BB)
   1160           PredsToFactor.push_back(Pred);
   1161     }
   1162 
   1163   // If the threadable edges are branching on an undefined value, we get to pick
   1164   // the destination that these predecessors should get to.
   1165   if (MostPopularDest == 0)
   1166     MostPopularDest = BB->getTerminator()->
   1167                             getSuccessor(GetBestDestForJumpOnUndef(BB));
   1168 
   1169   // Ok, try to thread it!
   1170   return ThreadEdge(BB, PredsToFactor, MostPopularDest);
   1171 }
   1172 
   1173 /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
   1174 /// a PHI node in the current block.  See if there are any simplifications we
   1175 /// can do based on inputs to the phi node.
   1176 ///
   1177 bool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
   1178   BasicBlock *BB = PN->getParent();
   1179 
   1180   // TODO: We could make use of this to do it once for blocks with common PHI
   1181   // values.
   1182   SmallVector<BasicBlock*, 1> PredBBs;
   1183   PredBBs.resize(1);
   1184 
   1185   // If any of the predecessor blocks end in an unconditional branch, we can
   1186   // *duplicate* the conditional branch into that block in order to further
   1187   // encourage jump threading and to eliminate cases where we have branch on a
   1188   // phi of an icmp (branch on icmp is much better).
   1189   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
   1190     BasicBlock *PredBB = PN->getIncomingBlock(i);
   1191     if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
   1192       if (PredBr->isUnconditional()) {
   1193         PredBBs[0] = PredBB;
   1194         // Try to duplicate BB into PredBB.
   1195         if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
   1196           return true;
   1197       }
   1198   }
   1199 
   1200   return false;
   1201 }
   1202 
   1203 /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
   1204 /// a xor instruction in the current block.  See if there are any
   1205 /// simplifications we can do based on inputs to the xor.
   1206 ///
   1207 bool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
   1208   BasicBlock *BB = BO->getParent();
   1209 
   1210   // If either the LHS or RHS of the xor is a constant, don't do this
   1211   // optimization.
   1212   if (isa<ConstantInt>(BO->getOperand(0)) ||
   1213       isa<ConstantInt>(BO->getOperand(1)))
   1214     return false;
   1215 
   1216   // If the first instruction in BB isn't a phi, we won't be able to infer
   1217   // anything special about any particular predecessor.
   1218   if (!isa<PHINode>(BB->front()))
   1219     return false;
   1220 
   1221   // If we have a xor as the branch input to this block, and we know that the
   1222   // LHS or RHS of the xor in any predecessor is true/false, then we can clone
   1223   // the condition into the predecessor and fix that value to true, saving some
   1224   // logical ops on that path and encouraging other paths to simplify.
   1225   //
   1226   // This copies something like this:
   1227   //
   1228   //  BB:
   1229   //    %X = phi i1 [1],  [%X']
   1230   //    %Y = icmp eq i32 %A, %B
   1231   //    %Z = xor i1 %X, %Y
   1232   //    br i1 %Z, ...
   1233   //
   1234   // Into:
   1235   //  BB':
   1236   //    %Y = icmp ne i32 %A, %B
   1237   //    br i1 %Z, ...
   1238 
   1239   PredValueInfoTy XorOpValues;
   1240   bool isLHS = true;
   1241   if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
   1242                                        WantInteger)) {
   1243     assert(XorOpValues.empty());
   1244     if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
   1245                                          WantInteger))
   1246       return false;
   1247     isLHS = false;
   1248   }
   1249 
   1250   assert(!XorOpValues.empty() &&
   1251          "ComputeValueKnownInPredecessors returned true with no values");
   1252 
   1253   // Scan the information to see which is most popular: true or false.  The
   1254   // predecessors can be of the set true, false, or undef.
   1255   unsigned NumTrue = 0, NumFalse = 0;
   1256   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
   1257     if (isa<UndefValue>(XorOpValues[i].first))
   1258       // Ignore undefs for the count.
   1259       continue;
   1260     if (cast<ConstantInt>(XorOpValues[i].first)->isZero())
   1261       ++NumFalse;
   1262     else
   1263       ++NumTrue;
   1264   }
   1265 
   1266   // Determine which value to split on, true, false, or undef if neither.
   1267   ConstantInt *SplitVal = 0;
   1268   if (NumTrue > NumFalse)
   1269     SplitVal = ConstantInt::getTrue(BB->getContext());
   1270   else if (NumTrue != 0 || NumFalse != 0)
   1271     SplitVal = ConstantInt::getFalse(BB->getContext());
   1272 
   1273   // Collect all of the blocks that this can be folded into so that we can
   1274   // factor this once and clone it once.
   1275   SmallVector<BasicBlock*, 8> BlocksToFoldInto;
   1276   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
   1277     if (XorOpValues[i].first != SplitVal &&
   1278         !isa<UndefValue>(XorOpValues[i].first))
   1279       continue;
   1280 
   1281     BlocksToFoldInto.push_back(XorOpValues[i].second);
   1282   }
   1283 
   1284   // If we inferred a value for all of the predecessors, then duplication won't
   1285   // help us.  However, we can just replace the LHS or RHS with the constant.
   1286   if (BlocksToFoldInto.size() ==
   1287       cast<PHINode>(BB->front()).getNumIncomingValues()) {
   1288     if (SplitVal == 0) {
   1289       // If all preds provide undef, just nuke the xor, because it is undef too.
   1290       BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
   1291       BO->eraseFromParent();
   1292     } else if (SplitVal->isZero()) {
   1293       // If all preds provide 0, replace the xor with the other input.
   1294       BO->replaceAllUsesWith(BO->getOperand(isLHS));
   1295       BO->eraseFromParent();
   1296     } else {
   1297       // If all preds provide 1, set the computed value to 1.
   1298       BO->setOperand(!isLHS, SplitVal);
   1299     }
   1300 
   1301     return true;
   1302   }
   1303 
   1304   // Try to duplicate BB into PredBB.
   1305   return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
   1306 }
   1307 
   1308 
   1309 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
   1310 /// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
   1311 /// NewPred using the entries from OldPred (suitably mapped).
   1312 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
   1313                                             BasicBlock *OldPred,
   1314                                             BasicBlock *NewPred,
   1315                                      DenseMap<Instruction*, Value*> &ValueMap) {
   1316   for (BasicBlock::iterator PNI = PHIBB->begin();
   1317        PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
   1318     // Ok, we have a PHI node.  Figure out what the incoming value was for the
   1319     // DestBlock.
   1320     Value *IV = PN->getIncomingValueForBlock(OldPred);
   1321 
   1322     // Remap the value if necessary.
   1323     if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
   1324       DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
   1325       if (I != ValueMap.end())
   1326         IV = I->second;
   1327     }
   1328 
   1329     PN->addIncoming(IV, NewPred);
   1330   }
   1331 }
   1332 
   1333 /// ThreadEdge - We have decided that it is safe and profitable to factor the
   1334 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
   1335 /// across BB.  Transform the IR to reflect this change.
   1336 bool JumpThreading::ThreadEdge(BasicBlock *BB,
   1337                                const SmallVectorImpl<BasicBlock*> &PredBBs,
   1338                                BasicBlock *SuccBB) {
   1339   // If threading to the same block as we come from, we would infinite loop.
   1340   if (SuccBB == BB) {
   1341     DEBUG(dbgs() << "  Not threading across BB '" << BB->getName()
   1342           << "' - would thread to self!\n");
   1343     return false;
   1344   }
   1345 
   1346   // If threading this would thread across a loop header, don't thread the edge.
   1347   // See the comments above FindLoopHeaders for justifications and caveats.
   1348   if (LoopHeaders.count(BB)) {
   1349     DEBUG(dbgs() << "  Not threading across loop header BB '" << BB->getName()
   1350           << "' to dest BB '" << SuccBB->getName()
   1351           << "' - it might create an irreducible loop!\n");
   1352     return false;
   1353   }
   1354 
   1355   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB, Threshold);
   1356   if (JumpThreadCost > Threshold) {
   1357     DEBUG(dbgs() << "  Not threading BB '" << BB->getName()
   1358           << "' - Cost is too high: " << JumpThreadCost << "\n");
   1359     return false;
   1360   }
   1361 
   1362   // And finally, do it!  Start by factoring the predecessors is needed.
   1363   BasicBlock *PredBB;
   1364   if (PredBBs.size() == 1)
   1365     PredBB = PredBBs[0];
   1366   else {
   1367     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
   1368           << " common predecessors.\n");
   1369     PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
   1370   }
   1371 
   1372   // And finally, do it!
   1373   DEBUG(dbgs() << "  Threading edge from '" << PredBB->getName() << "' to '"
   1374         << SuccBB->getName() << "' with cost: " << JumpThreadCost
   1375         << ", across block:\n    "
   1376         << *BB << "\n");
   1377 
   1378   LVI->threadEdge(PredBB, BB, SuccBB);
   1379 
   1380   // We are going to have to map operands from the original BB block to the new
   1381   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
   1382   // account for entry from PredBB.
   1383   DenseMap<Instruction*, Value*> ValueMapping;
   1384 
   1385   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
   1386                                          BB->getName()+".thread",
   1387                                          BB->getParent(), BB);
   1388   NewBB->moveAfter(PredBB);
   1389 
   1390   BasicBlock::iterator BI = BB->begin();
   1391   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
   1392     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
   1393 
   1394   // Clone the non-phi instructions of BB into NewBB, keeping track of the
   1395   // mapping and using it to remap operands in the cloned instructions.
   1396   for (; !isa<TerminatorInst>(BI); ++BI) {
   1397     Instruction *New = BI->clone();
   1398     New->setName(BI->getName());
   1399     NewBB->getInstList().push_back(New);
   1400     ValueMapping[BI] = New;
   1401 
   1402     // Remap operands to patch up intra-block references.
   1403     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
   1404       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
   1405         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
   1406         if (I != ValueMapping.end())
   1407           New->setOperand(i, I->second);
   1408       }
   1409   }
   1410 
   1411   // We didn't copy the terminator from BB over to NewBB, because there is now
   1412   // an unconditional jump to SuccBB.  Insert the unconditional jump.
   1413   BranchInst *NewBI =BranchInst::Create(SuccBB, NewBB);
   1414   NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
   1415 
   1416   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
   1417   // PHI nodes for NewBB now.
   1418   AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
   1419 
   1420   // If there were values defined in BB that are used outside the block, then we
   1421   // now have to update all uses of the value to use either the original value,
   1422   // the cloned value, or some PHI derived value.  This can require arbitrary
   1423   // PHI insertion, of which we are prepared to do, clean these up now.
   1424   SSAUpdater SSAUpdate;
   1425   SmallVector<Use*, 16> UsesToRename;
   1426   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
   1427     // Scan all uses of this instruction to see if it is used outside of its
   1428     // block, and if so, record them in UsesToRename.
   1429     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
   1430          ++UI) {
   1431       Instruction *User = cast<Instruction>(*UI);
   1432       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
   1433         if (UserPN->getIncomingBlock(UI) == BB)
   1434           continue;
   1435       } else if (User->getParent() == BB)
   1436         continue;
   1437 
   1438       UsesToRename.push_back(&UI.getUse());
   1439     }
   1440 
   1441     // If there are no uses outside the block, we're done with this instruction.
   1442     if (UsesToRename.empty())
   1443       continue;
   1444 
   1445     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
   1446 
   1447     // We found a use of I outside of BB.  Rename all uses of I that are outside
   1448     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
   1449     // with the two values we know.
   1450     SSAUpdate.Initialize(I->getType(), I->getName());
   1451     SSAUpdate.AddAvailableValue(BB, I);
   1452     SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
   1453 
   1454     while (!UsesToRename.empty())
   1455       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
   1456     DEBUG(dbgs() << "\n");
   1457   }
   1458 
   1459 
   1460   // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
   1461   // NewBB instead of BB.  This eliminates predecessors from BB, which requires
   1462   // us to simplify any PHI nodes in BB.
   1463   TerminatorInst *PredTerm = PredBB->getTerminator();
   1464   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
   1465     if (PredTerm->getSuccessor(i) == BB) {
   1466       BB->removePredecessor(PredBB, true);
   1467       PredTerm->setSuccessor(i, NewBB);
   1468     }
   1469 
   1470   // At this point, the IR is fully up to date and consistent.  Do a quick scan
   1471   // over the new instructions and zap any that are constants or dead.  This
   1472   // frequently happens because of phi translation.
   1473   SimplifyInstructionsInBlock(NewBB, TD, TLI);
   1474 
   1475   // Threaded an edge!
   1476   ++NumThreads;
   1477   return true;
   1478 }
   1479 
   1480 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
   1481 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
   1482 /// If we can duplicate the contents of BB up into PredBB do so now, this
   1483 /// improves the odds that the branch will be on an analyzable instruction like
   1484 /// a compare.
   1485 bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
   1486                                  const SmallVectorImpl<BasicBlock *> &PredBBs) {
   1487   assert(!PredBBs.empty() && "Can't handle an empty set");
   1488 
   1489   // If BB is a loop header, then duplicating this block outside the loop would
   1490   // cause us to transform this into an irreducible loop, don't do this.
   1491   // See the comments above FindLoopHeaders for justifications and caveats.
   1492   if (LoopHeaders.count(BB)) {
   1493     DEBUG(dbgs() << "  Not duplicating loop header '" << BB->getName()
   1494           << "' into predecessor block '" << PredBBs[0]->getName()
   1495           << "' - it might create an irreducible loop!\n");
   1496     return false;
   1497   }
   1498 
   1499   unsigned DuplicationCost = getJumpThreadDuplicationCost(BB, Threshold);
   1500   if (DuplicationCost > Threshold) {
   1501     DEBUG(dbgs() << "  Not duplicating BB '" << BB->getName()
   1502           << "' - Cost is too high: " << DuplicationCost << "\n");
   1503     return false;
   1504   }
   1505 
   1506   // And finally, do it!  Start by factoring the predecessors is needed.
   1507   BasicBlock *PredBB;
   1508   if (PredBBs.size() == 1)
   1509     PredBB = PredBBs[0];
   1510   else {
   1511     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
   1512           << " common predecessors.\n");
   1513     PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
   1514   }
   1515 
   1516   // Okay, we decided to do this!  Clone all the instructions in BB onto the end
   1517   // of PredBB.
   1518   DEBUG(dbgs() << "  Duplicating block '" << BB->getName() << "' into end of '"
   1519         << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
   1520         << DuplicationCost << " block is:" << *BB << "\n");
   1521 
   1522   // Unless PredBB ends with an unconditional branch, split the edge so that we
   1523   // can just clone the bits from BB into the end of the new PredBB.
   1524   BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
   1525 
   1526   if (OldPredBranch == 0 || !OldPredBranch->isUnconditional()) {
   1527     PredBB = SplitEdge(PredBB, BB, this);
   1528     OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
   1529   }
   1530 
   1531   // We are going to have to map operands from the original BB block into the
   1532   // PredBB block.  Evaluate PHI nodes in BB.
   1533   DenseMap<Instruction*, Value*> ValueMapping;
   1534 
   1535   BasicBlock::iterator BI = BB->begin();
   1536   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
   1537     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
   1538 
   1539   // Clone the non-phi instructions of BB into PredBB, keeping track of the
   1540   // mapping and using it to remap operands in the cloned instructions.
   1541   for (; BI != BB->end(); ++BI) {
   1542     Instruction *New = BI->clone();
   1543 
   1544     // Remap operands to patch up intra-block references.
   1545     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
   1546       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
   1547         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
   1548         if (I != ValueMapping.end())
   1549           New->setOperand(i, I->second);
   1550       }
   1551 
   1552     // If this instruction can be simplified after the operands are updated,
   1553     // just use the simplified value instead.  This frequently happens due to
   1554     // phi translation.
   1555     if (Value *IV = SimplifyInstruction(New, TD)) {
   1556       delete New;
   1557       ValueMapping[BI] = IV;
   1558     } else {
   1559       // Otherwise, insert the new instruction into the block.
   1560       New->setName(BI->getName());
   1561       PredBB->getInstList().insert(OldPredBranch, New);
   1562       ValueMapping[BI] = New;
   1563     }
   1564   }
   1565 
   1566   // Check to see if the targets of the branch had PHI nodes. If so, we need to
   1567   // add entries to the PHI nodes for branch from PredBB now.
   1568   BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
   1569   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
   1570                                   ValueMapping);
   1571   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
   1572                                   ValueMapping);
   1573 
   1574   // If there were values defined in BB that are used outside the block, then we
   1575   // now have to update all uses of the value to use either the original value,
   1576   // the cloned value, or some PHI derived value.  This can require arbitrary
   1577   // PHI insertion, of which we are prepared to do, clean these up now.
   1578   SSAUpdater SSAUpdate;
   1579   SmallVector<Use*, 16> UsesToRename;
   1580   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
   1581     // Scan all uses of this instruction to see if it is used outside of its
   1582     // block, and if so, record them in UsesToRename.
   1583     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
   1584          ++UI) {
   1585       Instruction *User = cast<Instruction>(*UI);
   1586       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
   1587         if (UserPN->getIncomingBlock(UI) == BB)
   1588           continue;
   1589       } else if (User->getParent() == BB)
   1590         continue;
   1591 
   1592       UsesToRename.push_back(&UI.getUse());
   1593     }
   1594 
   1595     // If there are no uses outside the block, we're done with this instruction.
   1596     if (UsesToRename.empty())
   1597       continue;
   1598 
   1599     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
   1600 
   1601     // We found a use of I outside of BB.  Rename all uses of I that are outside
   1602     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
   1603     // with the two values we know.
   1604     SSAUpdate.Initialize(I->getType(), I->getName());
   1605     SSAUpdate.AddAvailableValue(BB, I);
   1606     SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
   1607 
   1608     while (!UsesToRename.empty())
   1609       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
   1610     DEBUG(dbgs() << "\n");
   1611   }
   1612 
   1613   // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
   1614   // that we nuked.
   1615   BB->removePredecessor(PredBB, true);
   1616 
   1617   // Remove the unconditional branch at the end of the PredBB block.
   1618   OldPredBranch->eraseFromParent();
   1619 
   1620   ++NumDupes;
   1621   return true;
   1622 }
   1623 
   1624 /// TryToUnfoldSelect - Look for blocks of the form
   1625 /// bb1:
   1626 ///   %a = select
   1627 ///   br bb
   1628 ///
   1629 /// bb2:
   1630 ///   %p = phi [%a, %bb] ...
   1631 ///   %c = icmp %p
   1632 ///   br i1 %c
   1633 ///
   1634 /// And expand the select into a branch structure if one of its arms allows %c
   1635 /// to be folded. This later enables threading from bb1 over bb2.
   1636 bool JumpThreading::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
   1637   BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
   1638   PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
   1639   Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
   1640 
   1641   if (!CondBr || !CondBr->isConditional() || !CondLHS ||
   1642       CondLHS->getParent() != BB)
   1643     return false;
   1644 
   1645   for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
   1646     BasicBlock *Pred = CondLHS->getIncomingBlock(I);
   1647     SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
   1648 
   1649     // Look if one of the incoming values is a select in the corresponding
   1650     // predecessor.
   1651     if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
   1652       continue;
   1653 
   1654     BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
   1655     if (!PredTerm || !PredTerm->isUnconditional())
   1656       continue;
   1657 
   1658     // Now check if one of the select values would allow us to constant fold the
   1659     // terminator in BB. We don't do the transform if both sides fold, those
   1660     // cases will be threaded in any case.
   1661     LazyValueInfo::Tristate LHSFolds =
   1662         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
   1663                                 CondRHS, Pred, BB);
   1664     LazyValueInfo::Tristate RHSFolds =
   1665         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
   1666                                 CondRHS, Pred, BB);
   1667     if ((LHSFolds != LazyValueInfo::Unknown ||
   1668          RHSFolds != LazyValueInfo::Unknown) &&
   1669         LHSFolds != RHSFolds) {
   1670       // Expand the select.
   1671       //
   1672       // Pred --
   1673       //  |    v
   1674       //  |  NewBB
   1675       //  |    |
   1676       //  |-----
   1677       //  v
   1678       // BB
   1679       BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
   1680                                              BB->getParent(), BB);
   1681       // Move the unconditional branch to NewBB.
   1682       PredTerm->removeFromParent();
   1683       NewBB->getInstList().insert(NewBB->end(), PredTerm);
   1684       // Create a conditional branch and update PHI nodes.
   1685       BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
   1686       CondLHS->setIncomingValue(I, SI->getFalseValue());
   1687       CondLHS->addIncoming(SI->getTrueValue(), NewBB);
   1688       // The select is now dead.
   1689       SI->eraseFromParent();
   1690 
   1691       // Update any other PHI nodes in BB.
   1692       for (BasicBlock::iterator BI = BB->begin();
   1693            PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
   1694         if (Phi != CondLHS)
   1695           Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
   1696       return true;
   1697     }
   1698   }
   1699   return false;
   1700 }
   1701