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