LLVM API Documentation

JumpThreading.cpp
Go to the documentation of this file.
00001 //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Jump Threading pass.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "jump-threading"
00015 #include "llvm/Transforms/Scalar.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/DenseSet.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/SmallPtrSet.h"
00020 #include "llvm/ADT/SmallSet.h"
00021 #include "llvm/ADT/Statistic.h"
00022 #include "llvm/Analysis/CFG.h"
00023 #include "llvm/Analysis/ConstantFolding.h"
00024 #include "llvm/Analysis/InstructionSimplify.h"
00025 #include "llvm/Analysis/LazyValueInfo.h"
00026 #include "llvm/Analysis/Loads.h"
00027 #include "llvm/IR/DataLayout.h"
00028 #include "llvm/IR/IntrinsicInst.h"
00029 #include "llvm/IR/LLVMContext.h"
00030 #include "llvm/IR/ValueHandle.h"
00031 #include "llvm/Pass.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 #include "llvm/Target/TargetLibraryInfo.h"
00036 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00037 #include "llvm/Transforms/Utils/Local.h"
00038 #include "llvm/Transforms/Utils/SSAUpdater.h"
00039 using namespace llvm;
00040 
00041 STATISTIC(NumThreads, "Number of jumps threaded");
00042 STATISTIC(NumFolds,   "Number of terminators folded");
00043 STATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
00044 
00045 static cl::opt<unsigned>
00046 Threshold("jump-threading-threshold",
00047           cl::desc("Max block size to duplicate for jump threading"),
00048           cl::init(6), cl::Hidden);
00049 
00050 namespace {
00051   // These are at global scope so static functions can use them too.
00052   typedef SmallVectorImpl<std::pair<Constant*, BasicBlock*> > PredValueInfo;
00053   typedef SmallVector<std::pair<Constant*, BasicBlock*>, 8> PredValueInfoTy;
00054 
00055   // This is used to keep track of what kind of constant we're currently hoping
00056   // to find.
00057   enum ConstantPreference {
00058     WantInteger,
00059     WantBlockAddress
00060   };
00061 
00062   /// This pass performs 'jump threading', which looks at blocks that have
00063   /// multiple predecessors and multiple successors.  If one or more of the
00064   /// predecessors of the block can be proven to always jump to one of the
00065   /// successors, we forward the edge from the predecessor to the successor by
00066   /// duplicating the contents of this block.
00067   ///
00068   /// An example of when this can occur is code like this:
00069   ///
00070   ///   if () { ...
00071   ///     X = 4;
00072   ///   }
00073   ///   if (X < 3) {
00074   ///
00075   /// In this case, the unconditional branch at the end of the first if can be
00076   /// revectored to the false side of the second if.
00077   ///
00078   class JumpThreading : public FunctionPass {
00079     const DataLayout *DL;
00080     TargetLibraryInfo *TLI;
00081     LazyValueInfo *LVI;
00082 #ifdef NDEBUG
00083     SmallPtrSet<BasicBlock*, 16> LoopHeaders;
00084 #else
00085     SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
00086 #endif
00087     DenseSet<std::pair<Value*, BasicBlock*> > RecursionSet;
00088 
00089     // RAII helper for updating the recursion stack.
00090     struct RecursionSetRemover {
00091       DenseSet<std::pair<Value*, BasicBlock*> > &TheSet;
00092       std::pair<Value*, BasicBlock*> ThePair;
00093 
00094       RecursionSetRemover(DenseSet<std::pair<Value*, BasicBlock*> > &S,
00095                           std::pair<Value*, BasicBlock*> P)
00096         : TheSet(S), ThePair(P) { }
00097 
00098       ~RecursionSetRemover() {
00099         TheSet.erase(ThePair);
00100       }
00101     };
00102   public:
00103     static char ID; // Pass identification
00104     JumpThreading() : FunctionPass(ID) {
00105       initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
00106     }
00107 
00108     bool runOnFunction(Function &F) override;
00109 
00110     void getAnalysisUsage(AnalysisUsage &AU) const override {
00111       AU.addRequired<LazyValueInfo>();
00112       AU.addPreserved<LazyValueInfo>();
00113       AU.addRequired<TargetLibraryInfo>();
00114     }
00115 
00116     void FindLoopHeaders(Function &F);
00117     bool ProcessBlock(BasicBlock *BB);
00118     bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
00119                     BasicBlock *SuccBB);
00120     bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
00121                                   const SmallVectorImpl<BasicBlock *> &PredBBs);
00122 
00123     bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
00124                                          PredValueInfo &Result,
00125                                          ConstantPreference Preference);
00126     bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
00127                                 ConstantPreference Preference);
00128 
00129     bool ProcessBranchOnPHI(PHINode *PN);
00130     bool ProcessBranchOnXOR(BinaryOperator *BO);
00131 
00132     bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
00133     bool TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB);
00134   };
00135 }
00136 
00137 char JumpThreading::ID = 0;
00138 INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
00139                 "Jump Threading", false, false)
00140 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
00141 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
00142 INITIALIZE_PASS_END(JumpThreading, "jump-threading",
00143                 "Jump Threading", false, false)
00144 
00145 // Public interface to the Jump Threading pass
00146 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
00147 
00148 /// runOnFunction - Top level algorithm.
00149 ///
00150 bool JumpThreading::runOnFunction(Function &F) {
00151   if (skipOptnoneFunction(F))
00152     return false;
00153 
00154   DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
00155   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00156   DL = DLP ? &DLP->getDataLayout() : 0;
00157   TLI = &getAnalysis<TargetLibraryInfo>();
00158   LVI = &getAnalysis<LazyValueInfo>();
00159 
00160   FindLoopHeaders(F);
00161 
00162   bool Changed, EverChanged = false;
00163   do {
00164     Changed = false;
00165     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
00166       BasicBlock *BB = I;
00167       // Thread all of the branches we can over this block.
00168       while (ProcessBlock(BB))
00169         Changed = true;
00170 
00171       ++I;
00172 
00173       // If the block is trivially dead, zap it.  This eliminates the successor
00174       // edges which simplifies the CFG.
00175       if (pred_begin(BB) == pred_end(BB) &&
00176           BB != &BB->getParent()->getEntryBlock()) {
00177         DEBUG(dbgs() << "  JT: Deleting dead block '" << BB->getName()
00178               << "' with terminator: " << *BB->getTerminator() << '\n');
00179         LoopHeaders.erase(BB);
00180         LVI->eraseBlock(BB);
00181         DeleteDeadBlock(BB);
00182         Changed = true;
00183         continue;
00184       }
00185 
00186       BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
00187 
00188       // Can't thread an unconditional jump, but if the block is "almost
00189       // empty", we can replace uses of it with uses of the successor and make
00190       // this dead.
00191       if (BI && BI->isUnconditional() &&
00192           BB != &BB->getParent()->getEntryBlock() &&
00193           // If the terminator is the only non-phi instruction, try to nuke it.
00194           BB->getFirstNonPHIOrDbg()->isTerminator()) {
00195         // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
00196         // block, we have to make sure it isn't in the LoopHeaders set.  We
00197         // reinsert afterward if needed.
00198         bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
00199         BasicBlock *Succ = BI->getSuccessor(0);
00200 
00201         // FIXME: It is always conservatively correct to drop the info
00202         // for a block even if it doesn't get erased.  This isn't totally
00203         // awesome, but it allows us to use AssertingVH to prevent nasty
00204         // dangling pointer issues within LazyValueInfo.
00205         LVI->eraseBlock(BB);
00206         if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
00207           Changed = true;
00208           // If we deleted BB and BB was the header of a loop, then the
00209           // successor is now the header of the loop.
00210           BB = Succ;
00211         }
00212 
00213         if (ErasedFromLoopHeaders)
00214           LoopHeaders.insert(BB);
00215       }
00216     }
00217     EverChanged |= Changed;
00218   } while (Changed);
00219 
00220   LoopHeaders.clear();
00221   return EverChanged;
00222 }
00223 
00224 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
00225 /// thread across it. Stop scanning the block when passing the threshold.
00226 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB,
00227                                              unsigned Threshold) {
00228   /// Ignore PHI nodes, these will be flattened when duplication happens.
00229   BasicBlock::const_iterator I = BB->getFirstNonPHI();
00230 
00231   // FIXME: THREADING will delete values that are just used to compute the
00232   // branch, so they shouldn't count against the duplication cost.
00233 
00234   // Sum up the cost of each instruction until we get to the terminator.  Don't
00235   // include the terminator because the copy won't include it.
00236   unsigned Size = 0;
00237   for (; !isa<TerminatorInst>(I); ++I) {
00238 
00239     // Stop scanning the block if we've reached the threshold.
00240     if (Size > Threshold)
00241       return Size;
00242 
00243     // Debugger intrinsics don't incur code size.
00244     if (isa<DbgInfoIntrinsic>(I)) continue;
00245 
00246     // If this is a pointer->pointer bitcast, it is free.
00247     if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
00248       continue;
00249 
00250     // All other instructions count for at least one unit.
00251     ++Size;
00252 
00253     // Calls are more expensive.  If they are non-intrinsic calls, we model them
00254     // as having cost of 4.  If they are a non-vector intrinsic, we model them
00255     // as having cost of 2 total, and if they are a vector intrinsic, we model
00256     // them as having cost 1.
00257     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
00258       if (CI->cannotDuplicate())
00259         // Blocks with NoDuplicate are modelled as having infinite cost, so they
00260         // are never duplicated.
00261         return ~0U;
00262       else if (!isa<IntrinsicInst>(CI))
00263         Size += 3;
00264       else if (!CI->getType()->isVectorTy())
00265         Size += 1;
00266     }
00267   }
00268 
00269   // Threading through a switch statement is particularly profitable.  If this
00270   // block ends in a switch, decrease its cost to make it more likely to happen.
00271   if (isa<SwitchInst>(I))
00272     Size = Size > 6 ? Size-6 : 0;
00273 
00274   // The same holds for indirect branches, but slightly more so.
00275   if (isa<IndirectBrInst>(I))
00276     Size = Size > 8 ? Size-8 : 0;
00277 
00278   return Size;
00279 }
00280 
00281 /// FindLoopHeaders - We do not want jump threading to turn proper loop
00282 /// structures into irreducible loops.  Doing this breaks up the loop nesting
00283 /// hierarchy and pessimizes later transformations.  To prevent this from
00284 /// happening, we first have to find the loop headers.  Here we approximate this
00285 /// by finding targets of backedges in the CFG.
00286 ///
00287 /// Note that there definitely are cases when we want to allow threading of
00288 /// edges across a loop header.  For example, threading a jump from outside the
00289 /// loop (the preheader) to an exit block of the loop is definitely profitable.
00290 /// It is also almost always profitable to thread backedges from within the loop
00291 /// to exit blocks, and is often profitable to thread backedges to other blocks
00292 /// within the loop (forming a nested loop).  This simple analysis is not rich
00293 /// enough to track all of these properties and keep it up-to-date as the CFG
00294 /// mutates, so we don't allow any of these transformations.
00295 ///
00296 void JumpThreading::FindLoopHeaders(Function &F) {
00297   SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
00298   FindFunctionBackedges(F, Edges);
00299 
00300   for (unsigned i = 0, e = Edges.size(); i != e; ++i)
00301     LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
00302 }
00303 
00304 /// getKnownConstant - Helper method to determine if we can thread over a
00305 /// terminator with the given value as its condition, and if so what value to
00306 /// use for that. What kind of value this is depends on whether we want an
00307 /// integer or a block address, but an undef is always accepted.
00308 /// Returns null if Val is null or not an appropriate constant.
00309 static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
00310   if (!Val)
00311     return 0;
00312 
00313   // Undef is "known" enough.
00314   if (UndefValue *U = dyn_cast<UndefValue>(Val))
00315     return U;
00316 
00317   if (Preference == WantBlockAddress)
00318     return dyn_cast<BlockAddress>(Val->stripPointerCasts());
00319 
00320   return dyn_cast<ConstantInt>(Val);
00321 }
00322 
00323 /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
00324 /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
00325 /// in any of our predecessors.  If so, return the known list of value and pred
00326 /// BB in the result vector.
00327 ///
00328 /// This returns true if there were any known values.
00329 ///
00330 bool JumpThreading::
00331 ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB, PredValueInfo &Result,
00332                                 ConstantPreference Preference) {
00333   // This method walks up use-def chains recursively.  Because of this, we could
00334   // get into an infinite loop going around loops in the use-def chain.  To
00335   // prevent this, keep track of what (value, block) pairs we've already visited
00336   // and terminate the search if we loop back to them
00337   if (!RecursionSet.insert(std::make_pair(V, BB)).second)
00338     return false;
00339 
00340   // An RAII help to remove this pair from the recursion set once the recursion
00341   // stack pops back out again.
00342   RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
00343 
00344   // If V is a constant, then it is known in all predecessors.
00345   if (Constant *KC = getKnownConstant(V, Preference)) {
00346     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00347       Result.push_back(std::make_pair(KC, *PI));
00348 
00349     return true;
00350   }
00351 
00352   // If V is a non-instruction value, or an instruction in a different block,
00353   // then it can't be derived from a PHI.
00354   Instruction *I = dyn_cast<Instruction>(V);
00355   if (I == 0 || I->getParent() != BB) {
00356 
00357     // Okay, if this is a live-in value, see if it has a known value at the end
00358     // of any of our predecessors.
00359     //
00360     // FIXME: This should be an edge property, not a block end property.
00361     /// TODO: Per PR2563, we could infer value range information about a
00362     /// predecessor based on its terminator.
00363     //
00364     // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
00365     // "I" is a non-local compare-with-a-constant instruction.  This would be
00366     // able to handle value inequalities better, for example if the compare is
00367     // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
00368     // Perhaps getConstantOnEdge should be smart enough to do this?
00369 
00370     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00371       BasicBlock *P = *PI;
00372       // If the value is known by LazyValueInfo to be a constant in a
00373       // predecessor, use that information to try to thread this block.
00374       Constant *PredCst = LVI->getConstantOnEdge(V, P, BB);
00375       if (Constant *KC = getKnownConstant(PredCst, Preference))
00376         Result.push_back(std::make_pair(KC, P));
00377     }
00378 
00379     return !Result.empty();
00380   }
00381 
00382   /// If I is a PHI node, then we know the incoming values for any constants.
00383   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00384     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00385       Value *InVal = PN->getIncomingValue(i);
00386       if (Constant *KC = getKnownConstant(InVal, Preference)) {
00387         Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
00388       } else {
00389         Constant *CI = LVI->getConstantOnEdge(InVal,
00390                                               PN->getIncomingBlock(i), BB);
00391         if (Constant *KC = getKnownConstant(CI, Preference))
00392           Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
00393       }
00394     }
00395 
00396     return !Result.empty();
00397   }
00398 
00399   PredValueInfoTy LHSVals, RHSVals;
00400 
00401   // Handle some boolean conditions.
00402   if (I->getType()->getPrimitiveSizeInBits() == 1) {
00403     assert(Preference == WantInteger && "One-bit non-integer type?");
00404     // X | true -> true
00405     // X & false -> false
00406     if (I->getOpcode() == Instruction::Or ||
00407         I->getOpcode() == Instruction::And) {
00408       ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
00409                                       WantInteger);
00410       ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals,
00411                                       WantInteger);
00412 
00413       if (LHSVals.empty() && RHSVals.empty())
00414         return false;
00415 
00416       ConstantInt *InterestingVal;
00417       if (I->getOpcode() == Instruction::Or)
00418         InterestingVal = ConstantInt::getTrue(I->getContext());
00419       else
00420         InterestingVal = ConstantInt::getFalse(I->getContext());
00421 
00422       SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
00423 
00424       // Scan for the sentinel.  If we find an undef, force it to the
00425       // interesting value: x|undef -> true and x&undef -> false.
00426       for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
00427         if (LHSVals[i].first == InterestingVal ||
00428             isa<UndefValue>(LHSVals[i].first)) {
00429           Result.push_back(LHSVals[i]);
00430           Result.back().first = InterestingVal;
00431           LHSKnownBBs.insert(LHSVals[i].second);
00432         }
00433       for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
00434         if (RHSVals[i].first == InterestingVal ||
00435             isa<UndefValue>(RHSVals[i].first)) {
00436           // If we already inferred a value for this block on the LHS, don't
00437           // re-add it.
00438           if (!LHSKnownBBs.count(RHSVals[i].second)) {
00439             Result.push_back(RHSVals[i]);
00440             Result.back().first = InterestingVal;
00441           }
00442         }
00443 
00444       return !Result.empty();
00445     }
00446 
00447     // Handle the NOT form of XOR.
00448     if (I->getOpcode() == Instruction::Xor &&
00449         isa<ConstantInt>(I->getOperand(1)) &&
00450         cast<ConstantInt>(I->getOperand(1))->isOne()) {
00451       ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result,
00452                                       WantInteger);
00453       if (Result.empty())
00454         return false;
00455 
00456       // Invert the known values.
00457       for (unsigned i = 0, e = Result.size(); i != e; ++i)
00458         Result[i].first = ConstantExpr::getNot(Result[i].first);
00459 
00460       return true;
00461     }
00462 
00463   // Try to simplify some other binary operator values.
00464   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
00465     assert(Preference != WantBlockAddress
00466             && "A binary operator creating a block address?");
00467     if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
00468       PredValueInfoTy LHSVals;
00469       ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals,
00470                                       WantInteger);
00471 
00472       // Try to use constant folding to simplify the binary operator.
00473       for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
00474         Constant *V = LHSVals[i].first;
00475         Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
00476 
00477         if (Constant *KC = getKnownConstant(Folded, WantInteger))
00478           Result.push_back(std::make_pair(KC, LHSVals[i].second));
00479       }
00480     }
00481 
00482     return !Result.empty();
00483   }
00484 
00485   // Handle compare with phi operand, where the PHI is defined in this block.
00486   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
00487     assert(Preference == WantInteger && "Compares only produce integers");
00488     PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
00489     if (PN && PN->getParent() == BB) {
00490       // We can do this simplification if any comparisons fold to true or false.
00491       // See if any do.
00492       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00493         BasicBlock *PredBB = PN->getIncomingBlock(i);
00494         Value *LHS = PN->getIncomingValue(i);
00495         Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
00496 
00497         Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, DL);
00498         if (Res == 0) {
00499           if (!isa<Constant>(RHS))
00500             continue;
00501 
00502           LazyValueInfo::Tristate
00503             ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
00504                                            cast<Constant>(RHS), PredBB, BB);
00505           if (ResT == LazyValueInfo::Unknown)
00506             continue;
00507           Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
00508         }
00509 
00510         if (Constant *KC = getKnownConstant(Res, WantInteger))
00511           Result.push_back(std::make_pair(KC, PredBB));
00512       }
00513 
00514       return !Result.empty();
00515     }
00516 
00517 
00518     // If comparing a live-in value against a constant, see if we know the
00519     // live-in value on any predecessors.
00520     if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
00521       if (!isa<Instruction>(Cmp->getOperand(0)) ||
00522           cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
00523         Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
00524 
00525         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
00526           BasicBlock *P = *PI;
00527           // If the value is known by LazyValueInfo to be a constant in a
00528           // predecessor, use that information to try to thread this block.
00529           LazyValueInfo::Tristate Res =
00530             LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
00531                                     RHSCst, P, BB);
00532           if (Res == LazyValueInfo::Unknown)
00533             continue;
00534 
00535           Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
00536           Result.push_back(std::make_pair(ResC, P));
00537         }
00538 
00539         return !Result.empty();
00540       }
00541 
00542       // Try to find a constant value for the LHS of a comparison,
00543       // and evaluate it statically if we can.
00544       if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
00545         PredValueInfoTy LHSVals;
00546         ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
00547                                         WantInteger);
00548 
00549         for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
00550           Constant *V = LHSVals[i].first;
00551           Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
00552                                                       V, CmpConst);
00553           if (Constant *KC = getKnownConstant(Folded, WantInteger))
00554             Result.push_back(std::make_pair(KC, LHSVals[i].second));
00555         }
00556 
00557         return !Result.empty();
00558       }
00559     }
00560   }
00561 
00562   if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
00563     // Handle select instructions where at least one operand is a known constant
00564     // and we can figure out the condition value for any predecessor block.
00565     Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
00566     Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
00567     PredValueInfoTy Conds;
00568     if ((TrueVal || FalseVal) &&
00569         ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds,
00570                                         WantInteger)) {
00571       for (unsigned i = 0, e = Conds.size(); i != e; ++i) {
00572         Constant *Cond = Conds[i].first;
00573 
00574         // Figure out what value to use for the condition.
00575         bool KnownCond;
00576         if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
00577           // A known boolean.
00578           KnownCond = CI->isOne();
00579         } else {
00580           assert(isa<UndefValue>(Cond) && "Unexpected condition value");
00581           // Either operand will do, so be sure to pick the one that's a known
00582           // constant.
00583           // FIXME: Do this more cleverly if both values are known constants?
00584           KnownCond = (TrueVal != 0);
00585         }
00586 
00587         // See if the select has a known constant value for this predecessor.
00588         if (Constant *Val = KnownCond ? TrueVal : FalseVal)
00589           Result.push_back(std::make_pair(Val, Conds[i].second));
00590       }
00591 
00592       return !Result.empty();
00593     }
00594   }
00595 
00596   // If all else fails, see if LVI can figure out a constant value for us.
00597   Constant *CI = LVI->getConstant(V, BB);
00598   if (Constant *KC = getKnownConstant(CI, Preference)) {
00599     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00600       Result.push_back(std::make_pair(KC, *PI));
00601   }
00602 
00603   return !Result.empty();
00604 }
00605 
00606 
00607 
00608 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
00609 /// in an undefined jump, decide which block is best to revector to.
00610 ///
00611 /// Since we can pick an arbitrary destination, we pick the successor with the
00612 /// fewest predecessors.  This should reduce the in-degree of the others.
00613 ///
00614 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
00615   TerminatorInst *BBTerm = BB->getTerminator();
00616   unsigned MinSucc = 0;
00617   BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
00618   // Compute the successor with the minimum number of predecessors.
00619   unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
00620   for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
00621     TestBB = BBTerm->getSuccessor(i);
00622     unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
00623     if (NumPreds < MinNumPreds) {
00624       MinSucc = i;
00625       MinNumPreds = NumPreds;
00626     }
00627   }
00628 
00629   return MinSucc;
00630 }
00631 
00632 static bool hasAddressTakenAndUsed(BasicBlock *BB) {
00633   if (!BB->hasAddressTaken()) return false;
00634 
00635   // If the block has its address taken, it may be a tree of dead constants
00636   // hanging off of it.  These shouldn't keep the block alive.
00637   BlockAddress *BA = BlockAddress::get(BB);
00638   BA->removeDeadConstantUsers();
00639   return !BA->use_empty();
00640 }
00641 
00642 /// ProcessBlock - If there are any predecessors whose control can be threaded
00643 /// through to a successor, transform them now.
00644 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
00645   // If the block is trivially dead, just return and let the caller nuke it.
00646   // This simplifies other transformations.
00647   if (pred_begin(BB) == pred_end(BB) &&
00648       BB != &BB->getParent()->getEntryBlock())
00649     return false;
00650 
00651   // If this block has a single predecessor, and if that pred has a single
00652   // successor, merge the blocks.  This encourages recursive jump threading
00653   // because now the condition in this block can be threaded through
00654   // predecessors of our predecessor block.
00655   if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
00656     if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
00657         SinglePred != BB && !hasAddressTakenAndUsed(BB)) {
00658       // If SinglePred was a loop header, BB becomes one.
00659       if (LoopHeaders.erase(SinglePred))
00660         LoopHeaders.insert(BB);
00661 
00662       // Remember if SinglePred was the entry block of the function.  If so, we
00663       // will need to move BB back to the entry position.
00664       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
00665       LVI->eraseBlock(SinglePred);
00666       MergeBasicBlockIntoOnlyPred(BB);
00667 
00668       if (isEntry && BB != &BB->getParent()->getEntryBlock())
00669         BB->moveBefore(&BB->getParent()->getEntryBlock());
00670       return true;
00671     }
00672   }
00673 
00674   // What kind of constant we're looking for.
00675   ConstantPreference Preference = WantInteger;
00676 
00677   // Look to see if the terminator is a conditional branch, switch or indirect
00678   // branch, if not we can't thread it.
00679   Value *Condition;
00680   Instruction *Terminator = BB->getTerminator();
00681   if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
00682     // Can't thread an unconditional jump.
00683     if (BI->isUnconditional()) return false;
00684     Condition = BI->getCondition();
00685   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
00686     Condition = SI->getCondition();
00687   } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
00688     // Can't thread indirect branch with no successors.
00689     if (IB->getNumSuccessors() == 0) return false;
00690     Condition = IB->getAddress()->stripPointerCasts();
00691     Preference = WantBlockAddress;
00692   } else {
00693     return false; // Must be an invoke.
00694   }
00695 
00696   // Run constant folding to see if we can reduce the condition to a simple
00697   // constant.
00698   if (Instruction *I = dyn_cast<Instruction>(Condition)) {
00699     Value *SimpleVal = ConstantFoldInstruction(I, DL, TLI);
00700     if (SimpleVal) {
00701       I->replaceAllUsesWith(SimpleVal);
00702       I->eraseFromParent();
00703       Condition = SimpleVal;
00704     }
00705   }
00706 
00707   // If the terminator is branching on an undef, we can pick any of the
00708   // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
00709   if (isa<UndefValue>(Condition)) {
00710     unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
00711 
00712     // Fold the branch/switch.
00713     TerminatorInst *BBTerm = BB->getTerminator();
00714     for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
00715       if (i == BestSucc) continue;
00716       BBTerm->getSuccessor(i)->removePredecessor(BB, true);
00717     }
00718 
00719     DEBUG(dbgs() << "  In block '" << BB->getName()
00720           << "' folding undef terminator: " << *BBTerm << '\n');
00721     BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
00722     BBTerm->eraseFromParent();
00723     return true;
00724   }
00725 
00726   // If the terminator of this block is branching on a constant, simplify the
00727   // terminator to an unconditional branch.  This can occur due to threading in
00728   // other blocks.
00729   if (getKnownConstant(Condition, Preference)) {
00730     DEBUG(dbgs() << "  In block '" << BB->getName()
00731           << "' folding terminator: " << *BB->getTerminator() << '\n');
00732     ++NumFolds;
00733     ConstantFoldTerminator(BB, true);
00734     return true;
00735   }
00736 
00737   Instruction *CondInst = dyn_cast<Instruction>(Condition);
00738 
00739   // All the rest of our checks depend on the condition being an instruction.
00740   if (CondInst == 0) {
00741     // FIXME: Unify this with code below.
00742     if (ProcessThreadableEdges(Condition, BB, Preference))
00743       return true;
00744     return false;
00745   }
00746 
00747 
00748   if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
00749     // For a comparison where the LHS is outside this block, it's possible
00750     // that we've branched on it before.  Used LVI to see if we can simplify
00751     // the branch based on that.
00752     BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
00753     Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
00754     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
00755     if (CondBr && CondConst && CondBr->isConditional() && PI != PE &&
00756         (!isa<Instruction>(CondCmp->getOperand(0)) ||
00757          cast<Instruction>(CondCmp->getOperand(0))->getParent() != BB)) {
00758       // For predecessor edge, determine if the comparison is true or false
00759       // on that edge.  If they're all true or all false, we can simplify the
00760       // branch.
00761       // FIXME: We could handle mixed true/false by duplicating code.
00762       LazyValueInfo::Tristate Baseline =
00763         LVI->getPredicateOnEdge(CondCmp->getPredicate(), CondCmp->getOperand(0),
00764                                 CondConst, *PI, BB);
00765       if (Baseline != LazyValueInfo::Unknown) {
00766         // Check that all remaining incoming values match the first one.
00767         while (++PI != PE) {
00768           LazyValueInfo::Tristate Ret =
00769             LVI->getPredicateOnEdge(CondCmp->getPredicate(),
00770                                     CondCmp->getOperand(0), CondConst, *PI, BB);
00771           if (Ret != Baseline) break;
00772         }
00773 
00774         // If we terminated early, then one of the values didn't match.
00775         if (PI == PE) {
00776           unsigned ToRemove = Baseline == LazyValueInfo::True ? 1 : 0;
00777           unsigned ToKeep = Baseline == LazyValueInfo::True ? 0 : 1;
00778           CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
00779           BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
00780           CondBr->eraseFromParent();
00781           return true;
00782         }
00783       }
00784 
00785     }
00786 
00787     if (CondBr && CondConst && TryToUnfoldSelect(CondCmp, BB))
00788       return true;
00789   }
00790 
00791   // Check for some cases that are worth simplifying.  Right now we want to look
00792   // for loads that are used by a switch or by the condition for the branch.  If
00793   // we see one, check to see if it's partially redundant.  If so, insert a PHI
00794   // which can then be used to thread the values.
00795   //
00796   Value *SimplifyValue = CondInst;
00797   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
00798     if (isa<Constant>(CondCmp->getOperand(1)))
00799       SimplifyValue = CondCmp->getOperand(0);
00800 
00801   // TODO: There are other places where load PRE would be profitable, such as
00802   // more complex comparisons.
00803   if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
00804     if (SimplifyPartiallyRedundantLoad(LI))
00805       return true;
00806 
00807 
00808   // Handle a variety of cases where we are branching on something derived from
00809   // a PHI node in the current block.  If we can prove that any predecessors
00810   // compute a predictable value based on a PHI node, thread those predecessors.
00811   //
00812   if (ProcessThreadableEdges(CondInst, BB, Preference))
00813     return true;
00814 
00815   // If this is an otherwise-unfoldable branch on a phi node in the current
00816   // block, see if we can simplify.
00817   if (PHINode *PN = dyn_cast<PHINode>(CondInst))
00818     if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
00819       return ProcessBranchOnPHI(PN);
00820 
00821 
00822   // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
00823   if (CondInst->getOpcode() == Instruction::Xor &&
00824       CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
00825     return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
00826 
00827 
00828   // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
00829   // "(X == 4)", thread through this block.
00830 
00831   return false;
00832 }
00833 
00834 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
00835 /// load instruction, eliminate it by replacing it with a PHI node.  This is an
00836 /// important optimization that encourages jump threading, and needs to be run
00837 /// interlaced with other jump threading tasks.
00838 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
00839   // Don't hack volatile/atomic loads.
00840   if (!LI->isSimple()) return false;
00841 
00842   // If the load is defined in a block with exactly one predecessor, it can't be
00843   // partially redundant.
00844   BasicBlock *LoadBB = LI->getParent();
00845   if (LoadBB->getSinglePredecessor())
00846     return false;
00847 
00848   // If the load is defined in a landing pad, it can't be partially redundant,
00849   // because the edges between the invoke and the landing pad cannot have other
00850   // instructions between them.
00851   if (LoadBB->isLandingPad())
00852     return false;
00853 
00854   Value *LoadedPtr = LI->getOperand(0);
00855 
00856   // If the loaded operand is defined in the LoadBB, it can't be available.
00857   // TODO: Could do simple PHI translation, that would be fun :)
00858   if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
00859     if (PtrOp->getParent() == LoadBB)
00860       return false;
00861 
00862   // Scan a few instructions up from the load, to see if it is obviously live at
00863   // the entry to its block.
00864   BasicBlock::iterator BBIt = LI;
00865 
00866   if (Value *AvailableVal =
00867         FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
00868     // If the value if the load is locally available within the block, just use
00869     // it.  This frequently occurs for reg2mem'd allocas.
00870     //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
00871 
00872     // If the returned value is the load itself, replace with an undef. This can
00873     // only happen in dead loops.
00874     if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
00875     LI->replaceAllUsesWith(AvailableVal);
00876     LI->eraseFromParent();
00877     return true;
00878   }
00879 
00880   // Otherwise, if we scanned the whole block and got to the top of the block,
00881   // we know the block is locally transparent to the load.  If not, something
00882   // might clobber its value.
00883   if (BBIt != LoadBB->begin())
00884     return false;
00885 
00886   // If all of the loads and stores that feed the value have the same TBAA tag,
00887   // then we can propagate it onto any newly inserted loads.
00888   MDNode *TBAATag = LI->getMetadata(LLVMContext::MD_tbaa);
00889 
00890   SmallPtrSet<BasicBlock*, 8> PredsScanned;
00891   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
00892   AvailablePredsTy AvailablePreds;
00893   BasicBlock *OneUnavailablePred = 0;
00894 
00895   // If we got here, the loaded value is transparent through to the start of the
00896   // block.  Check to see if it is available in any of the predecessor blocks.
00897   for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
00898        PI != PE; ++PI) {
00899     BasicBlock *PredBB = *PI;
00900 
00901     // If we already scanned this predecessor, skip it.
00902     if (!PredsScanned.insert(PredBB))
00903       continue;
00904 
00905     // Scan the predecessor to see if the value is available in the pred.
00906     BBIt = PredBB->end();
00907     MDNode *ThisTBAATag = 0;
00908     Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6,
00909                                                     0, &ThisTBAATag);
00910     if (!PredAvailable) {
00911       OneUnavailablePred = PredBB;
00912       continue;
00913     }
00914 
00915     // If tbaa tags disagree or are not present, forget about them.
00916     if (TBAATag != ThisTBAATag) TBAATag = 0;
00917 
00918     // If so, this load is partially redundant.  Remember this info so that we
00919     // can create a PHI node.
00920     AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
00921   }
00922 
00923   // If the loaded value isn't available in any predecessor, it isn't partially
00924   // redundant.
00925   if (AvailablePreds.empty()) return false;
00926 
00927   // Okay, the loaded value is available in at least one (and maybe all!)
00928   // predecessors.  If the value is unavailable in more than one unique
00929   // predecessor, we want to insert a merge block for those common predecessors.
00930   // This ensures that we only have to insert one reload, thus not increasing
00931   // code size.
00932   BasicBlock *UnavailablePred = 0;
00933 
00934   // If there is exactly one predecessor where the value is unavailable, the
00935   // already computed 'OneUnavailablePred' block is it.  If it ends in an
00936   // unconditional branch, we know that it isn't a critical edge.
00937   if (PredsScanned.size() == AvailablePreds.size()+1 &&
00938       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
00939     UnavailablePred = OneUnavailablePred;
00940   } else if (PredsScanned.size() != AvailablePreds.size()) {
00941     // Otherwise, we had multiple unavailable predecessors or we had a critical
00942     // edge from the one.
00943     SmallVector<BasicBlock*, 8> PredsToSplit;
00944     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
00945 
00946     for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
00947       AvailablePredSet.insert(AvailablePreds[i].first);
00948 
00949     // Add all the unavailable predecessors to the PredsToSplit list.
00950     for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
00951          PI != PE; ++PI) {
00952       BasicBlock *P = *PI;
00953       // If the predecessor is an indirect goto, we can't split the edge.
00954       if (isa<IndirectBrInst>(P->getTerminator()))
00955         return false;
00956 
00957       if (!AvailablePredSet.count(P))
00958         PredsToSplit.push_back(P);
00959     }
00960 
00961     // Split them out to their own block.
00962     UnavailablePred =
00963       SplitBlockPredecessors(LoadBB, PredsToSplit, "thread-pre-split", this);
00964   }
00965 
00966   // If the value isn't available in all predecessors, then there will be
00967   // exactly one where it isn't available.  Insert a load on that edge and add
00968   // it to the AvailablePreds list.
00969   if (UnavailablePred) {
00970     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
00971            "Can't handle critical edge here!");
00972     LoadInst *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
00973                                  LI->getAlignment(),
00974                                  UnavailablePred->getTerminator());
00975     NewVal->setDebugLoc(LI->getDebugLoc());
00976     if (TBAATag)
00977       NewVal->setMetadata(LLVMContext::MD_tbaa, TBAATag);
00978 
00979     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
00980   }
00981 
00982   // Now we know that each predecessor of this block has a value in
00983   // AvailablePreds, sort them for efficient access as we're walking the preds.
00984   array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
00985 
00986   // Create a PHI node at the start of the block for the PRE'd load value.
00987   pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
00988   PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
00989                                 LoadBB->begin());
00990   PN->takeName(LI);
00991   PN->setDebugLoc(LI->getDebugLoc());
00992 
00993   // Insert new entries into the PHI for each predecessor.  A single block may
00994   // have multiple entries here.
00995   for (pred_iterator PI = PB; PI != PE; ++PI) {
00996     BasicBlock *P = *PI;
00997     AvailablePredsTy::iterator I =
00998       std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
00999                        std::make_pair(P, (Value*)0));
01000 
01001     assert(I != AvailablePreds.end() && I->first == P &&
01002            "Didn't find entry for predecessor!");
01003 
01004     PN->addIncoming(I->second, I->first);
01005   }
01006 
01007   //cerr << "PRE: " << *LI << *PN << "\n";
01008 
01009   LI->replaceAllUsesWith(PN);
01010   LI->eraseFromParent();
01011 
01012   return true;
01013 }
01014 
01015 /// FindMostPopularDest - The specified list contains multiple possible
01016 /// threadable destinations.  Pick the one that occurs the most frequently in
01017 /// the list.
01018 static BasicBlock *
01019 FindMostPopularDest(BasicBlock *BB,
01020                     const SmallVectorImpl<std::pair<BasicBlock*,
01021                                   BasicBlock*> > &PredToDestList) {
01022   assert(!PredToDestList.empty());
01023 
01024   // Determine popularity.  If there are multiple possible destinations, we
01025   // explicitly choose to ignore 'undef' destinations.  We prefer to thread
01026   // blocks with known and real destinations to threading undef.  We'll handle
01027   // them later if interesting.
01028   DenseMap<BasicBlock*, unsigned> DestPopularity;
01029   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
01030     if (PredToDestList[i].second)
01031       DestPopularity[PredToDestList[i].second]++;
01032 
01033   // Find the most popular dest.
01034   DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
01035   BasicBlock *MostPopularDest = DPI->first;
01036   unsigned Popularity = DPI->second;
01037   SmallVector<BasicBlock*, 4> SamePopularity;
01038 
01039   for (++DPI; DPI != DestPopularity.end(); ++DPI) {
01040     // If the popularity of this entry isn't higher than the popularity we've
01041     // seen so far, ignore it.
01042     if (DPI->second < Popularity)
01043       ; // ignore.
01044     else if (DPI->second == Popularity) {
01045       // If it is the same as what we've seen so far, keep track of it.
01046       SamePopularity.push_back(DPI->first);
01047     } else {
01048       // If it is more popular, remember it.
01049       SamePopularity.clear();
01050       MostPopularDest = DPI->first;
01051       Popularity = DPI->second;
01052     }
01053   }
01054 
01055   // Okay, now we know the most popular destination.  If there is more than one
01056   // destination, we need to determine one.  This is arbitrary, but we need
01057   // to make a deterministic decision.  Pick the first one that appears in the
01058   // successor list.
01059   if (!SamePopularity.empty()) {
01060     SamePopularity.push_back(MostPopularDest);
01061     TerminatorInst *TI = BB->getTerminator();
01062     for (unsigned i = 0; ; ++i) {
01063       assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
01064 
01065       if (std::find(SamePopularity.begin(), SamePopularity.end(),
01066                     TI->getSuccessor(i)) == SamePopularity.end())
01067         continue;
01068 
01069       MostPopularDest = TI->getSuccessor(i);
01070       break;
01071     }
01072   }
01073 
01074   // Okay, we have finally picked the most popular destination.
01075   return MostPopularDest;
01076 }
01077 
01078 bool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
01079                                            ConstantPreference Preference) {
01080   // If threading this would thread across a loop header, don't even try to
01081   // thread the edge.
01082   if (LoopHeaders.count(BB))
01083     return false;
01084 
01085   PredValueInfoTy PredValues;
01086   if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference))
01087     return false;
01088 
01089   assert(!PredValues.empty() &&
01090          "ComputeValueKnownInPredecessors returned true with no values");
01091 
01092   DEBUG(dbgs() << "IN BB: " << *BB;
01093         for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
01094           dbgs() << "  BB '" << BB->getName() << "': FOUND condition = "
01095             << *PredValues[i].first
01096             << " for pred '" << PredValues[i].second->getName() << "'.\n";
01097         });
01098 
01099   // Decide what we want to thread through.  Convert our list of known values to
01100   // a list of known destinations for each pred.  This also discards duplicate
01101   // predecessors and keeps track of the undefined inputs (which are represented
01102   // as a null dest in the PredToDestList).
01103   SmallPtrSet<BasicBlock*, 16> SeenPreds;
01104   SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
01105 
01106   BasicBlock *OnlyDest = 0;
01107   BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
01108 
01109   for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
01110     BasicBlock *Pred = PredValues[i].second;
01111     if (!SeenPreds.insert(Pred))
01112       continue;  // Duplicate predecessor entry.
01113 
01114     // If the predecessor ends with an indirect goto, we can't change its
01115     // destination.
01116     if (isa<IndirectBrInst>(Pred->getTerminator()))
01117       continue;
01118 
01119     Constant *Val = PredValues[i].first;
01120 
01121     BasicBlock *DestBB;
01122     if (isa<UndefValue>(Val))
01123       DestBB = 0;
01124     else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
01125       DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
01126     else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
01127       DestBB = SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccessor();
01128     } else {
01129       assert(isa<IndirectBrInst>(BB->getTerminator())
01130               && "Unexpected terminator");
01131       DestBB = cast<BlockAddress>(Val)->getBasicBlock();
01132     }
01133 
01134     // If we have exactly one destination, remember it for efficiency below.
01135     if (PredToDestList.empty())
01136       OnlyDest = DestBB;
01137     else if (OnlyDest != DestBB)
01138       OnlyDest = MultipleDestSentinel;
01139 
01140     PredToDestList.push_back(std::make_pair(Pred, DestBB));
01141   }
01142 
01143   // If all edges were unthreadable, we fail.
01144   if (PredToDestList.empty())
01145     return false;
01146 
01147   // Determine which is the most common successor.  If we have many inputs and
01148   // this block is a switch, we want to start by threading the batch that goes
01149   // to the most popular destination first.  If we only know about one
01150   // threadable destination (the common case) we can avoid this.
01151   BasicBlock *MostPopularDest = OnlyDest;
01152 
01153   if (MostPopularDest == MultipleDestSentinel)
01154     MostPopularDest = FindMostPopularDest(BB, PredToDestList);
01155 
01156   // Now that we know what the most popular destination is, factor all
01157   // predecessors that will jump to it into a single predecessor.
01158   SmallVector<BasicBlock*, 16> PredsToFactor;
01159   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
01160     if (PredToDestList[i].second == MostPopularDest) {
01161       BasicBlock *Pred = PredToDestList[i].first;
01162 
01163       // This predecessor may be a switch or something else that has multiple
01164       // edges to the block.  Factor each of these edges by listing them
01165       // according to # occurrences in PredsToFactor.
01166       TerminatorInst *PredTI = Pred->getTerminator();
01167       for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
01168         if (PredTI->getSuccessor(i) == BB)
01169           PredsToFactor.push_back(Pred);
01170     }
01171 
01172   // If the threadable edges are branching on an undefined value, we get to pick
01173   // the destination that these predecessors should get to.
01174   if (MostPopularDest == 0)
01175     MostPopularDest = BB->getTerminator()->
01176                             getSuccessor(GetBestDestForJumpOnUndef(BB));
01177 
01178   // Ok, try to thread it!
01179   return ThreadEdge(BB, PredsToFactor, MostPopularDest);
01180 }
01181 
01182 /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
01183 /// a PHI node in the current block.  See if there are any simplifications we
01184 /// can do based on inputs to the phi node.
01185 ///
01186 bool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
01187   BasicBlock *BB = PN->getParent();
01188 
01189   // TODO: We could make use of this to do it once for blocks with common PHI
01190   // values.
01191   SmallVector<BasicBlock*, 1> PredBBs;
01192   PredBBs.resize(1);
01193 
01194   // If any of the predecessor blocks end in an unconditional branch, we can
01195   // *duplicate* the conditional branch into that block in order to further
01196   // encourage jump threading and to eliminate cases where we have branch on a
01197   // phi of an icmp (branch on icmp is much better).
01198   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01199     BasicBlock *PredBB = PN->getIncomingBlock(i);
01200     if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
01201       if (PredBr->isUnconditional()) {
01202         PredBBs[0] = PredBB;
01203         // Try to duplicate BB into PredBB.
01204         if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
01205           return true;
01206       }
01207   }
01208 
01209   return false;
01210 }
01211 
01212 /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
01213 /// a xor instruction in the current block.  See if there are any
01214 /// simplifications we can do based on inputs to the xor.
01215 ///
01216 bool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
01217   BasicBlock *BB = BO->getParent();
01218 
01219   // If either the LHS or RHS of the xor is a constant, don't do this
01220   // optimization.
01221   if (isa<ConstantInt>(BO->getOperand(0)) ||
01222       isa<ConstantInt>(BO->getOperand(1)))
01223     return false;
01224 
01225   // If the first instruction in BB isn't a phi, we won't be able to infer
01226   // anything special about any particular predecessor.
01227   if (!isa<PHINode>(BB->front()))
01228     return false;
01229 
01230   // If we have a xor as the branch input to this block, and we know that the
01231   // LHS or RHS of the xor in any predecessor is true/false, then we can clone
01232   // the condition into the predecessor and fix that value to true, saving some
01233   // logical ops on that path and encouraging other paths to simplify.
01234   //
01235   // This copies something like this:
01236   //
01237   //  BB:
01238   //    %X = phi i1 [1],  [%X']
01239   //    %Y = icmp eq i32 %A, %B
01240   //    %Z = xor i1 %X, %Y
01241   //    br i1 %Z, ...
01242   //
01243   // Into:
01244   //  BB':
01245   //    %Y = icmp ne i32 %A, %B
01246   //    br i1 %Z, ...
01247 
01248   PredValueInfoTy XorOpValues;
01249   bool isLHS = true;
01250   if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
01251                                        WantInteger)) {
01252     assert(XorOpValues.empty());
01253     if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
01254                                          WantInteger))
01255       return false;
01256     isLHS = false;
01257   }
01258 
01259   assert(!XorOpValues.empty() &&
01260          "ComputeValueKnownInPredecessors returned true with no values");
01261 
01262   // Scan the information to see which is most popular: true or false.  The
01263   // predecessors can be of the set true, false, or undef.
01264   unsigned NumTrue = 0, NumFalse = 0;
01265   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
01266     if (isa<UndefValue>(XorOpValues[i].first))
01267       // Ignore undefs for the count.
01268       continue;
01269     if (cast<ConstantInt>(XorOpValues[i].first)->isZero())
01270       ++NumFalse;
01271     else
01272       ++NumTrue;
01273   }
01274 
01275   // Determine which value to split on, true, false, or undef if neither.
01276   ConstantInt *SplitVal = 0;
01277   if (NumTrue > NumFalse)
01278     SplitVal = ConstantInt::getTrue(BB->getContext());
01279   else if (NumTrue != 0 || NumFalse != 0)
01280     SplitVal = ConstantInt::getFalse(BB->getContext());
01281 
01282   // Collect all of the blocks that this can be folded into so that we can
01283   // factor this once and clone it once.
01284   SmallVector<BasicBlock*, 8> BlocksToFoldInto;
01285   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
01286     if (XorOpValues[i].first != SplitVal &&
01287         !isa<UndefValue>(XorOpValues[i].first))
01288       continue;
01289 
01290     BlocksToFoldInto.push_back(XorOpValues[i].second);
01291   }
01292 
01293   // If we inferred a value for all of the predecessors, then duplication won't
01294   // help us.  However, we can just replace the LHS or RHS with the constant.
01295   if (BlocksToFoldInto.size() ==
01296       cast<PHINode>(BB->front()).getNumIncomingValues()) {
01297     if (SplitVal == 0) {
01298       // If all preds provide undef, just nuke the xor, because it is undef too.
01299       BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
01300       BO->eraseFromParent();
01301     } else if (SplitVal->isZero()) {
01302       // If all preds provide 0, replace the xor with the other input.
01303       BO->replaceAllUsesWith(BO->getOperand(isLHS));
01304       BO->eraseFromParent();
01305     } else {
01306       // If all preds provide 1, set the computed value to 1.
01307       BO->setOperand(!isLHS, SplitVal);
01308     }
01309 
01310     return true;
01311   }
01312 
01313   // Try to duplicate BB into PredBB.
01314   return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
01315 }
01316 
01317 
01318 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
01319 /// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
01320 /// NewPred using the entries from OldPred (suitably mapped).
01321 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
01322                                             BasicBlock *OldPred,
01323                                             BasicBlock *NewPred,
01324                                      DenseMap<Instruction*, Value*> &ValueMap) {
01325   for (BasicBlock::iterator PNI = PHIBB->begin();
01326        PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
01327     // Ok, we have a PHI node.  Figure out what the incoming value was for the
01328     // DestBlock.
01329     Value *IV = PN->getIncomingValueForBlock(OldPred);
01330 
01331     // Remap the value if necessary.
01332     if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
01333       DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
01334       if (I != ValueMap.end())
01335         IV = I->second;
01336     }
01337 
01338     PN->addIncoming(IV, NewPred);
01339   }
01340 }
01341 
01342 /// ThreadEdge - We have decided that it is safe and profitable to factor the
01343 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
01344 /// across BB.  Transform the IR to reflect this change.
01345 bool JumpThreading::ThreadEdge(BasicBlock *BB,
01346                                const SmallVectorImpl<BasicBlock*> &PredBBs,
01347                                BasicBlock *SuccBB) {
01348   // If threading to the same block as we come from, we would infinite loop.
01349   if (SuccBB == BB) {
01350     DEBUG(dbgs() << "  Not threading across BB '" << BB->getName()
01351           << "' - would thread to self!\n");
01352     return false;
01353   }
01354 
01355   // If threading this would thread across a loop header, don't thread the edge.
01356   // See the comments above FindLoopHeaders for justifications and caveats.
01357   if (LoopHeaders.count(BB)) {
01358     DEBUG(dbgs() << "  Not threading across loop header BB '" << BB->getName()
01359           << "' to dest BB '" << SuccBB->getName()
01360           << "' - it might create an irreducible loop!\n");
01361     return false;
01362   }
01363 
01364   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB, Threshold);
01365   if (JumpThreadCost > Threshold) {
01366     DEBUG(dbgs() << "  Not threading BB '" << BB->getName()
01367           << "' - Cost is too high: " << JumpThreadCost << "\n");
01368     return false;
01369   }
01370 
01371   // And finally, do it!  Start by factoring the predecessors is needed.
01372   BasicBlock *PredBB;
01373   if (PredBBs.size() == 1)
01374     PredBB = PredBBs[0];
01375   else {
01376     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
01377           << " common predecessors.\n");
01378     PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
01379   }
01380 
01381   // And finally, do it!
01382   DEBUG(dbgs() << "  Threading edge from '" << PredBB->getName() << "' to '"
01383         << SuccBB->getName() << "' with cost: " << JumpThreadCost
01384         << ", across block:\n    "
01385         << *BB << "\n");
01386 
01387   LVI->threadEdge(PredBB, BB, SuccBB);
01388 
01389   // We are going to have to map operands from the original BB block to the new
01390   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
01391   // account for entry from PredBB.
01392   DenseMap<Instruction*, Value*> ValueMapping;
01393 
01394   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
01395                                          BB->getName()+".thread",
01396                                          BB->getParent(), BB);
01397   NewBB->moveAfter(PredBB);
01398 
01399   BasicBlock::iterator BI = BB->begin();
01400   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
01401     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
01402 
01403   // Clone the non-phi instructions of BB into NewBB, keeping track of the
01404   // mapping and using it to remap operands in the cloned instructions.
01405   for (; !isa<TerminatorInst>(BI); ++BI) {
01406     Instruction *New = BI->clone();
01407     New->setName(BI->getName());
01408     NewBB->getInstList().push_back(New);
01409     ValueMapping[BI] = New;
01410 
01411     // Remap operands to patch up intra-block references.
01412     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
01413       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
01414         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
01415         if (I != ValueMapping.end())
01416           New->setOperand(i, I->second);
01417       }
01418   }
01419 
01420   // We didn't copy the terminator from BB over to NewBB, because there is now
01421   // an unconditional jump to SuccBB.  Insert the unconditional jump.
01422   BranchInst *NewBI =BranchInst::Create(SuccBB, NewBB);
01423   NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
01424 
01425   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
01426   // PHI nodes for NewBB now.
01427   AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
01428 
01429   // If there were values defined in BB that are used outside the block, then we
01430   // now have to update all uses of the value to use either the original value,
01431   // the cloned value, or some PHI derived value.  This can require arbitrary
01432   // PHI insertion, of which we are prepared to do, clean these up now.
01433   SSAUpdater SSAUpdate;
01434   SmallVector<Use*, 16> UsesToRename;
01435   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
01436     // Scan all uses of this instruction to see if it is used outside of its
01437     // block, and if so, record them in UsesToRename.
01438     for (Use &U : I->uses()) {
01439       Instruction *User = cast<Instruction>(U.getUser());
01440       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
01441         if (UserPN->getIncomingBlock(U) == BB)
01442           continue;
01443       } else if (User->getParent() == BB)
01444         continue;
01445 
01446       UsesToRename.push_back(&U);
01447     }
01448 
01449     // If there are no uses outside the block, we're done with this instruction.
01450     if (UsesToRename.empty())
01451       continue;
01452 
01453     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
01454 
01455     // We found a use of I outside of BB.  Rename all uses of I that are outside
01456     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
01457     // with the two values we know.
01458     SSAUpdate.Initialize(I->getType(), I->getName());
01459     SSAUpdate.AddAvailableValue(BB, I);
01460     SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
01461 
01462     while (!UsesToRename.empty())
01463       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
01464     DEBUG(dbgs() << "\n");
01465   }
01466 
01467 
01468   // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
01469   // NewBB instead of BB.  This eliminates predecessors from BB, which requires
01470   // us to simplify any PHI nodes in BB.
01471   TerminatorInst *PredTerm = PredBB->getTerminator();
01472   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
01473     if (PredTerm->getSuccessor(i) == BB) {
01474       BB->removePredecessor(PredBB, true);
01475       PredTerm->setSuccessor(i, NewBB);
01476     }
01477 
01478   // At this point, the IR is fully up to date and consistent.  Do a quick scan
01479   // over the new instructions and zap any that are constants or dead.  This
01480   // frequently happens because of phi translation.
01481   SimplifyInstructionsInBlock(NewBB, DL, TLI);
01482 
01483   // Threaded an edge!
01484   ++NumThreads;
01485   return true;
01486 }
01487 
01488 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
01489 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
01490 /// If we can duplicate the contents of BB up into PredBB do so now, this
01491 /// improves the odds that the branch will be on an analyzable instruction like
01492 /// a compare.
01493 bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
01494                                  const SmallVectorImpl<BasicBlock *> &PredBBs) {
01495   assert(!PredBBs.empty() && "Can't handle an empty set");
01496 
01497   // If BB is a loop header, then duplicating this block outside the loop would
01498   // cause us to transform this into an irreducible loop, don't do this.
01499   // See the comments above FindLoopHeaders for justifications and caveats.
01500   if (LoopHeaders.count(BB)) {
01501     DEBUG(dbgs() << "  Not duplicating loop header '" << BB->getName()
01502           << "' into predecessor block '" << PredBBs[0]->getName()
01503           << "' - it might create an irreducible loop!\n");
01504     return false;
01505   }
01506 
01507   unsigned DuplicationCost = getJumpThreadDuplicationCost(BB, Threshold);
01508   if (DuplicationCost > Threshold) {
01509     DEBUG(dbgs() << "  Not duplicating BB '" << BB->getName()
01510           << "' - Cost is too high: " << DuplicationCost << "\n");
01511     return false;
01512   }
01513 
01514   // And finally, do it!  Start by factoring the predecessors is needed.
01515   BasicBlock *PredBB;
01516   if (PredBBs.size() == 1)
01517     PredBB = PredBBs[0];
01518   else {
01519     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
01520           << " common predecessors.\n");
01521     PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
01522   }
01523 
01524   // Okay, we decided to do this!  Clone all the instructions in BB onto the end
01525   // of PredBB.
01526   DEBUG(dbgs() << "  Duplicating block '" << BB->getName() << "' into end of '"
01527         << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
01528         << DuplicationCost << " block is:" << *BB << "\n");
01529 
01530   // Unless PredBB ends with an unconditional branch, split the edge so that we
01531   // can just clone the bits from BB into the end of the new PredBB.
01532   BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
01533 
01534   if (OldPredBranch == 0 || !OldPredBranch->isUnconditional()) {
01535     PredBB = SplitEdge(PredBB, BB, this);
01536     OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
01537   }
01538 
01539   // We are going to have to map operands from the original BB block into the
01540   // PredBB block.  Evaluate PHI nodes in BB.
01541   DenseMap<Instruction*, Value*> ValueMapping;
01542 
01543   BasicBlock::iterator BI = BB->begin();
01544   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
01545     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
01546 
01547   // Clone the non-phi instructions of BB into PredBB, keeping track of the
01548   // mapping and using it to remap operands in the cloned instructions.
01549   for (; BI != BB->end(); ++BI) {
01550     Instruction *New = BI->clone();
01551 
01552     // Remap operands to patch up intra-block references.
01553     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
01554       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
01555         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
01556         if (I != ValueMapping.end())
01557           New->setOperand(i, I->second);
01558       }
01559 
01560     // If this instruction can be simplified after the operands are updated,
01561     // just use the simplified value instead.  This frequently happens due to
01562     // phi translation.
01563     if (Value *IV = SimplifyInstruction(New, DL)) {
01564       delete New;
01565       ValueMapping[BI] = IV;
01566     } else {
01567       // Otherwise, insert the new instruction into the block.
01568       New->setName(BI->getName());
01569       PredBB->getInstList().insert(OldPredBranch, New);
01570       ValueMapping[BI] = New;
01571     }
01572   }
01573 
01574   // Check to see if the targets of the branch had PHI nodes. If so, we need to
01575   // add entries to the PHI nodes for branch from PredBB now.
01576   BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
01577   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
01578                                   ValueMapping);
01579   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
01580                                   ValueMapping);
01581 
01582   // If there were values defined in BB that are used outside the block, then we
01583   // now have to update all uses of the value to use either the original value,
01584   // the cloned value, or some PHI derived value.  This can require arbitrary
01585   // PHI insertion, of which we are prepared to do, clean these up now.
01586   SSAUpdater SSAUpdate;
01587   SmallVector<Use*, 16> UsesToRename;
01588   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
01589     // Scan all uses of this instruction to see if it is used outside of its
01590     // block, and if so, record them in UsesToRename.
01591     for (Use &U : I->uses()) {
01592       Instruction *User = cast<Instruction>(U.getUser());
01593       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
01594         if (UserPN->getIncomingBlock(U) == BB)
01595           continue;
01596       } else if (User->getParent() == BB)
01597         continue;
01598 
01599       UsesToRename.push_back(&U);
01600     }
01601 
01602     // If there are no uses outside the block, we're done with this instruction.
01603     if (UsesToRename.empty())
01604       continue;
01605 
01606     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
01607 
01608     // We found a use of I outside of BB.  Rename all uses of I that are outside
01609     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
01610     // with the two values we know.
01611     SSAUpdate.Initialize(I->getType(), I->getName());
01612     SSAUpdate.AddAvailableValue(BB, I);
01613     SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
01614 
01615     while (!UsesToRename.empty())
01616       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
01617     DEBUG(dbgs() << "\n");
01618   }
01619 
01620   // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
01621   // that we nuked.
01622   BB->removePredecessor(PredBB, true);
01623 
01624   // Remove the unconditional branch at the end of the PredBB block.
01625   OldPredBranch->eraseFromParent();
01626 
01627   ++NumDupes;
01628   return true;
01629 }
01630 
01631 /// TryToUnfoldSelect - Look for blocks of the form
01632 /// bb1:
01633 ///   %a = select
01634 ///   br bb
01635 ///
01636 /// bb2:
01637 ///   %p = phi [%a, %bb] ...
01638 ///   %c = icmp %p
01639 ///   br i1 %c
01640 ///
01641 /// And expand the select into a branch structure if one of its arms allows %c
01642 /// to be folded. This later enables threading from bb1 over bb2.
01643 bool JumpThreading::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
01644   BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
01645   PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
01646   Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
01647 
01648   if (!CondBr || !CondBr->isConditional() || !CondLHS ||
01649       CondLHS->getParent() != BB)
01650     return false;
01651 
01652   for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
01653     BasicBlock *Pred = CondLHS->getIncomingBlock(I);
01654     SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
01655 
01656     // Look if one of the incoming values is a select in the corresponding
01657     // predecessor.
01658     if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
01659       continue;
01660 
01661     BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
01662     if (!PredTerm || !PredTerm->isUnconditional())
01663       continue;
01664 
01665     // Now check if one of the select values would allow us to constant fold the
01666     // terminator in BB. We don't do the transform if both sides fold, those
01667     // cases will be threaded in any case.
01668     LazyValueInfo::Tristate LHSFolds =
01669         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
01670                                 CondRHS, Pred, BB);
01671     LazyValueInfo::Tristate RHSFolds =
01672         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
01673                                 CondRHS, Pred, BB);
01674     if ((LHSFolds != LazyValueInfo::Unknown ||
01675          RHSFolds != LazyValueInfo::Unknown) &&
01676         LHSFolds != RHSFolds) {
01677       // Expand the select.
01678       //
01679       // Pred --
01680       //  |    v
01681       //  |  NewBB
01682       //  |    |
01683       //  |-----
01684       //  v
01685       // BB
01686       BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
01687                                              BB->getParent(), BB);
01688       // Move the unconditional branch to NewBB.
01689       PredTerm->removeFromParent();
01690       NewBB->getInstList().insert(NewBB->end(), PredTerm);
01691       // Create a conditional branch and update PHI nodes.
01692       BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
01693       CondLHS->setIncomingValue(I, SI->getFalseValue());
01694       CondLHS->addIncoming(SI->getTrueValue(), NewBB);
01695       // The select is now dead.
01696       SI->eraseFromParent();
01697 
01698       // Update any other PHI nodes in BB.
01699       for (BasicBlock::iterator BI = BB->begin();
01700            PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
01701         if (Phi != CondLHS)
01702           Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
01703       return true;
01704     }
01705   }
01706   return false;
01707 }