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