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